Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

pirms 5 gadiem
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (c) 2009 Google Inc. All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Does google-lint on c++ files.
  31. The goal of this script is to identify places in the code that *may*
  32. be in non-compliance with google style. It does not attempt to fix
  33. up these problems -- the point is to educate. It does also not
  34. attempt to find all problems, or to ensure that everything it does
  35. find is legitimately a problem.
  36. In particular, we can get very confused by /* and // inside strings!
  37. We do a small hack, which is to ignore //'s with "'s after them on the
  38. same line, but it is far from perfect (in either direction).
  39. """
  40. import codecs
  41. import copy
  42. import getopt
  43. import math # for log
  44. import os
  45. import re
  46. import sre_compile
  47. import string
  48. import sys
  49. import unicodedata
  50. _USAGE = """
  51. Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
  52. [--counting=total|toplevel|detailed] [--root=subdir]
  53. [--linelength=digits] [--headers=x,y,...]
  54. <file> [file] ...
  55. The style guidelines this tries to follow are those in
  56. https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
  57. Every problem is given a confidence score from 1-5, with 5 meaning we are
  58. certain of the problem, and 1 meaning it could be a legitimate construct.
  59. This will miss some errors, and is not a substitute for a code review.
  60. To suppress false-positive errors of a certain category, add a
  61. 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)
  62. suppresses errors of all categories on that line.
  63. The files passed in will be linted; at least one file must be provided.
  64. Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the
  65. extensions with the --extensions flag.
  66. Flags:
  67. output=vs7
  68. By default, the output is formatted to ease emacs parsing. Visual Studio
  69. compatible output (vs7) may also be used. Other formats are unsupported.
  70. verbose=#
  71. Specify a number 0-5 to restrict errors to certain verbosity levels.
  72. filter=-x,+y,...
  73. Specify a comma-separated list of category-filters to apply: only
  74. error messages whose category names pass the filters will be printed.
  75. (Category names are printed with the message and look like
  76. "[whitespace/indent]".) Filters are evaluated left to right.
  77. "-FOO" and "FOO" means "do not print categories that start with FOO".
  78. "+FOO" means "do print categories that start with FOO".
  79. Examples: --filter=-whitespace,+whitespace/braces
  80. --filter=whitespace,runtime/printf,+runtime/printf_format
  81. --filter=-,+build/include_what_you_use
  82. To see a list of all the categories used in cpplint, pass no arg:
  83. --filter=
  84. counting=total|toplevel|detailed
  85. The total number of errors found is always printed. If
  86. 'toplevel' is provided, then the count of errors in each of
  87. the top-level categories like 'build' and 'whitespace' will
  88. also be printed. If 'detailed' is provided, then a count
  89. is provided for each category like 'build/class'.
  90. root=subdir
  91. The root directory used for deriving header guard CPP variable.
  92. By default, the header guard CPP variable is calculated as the relative
  93. path to the directory that contains .git, .hg, or .svn. When this flag
  94. is specified, the relative path is calculated from the specified
  95. directory. If the specified directory does not exist, this flag is
  96. ignored.
  97. Examples:
  98. Assuming that src/.git exists, the header guard CPP variables for
  99. src/chrome/browser/ui/browser.h are:
  100. No flag => CHROME_BROWSER_UI_BROWSER_H_
  101. --root=chrome => BROWSER_UI_BROWSER_H_
  102. --root=chrome/browser => UI_BROWSER_H_
  103. linelength=digits
  104. This is the allowed line length for the project. The default value is
  105. 80 characters.
  106. Examples:
  107. --linelength=120
  108. extensions=extension,extension,...
  109. The allowed file extensions that cpplint will check
  110. Examples:
  111. --extensions=hpp,cpp
  112. headers=x,y,...
  113. The header extensions that cpplint will treat as .h in checks. Values are
  114. automatically added to --extensions list.
  115. Examples:
  116. --headers=hpp,hxx
  117. --headers=hpp
  118. cpplint.py supports per-directory configurations specified in CPPLINT.cfg
  119. files. CPPLINT.cfg file can contain a number of key=value pairs.
  120. Currently the following options are supported:
  121. set noparent
  122. filter=+filter1,-filter2,...
  123. exclude_files=regex
  124. linelength=80
  125. root=subdir
  126. headers=x,y,...
  127. "set noparent" option prevents cpplint from traversing directory tree
  128. upwards looking for more .cfg files in parent directories. This option
  129. is usually placed in the top-level project directory.
  130. The "filter" option is similar in function to --filter flag. It specifies
  131. message filters in addition to the |_DEFAULT_FILTERS| and those specified
  132. through --filter command-line flag.
  133. "exclude_files" allows to specify a regular expression to be matched against
  134. a file name. If the expression matches, the file is skipped and not run
  135. through liner.
  136. "linelength" allows to specify the allowed line length for the project.
  137. The "root" option is similar in function to the --root flag (see example
  138. above).
  139. The "headers" option is similar in function to the --headers flag
  140. (see example above).
  141. CPPLINT.cfg has an effect on files in the same directory and all
  142. sub-directories, unless overridden by a nested configuration file.
  143. Example file:
  144. filter=-build/include_order,+build/include_alpha
  145. exclude_files=.*\.cc
  146. The above example disables build/include_order warning and enables
  147. build/include_alpha as well as excludes all .cc from being
  148. processed by linter, in the current directory (where the .cfg
  149. file is located) and all sub-directories.
  150. """
  151. # We categorize each error message we print. Here are the categories.
  152. # We want an explicit list so we can list them all in cpplint --filter=.
  153. # If you add a new error message with a new category, add it to the list
  154. # here! cpplint_unittest.py should tell you if you forget to do this.
  155. _ERROR_CATEGORIES = [
  156. 'build/class',
  157. 'build/c++11',
  158. 'build/c++14',
  159. 'build/c++tr1',
  160. 'build/deprecated',
  161. 'build/endif_comment',
  162. 'build/explicit_make_pair',
  163. 'build/forward_decl',
  164. 'build/header_guard',
  165. 'build/include',
  166. 'build/include_alpha',
  167. 'build/include_order',
  168. 'build/include_what_you_use',
  169. 'build/namespaces',
  170. 'build/printf_format',
  171. 'build/storage_class',
  172. 'legal/copyright',
  173. 'readability/alt_tokens',
  174. 'readability/braces',
  175. 'readability/casting',
  176. 'readability/check',
  177. 'readability/constructors',
  178. 'readability/fn_size',
  179. 'readability/inheritance',
  180. 'readability/multiline_comment',
  181. 'readability/multiline_string',
  182. 'readability/namespace',
  183. 'readability/nolint',
  184. 'readability/nul',
  185. 'readability/strings',
  186. 'readability/todo',
  187. 'readability/utf8',
  188. 'runtime/arrays',
  189. 'runtime/casting',
  190. 'runtime/explicit',
  191. 'runtime/int',
  192. 'runtime/init',
  193. 'runtime/invalid_increment',
  194. 'runtime/member_string_references',
  195. 'runtime/memset',
  196. 'runtime/indentation_namespace',
  197. 'runtime/operator',
  198. 'runtime/printf',
  199. 'runtime/printf_format',
  200. 'runtime/references',
  201. 'runtime/string',
  202. 'runtime/threadsafe_fn',
  203. 'runtime/vlog',
  204. 'whitespace/blank_line',
  205. 'whitespace/braces',
  206. 'whitespace/comma',
  207. 'whitespace/comments',
  208. 'whitespace/empty_conditional_body',
  209. 'whitespace/empty_if_body',
  210. 'whitespace/empty_loop_body',
  211. 'whitespace/end_of_line',
  212. 'whitespace/ending_newline',
  213. 'whitespace/forcolon',
  214. 'whitespace/indent',
  215. 'whitespace/line_length',
  216. 'whitespace/newline',
  217. 'whitespace/operators',
  218. 'whitespace/parens',
  219. 'whitespace/semicolon',
  220. 'whitespace/tab',
  221. 'whitespace/todo',
  222. ]
  223. # These error categories are no longer enforced by cpplint, but for backwards-
  224. # compatibility they may still appear in NOLINT comments.
  225. _LEGACY_ERROR_CATEGORIES = [
  226. 'readability/streams',
  227. 'readability/function',
  228. ]
  229. # The default state of the category filter. This is overridden by the --filter=
  230. # flag. By default all errors are on, so only add here categories that should be
  231. # off by default (i.e., categories that must be enabled by the --filter= flags).
  232. # All entries here should start with a '-' or '+', as in the --filter= flag.
  233. _DEFAULT_FILTERS = ['-build/include_alpha']
  234. # The default list of categories suppressed for C (not C++) files.
  235. _DEFAULT_C_SUPPRESSED_CATEGORIES = [
  236. 'readability/casting',
  237. ]
  238. # The default list of categories suppressed for Linux Kernel files.
  239. _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [
  240. 'whitespace/tab',
  241. ]
  242. # We used to check for high-bit characters, but after much discussion we
  243. # decided those were OK, as long as they were in UTF-8 and didn't represent
  244. # hard-coded international strings, which belong in a separate i18n file.
  245. # C++ headers
  246. _CPP_HEADERS = frozenset([
  247. # Legacy
  248. 'algobase.h',
  249. 'algo.h',
  250. 'alloc.h',
  251. 'builtinbuf.h',
  252. 'bvector.h',
  253. 'complex.h',
  254. 'defalloc.h',
  255. 'deque.h',
  256. 'editbuf.h',
  257. 'fstream.h',
  258. 'function.h',
  259. 'hash_map',
  260. 'hash_map.h',
  261. 'hash_set',
  262. 'hash_set.h',
  263. 'hashtable.h',
  264. 'heap.h',
  265. 'indstream.h',
  266. 'iomanip.h',
  267. 'iostream.h',
  268. 'istream.h',
  269. 'iterator.h',
  270. 'list.h',
  271. 'map.h',
  272. 'multimap.h',
  273. 'multiset.h',
  274. 'ostream.h',
  275. 'pair.h',
  276. 'parsestream.h',
  277. 'pfstream.h',
  278. 'procbuf.h',
  279. 'pthread_alloc',
  280. 'pthread_alloc.h',
  281. 'rope',
  282. 'rope.h',
  283. 'ropeimpl.h',
  284. 'set.h',
  285. 'slist',
  286. 'slist.h',
  287. 'stack.h',
  288. 'stdiostream.h',
  289. 'stl_alloc.h',
  290. 'stl_relops.h',
  291. 'streambuf.h',
  292. 'stream.h',
  293. 'strfile.h',
  294. 'strstream.h',
  295. 'tempbuf.h',
  296. 'tree.h',
  297. 'type_traits.h',
  298. 'vector.h',
  299. # 17.6.1.2 C++ library headers
  300. 'algorithm',
  301. 'array',
  302. 'atomic',
  303. 'bitset',
  304. 'chrono',
  305. 'codecvt',
  306. 'complex',
  307. 'condition_variable',
  308. 'deque',
  309. 'exception',
  310. 'forward_list',
  311. 'fstream',
  312. 'functional',
  313. 'future',
  314. 'initializer_list',
  315. 'iomanip',
  316. 'ios',
  317. 'iosfwd',
  318. 'iostream',
  319. 'istream',
  320. 'iterator',
  321. 'limits',
  322. 'list',
  323. 'locale',
  324. 'map',
  325. 'memory',
  326. 'mutex',
  327. 'new',
  328. 'numeric',
  329. 'ostream',
  330. 'queue',
  331. 'random',
  332. 'ratio',
  333. 'regex',
  334. 'scoped_allocator',
  335. 'set',
  336. 'sstream',
  337. 'stack',
  338. 'stdexcept',
  339. 'streambuf',
  340. 'string',
  341. 'strstream',
  342. 'system_error',
  343. 'thread',
  344. 'tuple',
  345. 'typeindex',
  346. 'typeinfo',
  347. 'type_traits',
  348. 'unordered_map',
  349. 'unordered_set',
  350. 'utility',
  351. 'valarray',
  352. 'vector',
  353. # 17.6.1.2 C++ headers for C library facilities
  354. 'cassert',
  355. 'ccomplex',
  356. 'cctype',
  357. 'cerrno',
  358. 'cfenv',
  359. 'cfloat',
  360. 'cinttypes',
  361. 'ciso646',
  362. 'climits',
  363. 'clocale',
  364. 'cmath',
  365. 'csetjmp',
  366. 'csignal',
  367. 'cstdalign',
  368. 'cstdarg',
  369. 'cstdbool',
  370. 'cstddef',
  371. 'cstdint',
  372. 'cstdio',
  373. 'cstdlib',
  374. 'cstring',
  375. 'ctgmath',
  376. 'ctime',
  377. 'cuchar',
  378. 'cwchar',
  379. 'cwctype',
  380. ])
  381. # Type names
  382. _TYPES = re.compile(
  383. r'^(?:'
  384. # [dcl.type.simple]
  385. r'(char(16_t|32_t)?)|wchar_t|'
  386. r'bool|short|int|long|signed|unsigned|float|double|'
  387. # [support.types]
  388. r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|'
  389. # [cstdint.syn]
  390. r'(u?int(_fast|_least)?(8|16|32|64)_t)|'
  391. r'(u?int(max|ptr)_t)|'
  392. r')$')
  393. # These headers are excluded from [build/include] and [build/include_order]
  394. # checks:
  395. # - Anything not following google file name conventions (containing an
  396. # uppercase character, such as Python.h or nsStringAPI.h, for example).
  397. # - Lua headers.
  398. _THIRD_PARTY_HEADERS_PATTERN = re.compile(
  399. r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
  400. # Pattern for matching FileInfo.BaseName() against test file name
  401. _TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$'
  402. # Pattern that matches only complete whitespace, possibly across multiple lines.
  403. _EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL)
  404. # Assertion macros. These are defined in base/logging.h and
  405. # testing/base/public/gunit.h.
  406. _CHECK_MACROS = [
  407. 'DCHECK', 'CHECK',
  408. 'EXPECT_TRUE', 'ASSERT_TRUE',
  409. 'EXPECT_FALSE', 'ASSERT_FALSE',
  410. ]
  411. # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
  412. _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
  413. for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
  414. ('>=', 'GE'), ('>', 'GT'),
  415. ('<=', 'LE'), ('<', 'LT')]:
  416. _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
  417. _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
  418. _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
  419. _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
  420. for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
  421. ('>=', 'LT'), ('>', 'LE'),
  422. ('<=', 'GT'), ('<', 'GE')]:
  423. _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
  424. _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
  425. # Alternative tokens and their replacements. For full list, see section 2.5
  426. # Alternative tokens [lex.digraph] in the C++ standard.
  427. #
  428. # Digraphs (such as '%:') are not included here since it's a mess to
  429. # match those on a word boundary.
  430. _ALT_TOKEN_REPLACEMENT = {
  431. 'and': '&&',
  432. 'bitor': '|',
  433. 'or': '||',
  434. 'xor': '^',
  435. 'compl': '~',
  436. 'bitand': '&',
  437. 'and_eq': '&=',
  438. 'or_eq': '|=',
  439. 'xor_eq': '^=',
  440. 'not': '!',
  441. 'not_eq': '!='
  442. }
  443. # Compile regular expression that matches all the above keywords. The "[ =()]"
  444. # bit is meant to avoid matching these keywords outside of boolean expressions.
  445. #
  446. # False positives include C-style multi-line comments and multi-line strings
  447. # but those have always been troublesome for cpplint.
  448. _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
  449. r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
  450. # These constants define types of headers for use with
  451. # _IncludeState.CheckNextIncludeOrder().
  452. _C_SYS_HEADER = 1
  453. _CPP_SYS_HEADER = 2
  454. _LIKELY_MY_HEADER = 3
  455. _POSSIBLE_MY_HEADER = 4
  456. _OTHER_HEADER = 5
  457. # These constants define the current inline assembly state
  458. _NO_ASM = 0 # Outside of inline assembly block
  459. _INSIDE_ASM = 1 # Inside inline assembly block
  460. _END_ASM = 2 # Last line of inline assembly block
  461. _BLOCK_ASM = 3 # The whole block is an inline assembly block
  462. # Match start of assembly blocks
  463. _MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
  464. r'(?:\s+(volatile|__volatile__))?'
  465. r'\s*[{(]')
  466. # Match strings that indicate we're working on a C (not C++) file.
  467. _SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|'
  468. r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))')
  469. # Match string that indicates we're working on a Linux Kernel file.
  470. _SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)')
  471. _regexp_compile_cache = {}
  472. # {str, set(int)}: a map from error categories to sets of linenumbers
  473. # on which those errors are expected and should be suppressed.
  474. _error_suppressions = {}
  475. # The root directory used for deriving header guard CPP variable.
  476. # This is set by --root flag.
  477. _root = None
  478. # The allowed line length of files.
  479. # This is set by --linelength flag.
  480. _line_length = 80
  481. # The allowed extensions for file names
  482. # This is set by --extensions flag.
  483. _valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])
  484. # Treat all headers starting with 'h' equally: .h, .hpp, .hxx etc.
  485. # This is set by --headers flag.
  486. _hpp_headers = set(['h'])
  487. # {str, bool}: a map from error categories to booleans which indicate if the
  488. # category should be suppressed for every line.
  489. _global_error_suppressions = {}
  490. def ProcessHppHeadersOption(val):
  491. global _hpp_headers
  492. try:
  493. _hpp_headers = set(val.split(','))
  494. # Automatically append to extensions list so it does not have to be set 2 times
  495. _valid_extensions.update(_hpp_headers)
  496. except ValueError:
  497. PrintUsage('Header extensions must be comma seperated list.')
  498. def IsHeaderExtension(file_extension):
  499. return file_extension in _hpp_headers
  500. def ParseNolintSuppressions(filename, raw_line, linenum, error):
  501. """Updates the global list of line error-suppressions.
  502. Parses any NOLINT comments on the current line, updating the global
  503. error_suppressions store. Reports an error if the NOLINT comment
  504. was malformed.
  505. Args:
  506. filename: str, the name of the input file.
  507. raw_line: str, the line of input text, with comments.
  508. linenum: int, the number of the current line.
  509. error: function, an error handler.
  510. """
  511. matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
  512. if matched:
  513. if matched.group(1):
  514. suppressed_line = linenum + 1
  515. else:
  516. suppressed_line = linenum
  517. category = matched.group(2)
  518. if category in (None, '(*)'): # => "suppress all"
  519. _error_suppressions.setdefault(None, set()).add(suppressed_line)
  520. else:
  521. if category.startswith('(') and category.endswith(')'):
  522. category = category[1:-1]
  523. if category in _ERROR_CATEGORIES:
  524. _error_suppressions.setdefault(category, set()).add(suppressed_line)
  525. elif category not in _LEGACY_ERROR_CATEGORIES:
  526. error(filename, linenum, 'readability/nolint', 5,
  527. 'Unknown NOLINT error category: %s' % category)
  528. def ProcessGlobalSuppresions(lines):
  529. """Updates the list of global error suppressions.
  530. Parses any lint directives in the file that have global effect.
  531. Args:
  532. lines: An array of strings, each representing a line of the file, with the
  533. last element being empty if the file is terminated with a newline.
  534. """
  535. for line in lines:
  536. if _SEARCH_C_FILE.search(line):
  537. for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
  538. _global_error_suppressions[category] = True
  539. if _SEARCH_KERNEL_FILE.search(line):
  540. for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
  541. _global_error_suppressions[category] = True
  542. def ResetNolintSuppressions():
  543. """Resets the set of NOLINT suppressions to empty."""
  544. _error_suppressions.clear()
  545. _global_error_suppressions.clear()
  546. def IsErrorSuppressedByNolint(category, linenum):
  547. """Returns true if the specified error category is suppressed on this line.
  548. Consults the global error_suppressions map populated by
  549. ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
  550. Args:
  551. category: str, the category of the error.
  552. linenum: int, the current line number.
  553. Returns:
  554. bool, True iff the error should be suppressed due to a NOLINT comment or
  555. global suppression.
  556. """
  557. return (_global_error_suppressions.get(category, False) or
  558. linenum in _error_suppressions.get(category, set()) or
  559. linenum in _error_suppressions.get(None, set()))
  560. def Match(pattern, s):
  561. """Matches the string with the pattern, caching the compiled regexp."""
  562. # The regexp compilation caching is inlined in both Match and Search for
  563. # performance reasons; factoring it out into a separate function turns out
  564. # to be noticeably expensive.
  565. if pattern not in _regexp_compile_cache:
  566. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  567. return _regexp_compile_cache[pattern].match(s)
  568. def ReplaceAll(pattern, rep, s):
  569. """Replaces instances of pattern in a string with a replacement.
  570. The compiled regex is kept in a cache shared by Match and Search.
  571. Args:
  572. pattern: regex pattern
  573. rep: replacement text
  574. s: search string
  575. Returns:
  576. string with replacements made (or original string if no replacements)
  577. """
  578. if pattern not in _regexp_compile_cache:
  579. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  580. return _regexp_compile_cache[pattern].sub(rep, s)
  581. def Search(pattern, s):
  582. """Searches the string for the pattern, caching the compiled regexp."""
  583. if pattern not in _regexp_compile_cache:
  584. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  585. return _regexp_compile_cache[pattern].search(s)
  586. def _IsSourceExtension(s):
  587. """File extension (excluding dot) matches a source file extension."""
  588. return s in ('c', 'cc', 'cpp', 'cxx')
  589. class _IncludeState(object):
  590. """Tracks line numbers for includes, and the order in which includes appear.
  591. include_list contains list of lists of (header, line number) pairs.
  592. It's a lists of lists rather than just one flat list to make it
  593. easier to update across preprocessor boundaries.
  594. Call CheckNextIncludeOrder() once for each header in the file, passing
  595. in the type constants defined above. Calls in an illegal order will
  596. raise an _IncludeError with an appropriate error message.
  597. """
  598. # self._section will move monotonically through this set. If it ever
  599. # needs to move backwards, CheckNextIncludeOrder will raise an error.
  600. _INITIAL_SECTION = 0
  601. _MY_H_SECTION = 1
  602. _C_SECTION = 2
  603. _CPP_SECTION = 3
  604. _OTHER_H_SECTION = 4
  605. _TYPE_NAMES = {
  606. _C_SYS_HEADER: 'C system header',
  607. _CPP_SYS_HEADER: 'C++ system header',
  608. _LIKELY_MY_HEADER: 'header this file implements',
  609. _POSSIBLE_MY_HEADER: 'header this file may implement',
  610. _OTHER_HEADER: 'other header',
  611. }
  612. _SECTION_NAMES = {
  613. _INITIAL_SECTION: "... nothing. (This can't be an error.)",
  614. _MY_H_SECTION: 'a header this file implements',
  615. _C_SECTION: 'C system header',
  616. _CPP_SECTION: 'C++ system header',
  617. _OTHER_H_SECTION: 'other header',
  618. }
  619. def __init__(self):
  620. self.include_list = [[]]
  621. self.ResetSection('')
  622. def FindHeader(self, header):
  623. """Check if a header has already been included.
  624. Args:
  625. header: header to check.
  626. Returns:
  627. Line number of previous occurrence, or -1 if the header has not
  628. been seen before.
  629. """
  630. for section_list in self.include_list:
  631. for f in section_list:
  632. if f[0] == header:
  633. return f[1]
  634. return -1
  635. def ResetSection(self, directive):
  636. """Reset section checking for preprocessor directive.
  637. Args:
  638. directive: preprocessor directive (e.g. "if", "else").
  639. """
  640. # The name of the current section.
  641. self._section = self._INITIAL_SECTION
  642. # The path of last found header.
  643. self._last_header = ''
  644. # Update list of includes. Note that we never pop from the
  645. # include list.
  646. if directive in ('if', 'ifdef', 'ifndef'):
  647. self.include_list.append([])
  648. elif directive in ('else', 'elif'):
  649. self.include_list[-1] = []
  650. def SetLastHeader(self, header_path):
  651. self._last_header = header_path
  652. def CanonicalizeAlphabeticalOrder(self, header_path):
  653. """Returns a path canonicalized for alphabetical comparison.
  654. - replaces "-" with "_" so they both cmp the same.
  655. - removes '-inl' since we don't require them to be after the main header.
  656. - lowercase everything, just in case.
  657. Args:
  658. header_path: Path to be canonicalized.
  659. Returns:
  660. Canonicalized path.
  661. """
  662. return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
  663. def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
  664. """Check if a header is in alphabetical order with the previous header.
  665. Args:
  666. clean_lines: A CleansedLines instance containing the file.
  667. linenum: The number of the line to check.
  668. header_path: Canonicalized header to be checked.
  669. Returns:
  670. Returns true if the header is in alphabetical order.
  671. """
  672. # If previous section is different from current section, _last_header will
  673. # be reset to empty string, so it's always less than current header.
  674. #
  675. # If previous line was a blank line, assume that the headers are
  676. # intentionally sorted the way they are.
  677. if (self._last_header > header_path and
  678. Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
  679. return False
  680. return True
  681. def CheckNextIncludeOrder(self, header_type):
  682. """Returns a non-empty error message if the next header is out of order.
  683. This function also updates the internal state to be ready to check
  684. the next include.
  685. Args:
  686. header_type: One of the _XXX_HEADER constants defined above.
  687. Returns:
  688. The empty string if the header is in the right order, or an
  689. error message describing what's wrong.
  690. """
  691. error_message = ('Found %s after %s' %
  692. (self._TYPE_NAMES[header_type],
  693. self._SECTION_NAMES[self._section]))
  694. last_section = self._section
  695. if header_type == _C_SYS_HEADER:
  696. if self._section <= self._C_SECTION:
  697. self._section = self._C_SECTION
  698. else:
  699. self._last_header = ''
  700. return error_message
  701. elif header_type == _CPP_SYS_HEADER:
  702. if self._section <= self._CPP_SECTION:
  703. self._section = self._CPP_SECTION
  704. else:
  705. self._last_header = ''
  706. return error_message
  707. elif header_type == _LIKELY_MY_HEADER:
  708. if self._section <= self._MY_H_SECTION:
  709. self._section = self._MY_H_SECTION
  710. else:
  711. self._section = self._OTHER_H_SECTION
  712. elif header_type == _POSSIBLE_MY_HEADER:
  713. if self._section <= self._MY_H_SECTION:
  714. self._section = self._MY_H_SECTION
  715. else:
  716. # This will always be the fallback because we're not sure
  717. # enough that the header is associated with this file.
  718. self._section = self._OTHER_H_SECTION
  719. else:
  720. assert header_type == _OTHER_HEADER
  721. self._section = self._OTHER_H_SECTION
  722. if last_section != self._section:
  723. self._last_header = ''
  724. return ''
  725. class _CppLintState(object):
  726. """Maintains module-wide state.."""
  727. def __init__(self):
  728. self.verbose_level = 1 # global setting.
  729. self.error_count = 0 # global count of reported errors
  730. # filters to apply when emitting error messages
  731. self.filters = _DEFAULT_FILTERS[:]
  732. # backup of filter list. Used to restore the state after each file.
  733. self._filters_backup = self.filters[:]
  734. self.counting = 'total' # In what way are we counting errors?
  735. self.errors_by_category = {} # string to int dict storing error counts
  736. # output format:
  737. # "emacs" - format that emacs can parse (default)
  738. # "vs7" - format that Microsoft Visual Studio 7 can parse
  739. self.output_format = 'emacs'
  740. def SetOutputFormat(self, output_format):
  741. """Sets the output format for errors."""
  742. self.output_format = output_format
  743. def SetVerboseLevel(self, level):
  744. """Sets the module's verbosity, and returns the previous setting."""
  745. last_verbose_level = self.verbose_level
  746. self.verbose_level = level
  747. return last_verbose_level
  748. def SetCountingStyle(self, counting_style):
  749. """Sets the module's counting options."""
  750. self.counting = counting_style
  751. def SetFilters(self, filters):
  752. """Sets the error-message filters.
  753. These filters are applied when deciding whether to emit a given
  754. error message.
  755. Args:
  756. filters: A string of comma-separated filters (eg "+whitespace/indent").
  757. Each filter should start with + or -; else we die.
  758. Raises:
  759. ValueError: The comma-separated filters did not all start with '+' or '-'.
  760. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
  761. """
  762. # Default filters always have less priority than the flag ones.
  763. self.filters = _DEFAULT_FILTERS[:]
  764. self.AddFilters(filters)
  765. def AddFilters(self, filters):
  766. """ Adds more filters to the existing list of error-message filters. """
  767. for filt in filters.split(','):
  768. clean_filt = filt.strip()
  769. if clean_filt:
  770. self.filters.append(clean_filt)
  771. for filt in self.filters:
  772. if not (filt.startswith('+') or filt.startswith('-')):
  773. raise ValueError('Every filter in --filters must start with + or -'
  774. ' (%s does not)' % filt)
  775. def BackupFilters(self):
  776. """ Saves the current filter list to backup storage."""
  777. self._filters_backup = self.filters[:]
  778. def RestoreFilters(self):
  779. """ Restores filters previously backed up."""
  780. self.filters = self._filters_backup[:]
  781. def ResetErrorCounts(self):
  782. """Sets the module's error statistic back to zero."""
  783. self.error_count = 0
  784. self.errors_by_category = {}
  785. def IncrementErrorCount(self, category):
  786. """Bumps the module's error statistic."""
  787. self.error_count += 1
  788. if self.counting in ('toplevel', 'detailed'):
  789. if self.counting != 'detailed':
  790. category = category.split('/')[0]
  791. if category not in self.errors_by_category:
  792. self.errors_by_category[category] = 0
  793. self.errors_by_category[category] += 1
  794. def PrintErrorCounts(self):
  795. """Print a summary of errors by category, and the total."""
  796. for category, count in self.errors_by_category.iteritems():
  797. sys.stderr.write('Category \'%s\' errors found: %d\n' %
  798. (category, count))
  799. sys.stdout.write('Total errors found: %d\n' % self.error_count)
  800. _cpplint_state = _CppLintState()
  801. def _OutputFormat():
  802. """Gets the module's output format."""
  803. return _cpplint_state.output_format
  804. def _SetOutputFormat(output_format):
  805. """Sets the module's output format."""
  806. _cpplint_state.SetOutputFormat(output_format)
  807. def _VerboseLevel():
  808. """Returns the module's verbosity setting."""
  809. return _cpplint_state.verbose_level
  810. def _SetVerboseLevel(level):
  811. """Sets the module's verbosity, and returns the previous setting."""
  812. return _cpplint_state.SetVerboseLevel(level)
  813. def _SetCountingStyle(level):
  814. """Sets the module's counting options."""
  815. _cpplint_state.SetCountingStyle(level)
  816. def _Filters():
  817. """Returns the module's list of output filters, as a list."""
  818. return _cpplint_state.filters
  819. def _SetFilters(filters):
  820. """Sets the module's error-message filters.
  821. These filters are applied when deciding whether to emit a given
  822. error message.
  823. Args:
  824. filters: A string of comma-separated filters (eg "whitespace/indent").
  825. Each filter should start with + or -; else we die.
  826. """
  827. _cpplint_state.SetFilters(filters)
  828. def _AddFilters(filters):
  829. """Adds more filter overrides.
  830. Unlike _SetFilters, this function does not reset the current list of filters
  831. available.
  832. Args:
  833. filters: A string of comma-separated filters (eg "whitespace/indent").
  834. Each filter should start with + or -; else we die.
  835. """
  836. _cpplint_state.AddFilters(filters)
  837. def _BackupFilters():
  838. """ Saves the current filter list to backup storage."""
  839. _cpplint_state.BackupFilters()
  840. def _RestoreFilters():
  841. """ Restores filters previously backed up."""
  842. _cpplint_state.RestoreFilters()
  843. class _FunctionState(object):
  844. """Tracks current function name and the number of lines in its body."""
  845. _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
  846. _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
  847. def __init__(self):
  848. self.in_a_function = False
  849. self.lines_in_function = 0
  850. self.current_function = ''
  851. def Begin(self, function_name):
  852. """Start analyzing function body.
  853. Args:
  854. function_name: The name of the function being tracked.
  855. """
  856. self.in_a_function = True
  857. self.lines_in_function = 0
  858. self.current_function = function_name
  859. def Count(self):
  860. """Count line in current function body."""
  861. if self.in_a_function:
  862. self.lines_in_function += 1
  863. def Check(self, error, filename, linenum):
  864. """Report if too many lines in function body.
  865. Args:
  866. error: The function to call with any errors found.
  867. filename: The name of the current file.
  868. linenum: The number of the line to check.
  869. """
  870. if not self.in_a_function:
  871. return
  872. if Match(r'T(EST|est)', self.current_function):
  873. base_trigger = self._TEST_TRIGGER
  874. else:
  875. base_trigger = self._NORMAL_TRIGGER
  876. trigger = base_trigger * 2**_VerboseLevel()
  877. if self.lines_in_function > trigger:
  878. error_level = int(math.log(self.lines_in_function / base_trigger, 2))
  879. # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
  880. if error_level > 5:
  881. error_level = 5
  882. error(filename, linenum, 'readability/fn_size', error_level,
  883. 'Small and focused functions are preferred:'
  884. ' %s has %d non-comment lines'
  885. ' (error triggered by exceeding %d lines).' % (
  886. self.current_function, self.lines_in_function, trigger))
  887. def End(self):
  888. """Stop analyzing function body."""
  889. self.in_a_function = False
  890. class _IncludeError(Exception):
  891. """Indicates a problem with the include order in a file."""
  892. pass
  893. class FileInfo(object):
  894. """Provides utility functions for filenames.
  895. FileInfo provides easy access to the components of a file's path
  896. relative to the project root.
  897. """
  898. def __init__(self, filename):
  899. self._filename = filename
  900. def FullName(self):
  901. """Make Windows paths like Unix."""
  902. return os.path.abspath(self._filename).replace('\\', '/')
  903. def RepositoryName(self):
  904. """FullName after removing the local path to the repository.
  905. If we have a real absolute path name here we can try to do something smart:
  906. detecting the root of the checkout and truncating /path/to/checkout from
  907. the name so that we get header guards that don't include things like
  908. "C:\Documents and Settings\..." or "/home/username/..." in them and thus
  909. people on different computers who have checked the source out to different
  910. locations won't see bogus errors.
  911. """
  912. fullname = self.FullName()
  913. if os.path.exists(fullname):
  914. project_dir = os.path.dirname(fullname)
  915. if os.path.exists(os.path.join(project_dir, ".svn")):
  916. # If there's a .svn file in the current directory, we recursively look
  917. # up the directory tree for the top of the SVN checkout
  918. root_dir = project_dir
  919. one_up_dir = os.path.dirname(root_dir)
  920. while os.path.exists(os.path.join(one_up_dir, ".svn")):
  921. root_dir = os.path.dirname(root_dir)
  922. one_up_dir = os.path.dirname(one_up_dir)
  923. prefix = os.path.commonprefix([root_dir, project_dir])
  924. return fullname[len(prefix) + 1:]
  925. # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
  926. # searching up from the current path.
  927. root_dir = current_dir = os.path.dirname(fullname)
  928. while current_dir != os.path.dirname(current_dir):
  929. if (os.path.exists(os.path.join(current_dir, ".git")) or
  930. os.path.exists(os.path.join(current_dir, ".hg")) or
  931. os.path.exists(os.path.join(current_dir, ".svn"))):
  932. root_dir = current_dir
  933. current_dir = os.path.dirname(current_dir)
  934. if (os.path.exists(os.path.join(root_dir, ".git")) or
  935. os.path.exists(os.path.join(root_dir, ".hg")) or
  936. os.path.exists(os.path.join(root_dir, ".svn"))):
  937. prefix = os.path.commonprefix([root_dir, project_dir])
  938. return fullname[len(prefix) + 1:]
  939. # Don't know what to do; header guard warnings may be wrong...
  940. return fullname
  941. def Split(self):
  942. """Splits the file into the directory, basename, and extension.
  943. For 'chrome/browser/browser.cc', Split() would
  944. return ('chrome/browser', 'browser', '.cc')
  945. Returns:
  946. A tuple of (directory, basename, extension).
  947. """
  948. googlename = self.RepositoryName()
  949. project, rest = os.path.split(googlename)
  950. return (project,) + os.path.splitext(rest)
  951. def BaseName(self):
  952. """File base name - text after the final slash, before the final period."""
  953. return self.Split()[1]
  954. def Extension(self):
  955. """File extension - text following the final period."""
  956. return self.Split()[2]
  957. def NoExtension(self):
  958. """File has no source file extension."""
  959. return '/'.join(self.Split()[0:2])
  960. def IsSource(self):
  961. """File has a source file extension."""
  962. return _IsSourceExtension(self.Extension()[1:])
  963. def _ShouldPrintError(category, confidence, linenum):
  964. """If confidence >= verbose, category passes filter and is not suppressed."""
  965. # There are three ways we might decide not to print an error message:
  966. # a "NOLINT(category)" comment appears in the source,
  967. # the verbosity level isn't high enough, or the filters filter it out.
  968. if IsErrorSuppressedByNolint(category, linenum):
  969. return False
  970. if confidence < _cpplint_state.verbose_level:
  971. return False
  972. is_filtered = False
  973. for one_filter in _Filters():
  974. if one_filter.startswith('-'):
  975. if category.startswith(one_filter[1:]):
  976. is_filtered = True
  977. elif one_filter.startswith('+'):
  978. if category.startswith(one_filter[1:]):
  979. is_filtered = False
  980. else:
  981. assert False # should have been checked for in SetFilter.
  982. if is_filtered:
  983. return False
  984. return True
  985. def Error(filename, linenum, category, confidence, message):
  986. """Logs the fact we've found a lint error.
  987. We log where the error was found, and also our confidence in the error,
  988. that is, how certain we are this is a legitimate style regression, and
  989. not a misidentification or a use that's sometimes justified.
  990. False positives can be suppressed by the use of
  991. "cpplint(category)" comments on the offending line. These are
  992. parsed into _error_suppressions.
  993. Args:
  994. filename: The name of the file containing the error.
  995. linenum: The number of the line containing the error.
  996. category: A string used to describe the "category" this bug
  997. falls under: "whitespace", say, or "runtime". Categories
  998. may have a hierarchy separated by slashes: "whitespace/indent".
  999. confidence: A number from 1-5 representing a confidence score for
  1000. the error, with 5 meaning that we are certain of the problem,
  1001. and 1 meaning that it could be a legitimate construct.
  1002. message: The error message.
  1003. """
  1004. if _ShouldPrintError(category, confidence, linenum):
  1005. _cpplint_state.IncrementErrorCount(category)
  1006. if _cpplint_state.output_format == 'vs7':
  1007. sys.stderr.write('%s(%s): error cpplint: [%s] %s [%d]\n' % (
  1008. filename, linenum, category, message, confidence))
  1009. elif _cpplint_state.output_format == 'eclipse':
  1010. sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
  1011. filename, linenum, message, category, confidence))
  1012. else:
  1013. sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
  1014. filename, linenum, message, category, confidence))
  1015. # Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
  1016. _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
  1017. r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
  1018. # Match a single C style comment on the same line.
  1019. _RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'
  1020. # Matches multi-line C style comments.
  1021. # This RE is a little bit more complicated than one might expect, because we
  1022. # have to take care of space removals tools so we can handle comments inside
  1023. # statements better.
  1024. # The current rule is: We only clear spaces from both sides when we're at the
  1025. # end of the line. Otherwise, we try to remove spaces from the right side,
  1026. # if this doesn't work we try on left side but only if there's a non-character
  1027. # on the right.
  1028. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
  1029. r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +
  1030. _RE_PATTERN_C_COMMENTS + r'\s+|' +
  1031. r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +
  1032. _RE_PATTERN_C_COMMENTS + r')')
  1033. def IsCppString(line):
  1034. """Does line terminate so, that the next symbol is in string constant.
  1035. This function does not consider single-line nor multi-line comments.
  1036. Args:
  1037. line: is a partial line of code starting from the 0..n.
  1038. Returns:
  1039. True, if next character appended to 'line' is inside a
  1040. string constant.
  1041. """
  1042. line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
  1043. return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
  1044. def CleanseRawStrings(raw_lines):
  1045. """Removes C++11 raw strings from lines.
  1046. Before:
  1047. static const char kData[] = R"(
  1048. multi-line string
  1049. )";
  1050. After:
  1051. static const char kData[] = ""
  1052. (replaced by blank line)
  1053. "";
  1054. Args:
  1055. raw_lines: list of raw lines.
  1056. Returns:
  1057. list of lines with C++11 raw strings replaced by empty strings.
  1058. """
  1059. delimiter = None
  1060. lines_without_raw_strings = []
  1061. for line in raw_lines:
  1062. if delimiter:
  1063. # Inside a raw string, look for the end
  1064. end = line.find(delimiter)
  1065. if end >= 0:
  1066. # Found the end of the string, match leading space for this
  1067. # line and resume copying the original lines, and also insert
  1068. # a "" on the last line.
  1069. leading_space = Match(r'^(\s*)\S', line)
  1070. line = leading_space.group(1) + '""' + line[end + len(delimiter):]
  1071. delimiter = None
  1072. else:
  1073. # Haven't found the end yet, append a blank line.
  1074. line = '""'
  1075. # Look for beginning of a raw string, and replace them with
  1076. # empty strings. This is done in a loop to handle multiple raw
  1077. # strings on the same line.
  1078. while delimiter is None:
  1079. # Look for beginning of a raw string.
  1080. # See 2.14.15 [lex.string] for syntax.
  1081. #
  1082. # Once we have matched a raw string, we check the prefix of the
  1083. # line to make sure that the line is not part of a single line
  1084. # comment. It's done this way because we remove raw strings
  1085. # before removing comments as opposed to removing comments
  1086. # before removing raw strings. This is because there are some
  1087. # cpplint checks that requires the comments to be preserved, but
  1088. # we don't want to check comments that are inside raw strings.
  1089. matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
  1090. if (matched and
  1091. not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
  1092. matched.group(1))):
  1093. delimiter = ')' + matched.group(2) + '"'
  1094. end = matched.group(3).find(delimiter)
  1095. if end >= 0:
  1096. # Raw string ended on same line
  1097. line = (matched.group(1) + '""' +
  1098. matched.group(3)[end + len(delimiter):])
  1099. delimiter = None
  1100. else:
  1101. # Start of a multi-line raw string
  1102. line = matched.group(1) + '""'
  1103. else:
  1104. break
  1105. lines_without_raw_strings.append(line)
  1106. # TODO(unknown): if delimiter is not None here, we might want to
  1107. # emit a warning for unterminated string.
  1108. return lines_without_raw_strings
  1109. def FindNextMultiLineCommentStart(lines, lineix):
  1110. """Find the beginning marker for a multiline comment."""
  1111. while lineix < len(lines):
  1112. if lines[lineix].strip().startswith('/*'):
  1113. # Only return this marker if the comment goes beyond this line
  1114. if lines[lineix].strip().find('*/', 2) < 0:
  1115. return lineix
  1116. lineix += 1
  1117. return len(lines)
  1118. def FindNextMultiLineCommentEnd(lines, lineix):
  1119. """We are inside a comment, find the end marker."""
  1120. while lineix < len(lines):
  1121. if lines[lineix].strip().endswith('*/'):
  1122. return lineix
  1123. lineix += 1
  1124. return len(lines)
  1125. def RemoveMultiLineCommentsFromRange(lines, begin, end):
  1126. """Clears a range of lines for multi-line comments."""
  1127. # Having // dummy comments makes the lines non-empty, so we will not get
  1128. # unnecessary blank line warnings later in the code.
  1129. for i in range(begin, end):
  1130. lines[i] = '/**/'
  1131. def RemoveMultiLineComments(filename, lines, error):
  1132. """Removes multiline (c-style) comments from lines."""
  1133. lineix = 0
  1134. while lineix < len(lines):
  1135. lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
  1136. if lineix_begin >= len(lines):
  1137. return
  1138. lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
  1139. if lineix_end >= len(lines):
  1140. error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
  1141. 'Could not find end of multi-line comment')
  1142. return
  1143. RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
  1144. lineix = lineix_end + 1
  1145. def CleanseComments(line):
  1146. """Removes //-comments and single-line C-style /* */ comments.
  1147. Args:
  1148. line: A line of C++ source.
  1149. Returns:
  1150. The line with single-line comments removed.
  1151. """
  1152. commentpos = line.find('//')
  1153. if commentpos != -1 and not IsCppString(line[:commentpos]):
  1154. line = line[:commentpos].rstrip()
  1155. # get rid of /* ... */
  1156. return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
  1157. class CleansedLines(object):
  1158. """Holds 4 copies of all lines with different preprocessing applied to them.
  1159. 1) elided member contains lines without strings and comments.
  1160. 2) lines member contains lines without comments.
  1161. 3) raw_lines member contains all the lines without processing.
  1162. 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw
  1163. strings removed.
  1164. All these members are of <type 'list'>, and of the same length.
  1165. """
  1166. def __init__(self, lines):
  1167. self.elided = []
  1168. self.lines = []
  1169. self.raw_lines = lines
  1170. self.num_lines = len(lines)
  1171. self.lines_without_raw_strings = CleanseRawStrings(lines)
  1172. for linenum in range(len(self.lines_without_raw_strings)):
  1173. self.lines.append(CleanseComments(
  1174. self.lines_without_raw_strings[linenum]))
  1175. elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
  1176. self.elided.append(CleanseComments(elided))
  1177. def NumLines(self):
  1178. """Returns the number of lines represented."""
  1179. return self.num_lines
  1180. @staticmethod
  1181. def _CollapseStrings(elided):
  1182. """Collapses strings and chars on a line to simple "" or '' blocks.
  1183. We nix strings first so we're not fooled by text like '"http://"'
  1184. Args:
  1185. elided: The line being processed.
  1186. Returns:
  1187. The line with collapsed strings.
  1188. """
  1189. if _RE_PATTERN_INCLUDE.match(elided):
  1190. return elided
  1191. # Remove escaped characters first to make quote/single quote collapsing
  1192. # basic. Things that look like escaped characters shouldn't occur
  1193. # outside of strings and chars.
  1194. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
  1195. # Replace quoted strings and digit separators. Both single quotes
  1196. # and double quotes are processed in the same loop, otherwise
  1197. # nested quotes wouldn't work.
  1198. collapsed = ''
  1199. while True:
  1200. # Find the first quote character
  1201. match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
  1202. if not match:
  1203. collapsed += elided
  1204. break
  1205. head, quote, tail = match.groups()
  1206. if quote == '"':
  1207. # Collapse double quoted strings
  1208. second_quote = tail.find('"')
  1209. if second_quote >= 0:
  1210. collapsed += head + '""'
  1211. elided = tail[second_quote + 1:]
  1212. else:
  1213. # Unmatched double quote, don't bother processing the rest
  1214. # of the line since this is probably a multiline string.
  1215. collapsed += elided
  1216. break
  1217. else:
  1218. # Found single quote, check nearby text to eliminate digit separators.
  1219. #
  1220. # There is no special handling for floating point here, because
  1221. # the integer/fractional/exponent parts would all be parsed
  1222. # correctly as long as there are digits on both sides of the
  1223. # separator. So we are fine as long as we don't see something
  1224. # like "0.'3" (gcc 4.9.0 will not allow this literal).
  1225. if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
  1226. match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
  1227. collapsed += head + match_literal.group(1).replace("'", '')
  1228. elided = match_literal.group(2)
  1229. else:
  1230. second_quote = tail.find('\'')
  1231. if second_quote >= 0:
  1232. collapsed += head + "''"
  1233. elided = tail[second_quote + 1:]
  1234. else:
  1235. # Unmatched single quote
  1236. collapsed += elided
  1237. break
  1238. return collapsed
  1239. def FindEndOfExpressionInLine(line, startpos, stack):
  1240. """Find the position just after the end of current parenthesized expression.
  1241. Args:
  1242. line: a CleansedLines line.
  1243. startpos: start searching at this position.
  1244. stack: nesting stack at startpos.
  1245. Returns:
  1246. On finding matching end: (index just after matching end, None)
  1247. On finding an unclosed expression: (-1, None)
  1248. Otherwise: (-1, new stack at end of this line)
  1249. """
  1250. for i in xrange(startpos, len(line)):
  1251. char = line[i]
  1252. if char in '([{':
  1253. # Found start of parenthesized expression, push to expression stack
  1254. stack.append(char)
  1255. elif char == '<':
  1256. # Found potential start of template argument list
  1257. if i > 0 and line[i - 1] == '<':
  1258. # Left shift operator
  1259. if stack and stack[-1] == '<':
  1260. stack.pop()
  1261. if not stack:
  1262. return (-1, None)
  1263. elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
  1264. # operator<, don't add to stack
  1265. continue
  1266. else:
  1267. # Tentative start of template argument list
  1268. stack.append('<')
  1269. elif char in ')]}':
  1270. # Found end of parenthesized expression.
  1271. #
  1272. # If we are currently expecting a matching '>', the pending '<'
  1273. # must have been an operator. Remove them from expression stack.
  1274. while stack and stack[-1] == '<':
  1275. stack.pop()
  1276. if not stack:
  1277. return (-1, None)
  1278. if ((stack[-1] == '(' and char == ')') or
  1279. (stack[-1] == '[' and char == ']') or
  1280. (stack[-1] == '{' and char == '}')):
  1281. stack.pop()
  1282. if not stack:
  1283. return (i + 1, None)
  1284. else:
  1285. # Mismatched parentheses
  1286. return (-1, None)
  1287. elif char == '>':
  1288. # Found potential end of template argument list.
  1289. # Ignore "->" and operator functions
  1290. if (i > 0 and
  1291. (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
  1292. continue
  1293. # Pop the stack if there is a matching '<'. Otherwise, ignore
  1294. # this '>' since it must be an operator.
  1295. if stack:
  1296. if stack[-1] == '<':
  1297. stack.pop()
  1298. if not stack:
  1299. return (i + 1, None)
  1300. elif char == ';':
  1301. # Found something that look like end of statements. If we are currently
  1302. # expecting a '>', the matching '<' must have been an operator, since
  1303. # template argument list should not contain statements.
  1304. while stack and stack[-1] == '<':
  1305. stack.pop()
  1306. if not stack:
  1307. return (-1, None)
  1308. # Did not find end of expression or unbalanced parentheses on this line
  1309. return (-1, stack)
  1310. def CloseExpression(clean_lines, linenum, pos):
  1311. """If input points to ( or { or [ or <, finds the position that closes it.
  1312. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
  1313. linenum/pos that correspond to the closing of the expression.
  1314. TODO(unknown): cpplint spends a fair bit of time matching parentheses.
  1315. Ideally we would want to index all opening and closing parentheses once
  1316. and have CloseExpression be just a simple lookup, but due to preprocessor
  1317. tricks, this is not so easy.
  1318. Args:
  1319. clean_lines: A CleansedLines instance containing the file.
  1320. linenum: The number of the line to check.
  1321. pos: A position on the line.
  1322. Returns:
  1323. A tuple (line, linenum, pos) pointer *past* the closing brace, or
  1324. (line, len(lines), -1) if we never find a close. Note we ignore
  1325. strings and comments when matching; and the line we return is the
  1326. 'cleansed' line at linenum.
  1327. """
  1328. line = clean_lines.elided[linenum]
  1329. if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
  1330. return (line, clean_lines.NumLines(), -1)
  1331. # Check first line
  1332. (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
  1333. if end_pos > -1:
  1334. return (line, linenum, end_pos)
  1335. # Continue scanning forward
  1336. while stack and linenum < clean_lines.NumLines() - 1:
  1337. linenum += 1
  1338. line = clean_lines.elided[linenum]
  1339. (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
  1340. if end_pos > -1:
  1341. return (line, linenum, end_pos)
  1342. # Did not find end of expression before end of file, give up
  1343. return (line, clean_lines.NumLines(), -1)
  1344. def FindStartOfExpressionInLine(line, endpos, stack):
  1345. """Find position at the matching start of current expression.
  1346. This is almost the reverse of FindEndOfExpressionInLine, but note
  1347. that the input position and returned position differs by 1.
  1348. Args:
  1349. line: a CleansedLines line.
  1350. endpos: start searching at this position.
  1351. stack: nesting stack at endpos.
  1352. Returns:
  1353. On finding matching start: (index at matching start, None)
  1354. On finding an unclosed expression: (-1, None)
  1355. Otherwise: (-1, new stack at beginning of this line)
  1356. """
  1357. i = endpos
  1358. while i >= 0:
  1359. char = line[i]
  1360. if char in ')]}':
  1361. # Found end of expression, push to expression stack
  1362. stack.append(char)
  1363. elif char == '>':
  1364. # Found potential end of template argument list.
  1365. #
  1366. # Ignore it if it's a "->" or ">=" or "operator>"
  1367. if (i > 0 and
  1368. (line[i - 1] == '-' or
  1369. Match(r'\s>=\s', line[i - 1:]) or
  1370. Search(r'\boperator\s*$', line[0:i]))):
  1371. i -= 1
  1372. else:
  1373. stack.append('>')
  1374. elif char == '<':
  1375. # Found potential start of template argument list
  1376. if i > 0 and line[i - 1] == '<':
  1377. # Left shift operator
  1378. i -= 1
  1379. else:
  1380. # If there is a matching '>', we can pop the expression stack.
  1381. # Otherwise, ignore this '<' since it must be an operator.
  1382. if stack and stack[-1] == '>':
  1383. stack.pop()
  1384. if not stack:
  1385. return (i, None)
  1386. elif char in '([{':
  1387. # Found start of expression.
  1388. #
  1389. # If there are any unmatched '>' on the stack, they must be
  1390. # operators. Remove those.
  1391. while stack and stack[-1] == '>':
  1392. stack.pop()
  1393. if not stack:
  1394. return (-1, None)
  1395. if ((char == '(' and stack[-1] == ')') or
  1396. (char == '[' and stack[-1] == ']') or
  1397. (char == '{' and stack[-1] == '}')):
  1398. stack.pop()
  1399. if not stack:
  1400. return (i, None)
  1401. else:
  1402. # Mismatched parentheses
  1403. return (-1, None)
  1404. elif char == ';':
  1405. # Found something that look like end of statements. If we are currently
  1406. # expecting a '<', the matching '>' must have been an operator, since
  1407. # template argument list should not contain statements.
  1408. while stack and stack[-1] == '>':
  1409. stack.pop()
  1410. if not stack:
  1411. return (-1, None)
  1412. i -= 1
  1413. return (-1, stack)
  1414. def ReverseCloseExpression(clean_lines, linenum, pos):
  1415. """If input points to ) or } or ] or >, finds the position that opens it.
  1416. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
  1417. linenum/pos that correspond to the opening of the expression.
  1418. Args:
  1419. clean_lines: A CleansedLines instance containing the file.
  1420. linenum: The number of the line to check.
  1421. pos: A position on the line.
  1422. Returns:
  1423. A tuple (line, linenum, pos) pointer *at* the opening brace, or
  1424. (line, 0, -1) if we never find the matching opening brace. Note
  1425. we ignore strings and comments when matching; and the line we
  1426. return is the 'cleansed' line at linenum.
  1427. """
  1428. line = clean_lines.elided[linenum]
  1429. if line[pos] not in ')}]>':
  1430. return (line, 0, -1)
  1431. # Check last line
  1432. (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
  1433. if start_pos > -1:
  1434. return (line, linenum, start_pos)
  1435. # Continue scanning backward
  1436. while stack and linenum > 0:
  1437. linenum -= 1
  1438. line = clean_lines.elided[linenum]
  1439. (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
  1440. if start_pos > -1:
  1441. return (line, linenum, start_pos)
  1442. # Did not find start of expression before beginning of file, give up
  1443. return (line, 0, -1)
  1444. def CheckForCopyright(filename, lines, error):
  1445. """Logs an error if no Copyright message appears at the top of the file."""
  1446. # We'll say it should occur by line 10. Don't forget there's a
  1447. # dummy line at the front.
  1448. for line in xrange(1, min(len(lines), 11)):
  1449. if re.search(r'Copyright', lines[line], re.I): break
  1450. else: # means no copyright line was found
  1451. error(filename, 0, 'legal/copyright', 5,
  1452. 'No copyright message found. '
  1453. 'You should have a line: "Copyright [year] <Copyright Owner>"')
  1454. def GetIndentLevel(line):
  1455. """Return the number of leading spaces in line.
  1456. Args:
  1457. line: A string to check.
  1458. Returns:
  1459. An integer count of leading spaces, possibly zero.
  1460. """
  1461. indent = Match(r'^( *)\S', line)
  1462. if indent:
  1463. return len(indent.group(1))
  1464. else:
  1465. return 0
  1466. def GetHeaderGuardCPPVariable(filename):
  1467. """Returns the CPP variable that should be used as a header guard.
  1468. Args:
  1469. filename: The name of a C++ header file.
  1470. Returns:
  1471. The CPP variable that should be used as a header guard in the
  1472. named file.
  1473. """
  1474. # Restores original filename in case that cpplint is invoked from Emacs's
  1475. # flymake.
  1476. filename = re.sub(r'_flymake\.h$', '.h', filename)
  1477. filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
  1478. # Replace 'c++' with 'cpp'.
  1479. filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
  1480. fileinfo = FileInfo(filename)
  1481. file_path_from_root = fileinfo.RepositoryName()
  1482. if _root:
  1483. suffix = os.sep
  1484. # On Windows using directory separator will leave us with
  1485. # "bogus escape error" unless we properly escape regex.
  1486. if suffix == '\\':
  1487. suffix += '\\'
  1488. file_path_from_root = re.sub('^' + _root + suffix, '', file_path_from_root)
  1489. return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
  1490. def CheckForHeaderGuard(filename, clean_lines, error):
  1491. """Checks that the file contains a header guard.
  1492. Logs an error if no #ifndef header guard is present. For other
  1493. headers, checks that the full pathname is used.
  1494. Args:
  1495. filename: The name of the C++ header file.
  1496. clean_lines: A CleansedLines instance containing the file.
  1497. error: The function to call with any errors found.
  1498. """
  1499. # Don't check for header guards if there are error suppression
  1500. # comments somewhere in this file.
  1501. #
  1502. # Because this is silencing a warning for a nonexistent line, we
  1503. # only support the very specific NOLINT(build/header_guard) syntax,
  1504. # and not the general NOLINT or NOLINT(*) syntax.
  1505. raw_lines = clean_lines.lines_without_raw_strings
  1506. for i in raw_lines:
  1507. if Search(r'//\s*NOLINT\(build/header_guard\)', i):
  1508. return
  1509. cppvar = GetHeaderGuardCPPVariable(filename)
  1510. ifndef = ''
  1511. ifndef_linenum = 0
  1512. define = ''
  1513. endif = ''
  1514. endif_linenum = 0
  1515. for linenum, line in enumerate(raw_lines):
  1516. linesplit = line.split()
  1517. if len(linesplit) >= 2:
  1518. # find the first occurrence of #ifndef and #define, save arg
  1519. if not ifndef and linesplit[0] == '#ifndef':
  1520. # set ifndef to the header guard presented on the #ifndef line.
  1521. ifndef = linesplit[1]
  1522. ifndef_linenum = linenum
  1523. if not define and linesplit[0] == '#define':
  1524. define = linesplit[1]
  1525. # find the last occurrence of #endif, save entire line
  1526. if line.startswith('#endif'):
  1527. endif = line
  1528. endif_linenum = linenum
  1529. if not ifndef or not define or ifndef != define:
  1530. error(filename, 0, 'build/header_guard', 5,
  1531. 'No #ifndef header guard found, suggested CPP variable is: %s' %
  1532. cppvar)
  1533. return
  1534. # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
  1535. # for backward compatibility.
  1536. if ifndef != cppvar:
  1537. error_level = 0
  1538. if ifndef != cppvar + '_':
  1539. error_level = 5
  1540. ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
  1541. error)
  1542. error(filename, ifndef_linenum, 'build/header_guard', error_level,
  1543. '#ifndef header guard has wrong style, please use: %s' % cppvar)
  1544. # Check for "//" comments on endif line.
  1545. ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
  1546. error)
  1547. match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
  1548. if match:
  1549. if match.group(1) == '_':
  1550. # Issue low severity warning for deprecated double trailing underscore
  1551. error(filename, endif_linenum, 'build/header_guard', 0,
  1552. '#endif line should be "#endif // %s"' % cppvar)
  1553. return
  1554. # Didn't find the corresponding "//" comment. If this file does not
  1555. # contain any "//" comments at all, it could be that the compiler
  1556. # only wants "/**/" comments, look for those instead.
  1557. no_single_line_comments = True
  1558. for i in xrange(1, len(raw_lines) - 1):
  1559. line = raw_lines[i]
  1560. if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
  1561. no_single_line_comments = False
  1562. break
  1563. if no_single_line_comments:
  1564. match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
  1565. if match:
  1566. if match.group(1) == '_':
  1567. # Low severity warning for double trailing underscore
  1568. error(filename, endif_linenum, 'build/header_guard', 0,
  1569. '#endif line should be "#endif /* %s */"' % cppvar)
  1570. return
  1571. # Didn't find anything
  1572. error(filename, endif_linenum, 'build/header_guard', 5,
  1573. '#endif line should be "#endif // %s"' % cppvar)
  1574. def CheckHeaderFileIncluded(filename, include_state, error):
  1575. """Logs an error if a .cc file does not include its header."""
  1576. # Do not check test files
  1577. fileinfo = FileInfo(filename)
  1578. if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
  1579. return
  1580. headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'
  1581. if not os.path.exists(headerfile):
  1582. return
  1583. headername = FileInfo(headerfile).RepositoryName()
  1584. first_include = 0
  1585. for section_list in include_state.include_list:
  1586. for f in section_list:
  1587. if headername in f[0] or f[0] in headername:
  1588. return
  1589. if not first_include:
  1590. first_include = f[1]
  1591. error(filename, first_include, 'build/include', 5,
  1592. '%s should include its header file %s' % (fileinfo.RepositoryName(),
  1593. headername))
  1594. def CheckForBadCharacters(filename, lines, error):
  1595. """Logs an error for each line containing bad characters.
  1596. Two kinds of bad characters:
  1597. 1. Unicode replacement characters: These indicate that either the file
  1598. contained invalid UTF-8 (likely) or Unicode replacement characters (which
  1599. it shouldn't). Note that it's possible for this to throw off line
  1600. numbering if the invalid UTF-8 occurred adjacent to a newline.
  1601. 2. NUL bytes. These are problematic for some tools.
  1602. Args:
  1603. filename: The name of the current file.
  1604. lines: An array of strings, each representing a line of the file.
  1605. error: The function to call with any errors found.
  1606. """
  1607. for linenum, line in enumerate(lines):
  1608. if u'\ufffd' in line:
  1609. error(filename, linenum, 'readability/utf8', 5,
  1610. 'Line contains invalid UTF-8 (or Unicode replacement character).')
  1611. if '\0' in line:
  1612. error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
  1613. def CheckForNewlineAtEOF(filename, lines, error):
  1614. """Logs an error if there is no newline char at the end of the file.
  1615. Args:
  1616. filename: The name of the current file.
  1617. lines: An array of strings, each representing a line of the file.
  1618. error: The function to call with any errors found.
  1619. """
  1620. # The array lines() was created by adding two newlines to the
  1621. # original file (go figure), then splitting on \n.
  1622. # To verify that the file ends in \n, we just have to make sure the
  1623. # last-but-two element of lines() exists and is empty.
  1624. if len(lines) < 3 or lines[-2]:
  1625. error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
  1626. 'Could not find a newline character at the end of the file.')
  1627. def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
  1628. """Logs an error if we see /* ... */ or "..." that extend past one line.
  1629. /* ... */ comments are legit inside macros, for one line.
  1630. Otherwise, we prefer // comments, so it's ok to warn about the
  1631. other. Likewise, it's ok for strings to extend across multiple
  1632. lines, as long as a line continuation character (backslash)
  1633. terminates each line. Although not currently prohibited by the C++
  1634. style guide, it's ugly and unnecessary. We don't do well with either
  1635. in this lint program, so we warn about both.
  1636. Args:
  1637. filename: The name of the current file.
  1638. clean_lines: A CleansedLines instance containing the file.
  1639. linenum: The number of the line to check.
  1640. error: The function to call with any errors found.
  1641. """
  1642. line = clean_lines.elided[linenum]
  1643. # Remove all \\ (escaped backslashes) from the line. They are OK, and the
  1644. # second (escaped) slash may trigger later \" detection erroneously.
  1645. line = line.replace('\\\\', '')
  1646. if line.count('/*') > line.count('*/'):
  1647. error(filename, linenum, 'readability/multiline_comment', 5,
  1648. 'Complex multi-line /*...*/-style comment found. '
  1649. 'Lint may give bogus warnings. '
  1650. 'Consider replacing these with //-style comments, '
  1651. 'with #if 0...#endif, '
  1652. 'or with more clearly structured multi-line comments.')
  1653. if (line.count('"') - line.count('\\"')) % 2:
  1654. error(filename, linenum, 'readability/multiline_string', 5,
  1655. 'Multi-line string ("...") found. This lint script doesn\'t '
  1656. 'do well with such strings, and may give bogus warnings. '
  1657. 'Use C++11 raw strings or concatenation instead.')
  1658. # (non-threadsafe name, thread-safe alternative, validation pattern)
  1659. #
  1660. # The validation pattern is used to eliminate false positives such as:
  1661. # _rand(); // false positive due to substring match.
  1662. # ->rand(); // some member function rand().
  1663. # ACMRandom rand(seed); // some variable named rand.
  1664. # ISAACRandom rand(); // another variable named rand.
  1665. #
  1666. # Basically we require the return value of these functions to be used
  1667. # in some expression context on the same line by matching on some
  1668. # operator before the function name. This eliminates constructors and
  1669. # member function calls.
  1670. _UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
  1671. _THREADING_LIST = (
  1672. ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),
  1673. ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),
  1674. ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),
  1675. ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),
  1676. ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),
  1677. ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),
  1678. ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),
  1679. ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),
  1680. ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),
  1681. ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),
  1682. ('strtok(', 'strtok_r(',
  1683. _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),
  1684. ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),
  1685. )
  1686. def CheckPosixThreading(filename, clean_lines, linenum, error):
  1687. """Checks for calls to thread-unsafe functions.
  1688. Much code has been originally written without consideration of
  1689. multi-threading. Also, engineers are relying on their old experience;
  1690. they have learned posix before threading extensions were added. These
  1691. tests guide the engineers to use thread-safe functions (when using
  1692. posix directly).
  1693. Args:
  1694. filename: The name of the current file.
  1695. clean_lines: A CleansedLines instance containing the file.
  1696. linenum: The number of the line to check.
  1697. error: The function to call with any errors found.
  1698. """
  1699. line = clean_lines.elided[linenum]
  1700. for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
  1701. # Additional pattern matching check to confirm that this is the
  1702. # function we are looking for
  1703. if Search(pattern, line):
  1704. error(filename, linenum, 'runtime/threadsafe_fn', 2,
  1705. 'Consider using ' + multithread_safe_func +
  1706. '...) instead of ' + single_thread_func +
  1707. '...) for improved thread safety.')
  1708. def CheckVlogArguments(filename, clean_lines, linenum, error):
  1709. """Checks that VLOG() is only used for defining a logging level.
  1710. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
  1711. VLOG(FATAL) are not.
  1712. Args:
  1713. filename: The name of the current file.
  1714. clean_lines: A CleansedLines instance containing the file.
  1715. linenum: The number of the line to check.
  1716. error: The function to call with any errors found.
  1717. """
  1718. line = clean_lines.elided[linenum]
  1719. if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
  1720. error(filename, linenum, 'runtime/vlog', 5,
  1721. 'VLOG() should be used with numeric verbosity level. '
  1722. 'Use LOG() if you want symbolic severity levels.')
  1723. # Matches invalid increment: *count++, which moves pointer instead of
  1724. # incrementing a value.
  1725. _RE_PATTERN_INVALID_INCREMENT = re.compile(
  1726. r'^\s*\*\w+(\+\+|--);')
  1727. def CheckInvalidIncrement(filename, clean_lines, linenum, error):
  1728. """Checks for invalid increment *count++.
  1729. For example following function:
  1730. void increment_counter(int* count) {
  1731. *count++;
  1732. }
  1733. is invalid, because it effectively does count++, moving pointer, and should
  1734. be replaced with ++*count, (*count)++ or *count += 1.
  1735. Args:
  1736. filename: The name of the current file.
  1737. clean_lines: A CleansedLines instance containing the file.
  1738. linenum: The number of the line to check.
  1739. error: The function to call with any errors found.
  1740. """
  1741. line = clean_lines.elided[linenum]
  1742. if _RE_PATTERN_INVALID_INCREMENT.match(line):
  1743. error(filename, linenum, 'runtime/invalid_increment', 5,
  1744. 'Changing pointer instead of value (or unused value of operator*).')
  1745. def IsMacroDefinition(clean_lines, linenum):
  1746. if Search(r'^#define', clean_lines[linenum]):
  1747. return True
  1748. if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
  1749. return True
  1750. return False
  1751. def IsForwardClassDeclaration(clean_lines, linenum):
  1752. return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])
  1753. class _BlockInfo(object):
  1754. """Stores information about a generic block of code."""
  1755. def __init__(self, linenum, seen_open_brace):
  1756. self.starting_linenum = linenum
  1757. self.seen_open_brace = seen_open_brace
  1758. self.open_parentheses = 0
  1759. self.inline_asm = _NO_ASM
  1760. self.check_namespace_indentation = False
  1761. def CheckBegin(self, filename, clean_lines, linenum, error):
  1762. """Run checks that applies to text up to the opening brace.
  1763. This is mostly for checking the text after the class identifier
  1764. and the "{", usually where the base class is specified. For other
  1765. blocks, there isn't much to check, so we always pass.
  1766. Args:
  1767. filename: The name of the current file.
  1768. clean_lines: A CleansedLines instance containing the file.
  1769. linenum: The number of the line to check.
  1770. error: The function to call with any errors found.
  1771. """
  1772. pass
  1773. def CheckEnd(self, filename, clean_lines, linenum, error):
  1774. """Run checks that applies to text after the closing brace.
  1775. This is mostly used for checking end of namespace comments.
  1776. Args:
  1777. filename: The name of the current file.
  1778. clean_lines: A CleansedLines instance containing the file.
  1779. linenum: The number of the line to check.
  1780. error: The function to call with any errors found.
  1781. """
  1782. pass
  1783. def IsBlockInfo(self):
  1784. """Returns true if this block is a _BlockInfo.
  1785. This is convenient for verifying that an object is an instance of
  1786. a _BlockInfo, but not an instance of any of the derived classes.
  1787. Returns:
  1788. True for this class, False for derived classes.
  1789. """
  1790. return self.__class__ == _BlockInfo
  1791. class _ExternCInfo(_BlockInfo):
  1792. """Stores information about an 'extern "C"' block."""
  1793. def __init__(self, linenum):
  1794. _BlockInfo.__init__(self, linenum, True)
  1795. class _ClassInfo(_BlockInfo):
  1796. """Stores information about a class."""
  1797. def __init__(self, name, class_or_struct, clean_lines, linenum):
  1798. _BlockInfo.__init__(self, linenum, False)
  1799. self.name = name
  1800. self.is_derived = False
  1801. self.check_namespace_indentation = True
  1802. if class_or_struct == 'struct':
  1803. self.access = 'public'
  1804. self.is_struct = True
  1805. else:
  1806. self.access = 'private'
  1807. self.is_struct = False
  1808. # Remember initial indentation level for this class. Using raw_lines here
  1809. # instead of elided to account for leading comments.
  1810. self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])
  1811. # Try to find the end of the class. This will be confused by things like:
  1812. # class A {
  1813. # } *x = { ...
  1814. #
  1815. # But it's still good enough for CheckSectionSpacing.
  1816. self.last_line = 0
  1817. depth = 0
  1818. for i in range(linenum, clean_lines.NumLines()):
  1819. line = clean_lines.elided[i]
  1820. depth += line.count('{') - line.count('}')
  1821. if not depth:
  1822. self.last_line = i
  1823. break
  1824. def CheckBegin(self, filename, clean_lines, linenum, error):
  1825. # Look for a bare ':'
  1826. if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
  1827. self.is_derived = True
  1828. def CheckEnd(self, filename, clean_lines, linenum, error):
  1829. # If there is a DISALLOW macro, it should appear near the end of
  1830. # the class.
  1831. seen_last_thing_in_class = False
  1832. for i in xrange(linenum - 1, self.starting_linenum, -1):
  1833. match = Search(
  1834. r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +
  1835. self.name + r'\)',
  1836. clean_lines.elided[i])
  1837. if match:
  1838. if seen_last_thing_in_class:
  1839. error(filename, i, 'readability/constructors', 3,
  1840. match.group(1) + ' should be the last thing in the class')
  1841. break
  1842. if not Match(r'^\s*$', clean_lines.elided[i]):
  1843. seen_last_thing_in_class = True
  1844. # Check that closing brace is aligned with beginning of the class.
  1845. # Only do this if the closing brace is indented by only whitespaces.
  1846. # This means we will not check single-line class definitions.
  1847. indent = Match(r'^( *)\}', clean_lines.elided[linenum])
  1848. if indent and len(indent.group(1)) != self.class_indent:
  1849. if self.is_struct:
  1850. parent = 'struct ' + self.name
  1851. else:
  1852. parent = 'class ' + self.name
  1853. error(filename, linenum, 'whitespace/indent', 3,
  1854. 'Closing brace should be aligned with beginning of %s' % parent)
  1855. class _NamespaceInfo(_BlockInfo):
  1856. """Stores information about a namespace."""
  1857. def __init__(self, name, linenum):
  1858. _BlockInfo.__init__(self, linenum, False)
  1859. self.name = name or ''
  1860. self.check_namespace_indentation = True
  1861. def CheckEnd(self, filename, clean_lines, linenum, error):
  1862. """Check end of namespace comments."""
  1863. line = clean_lines.raw_lines[linenum]
  1864. # Check how many lines is enclosed in this namespace. Don't issue
  1865. # warning for missing namespace comments if there aren't enough
  1866. # lines. However, do apply checks if there is already an end of
  1867. # namespace comment and it's incorrect.
  1868. #
  1869. # TODO(unknown): We always want to check end of namespace comments
  1870. # if a namespace is large, but sometimes we also want to apply the
  1871. # check if a short namespace contained nontrivial things (something
  1872. # other than forward declarations). There is currently no logic on
  1873. # deciding what these nontrivial things are, so this check is
  1874. # triggered by namespace size only, which works most of the time.
  1875. if (linenum - self.starting_linenum < 10
  1876. and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):
  1877. return
  1878. # Look for matching comment at end of namespace.
  1879. #
  1880. # Note that we accept C style "/* */" comments for terminating
  1881. # namespaces, so that code that terminate namespaces inside
  1882. # preprocessor macros can be cpplint clean.
  1883. #
  1884. # We also accept stuff like "// end of namespace <name>." with the
  1885. # period at the end.
  1886. #
  1887. # Besides these, we don't accept anything else, otherwise we might
  1888. # get false negatives when existing comment is a substring of the
  1889. # expected namespace.
  1890. if self.name:
  1891. # Named namespace
  1892. if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +
  1893. re.escape(self.name) + r'[\*/\.\\\s]*$'),
  1894. line):
  1895. error(filename, linenum, 'readability/namespace', 5,
  1896. 'Namespace should be terminated with "// namespace %s"' %
  1897. self.name)
  1898. else:
  1899. # Anonymous namespace
  1900. if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
  1901. # If "// namespace anonymous" or "// anonymous namespace (more text)",
  1902. # mention "// anonymous namespace" as an acceptable form
  1903. if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):
  1904. error(filename, linenum, 'readability/namespace', 5,
  1905. 'Anonymous namespace should be terminated with "// namespace"'
  1906. ' or "// anonymous namespace"')
  1907. else:
  1908. error(filename, linenum, 'readability/namespace', 5,
  1909. 'Anonymous namespace should be terminated with "// namespace"')
  1910. class _PreprocessorInfo(object):
  1911. """Stores checkpoints of nesting stacks when #if/#else is seen."""
  1912. def __init__(self, stack_before_if):
  1913. # The entire nesting stack before #if
  1914. self.stack_before_if = stack_before_if
  1915. # The entire nesting stack up to #else
  1916. self.stack_before_else = []
  1917. # Whether we have already seen #else or #elif
  1918. self.seen_else = False
  1919. class NestingState(object):
  1920. """Holds states related to parsing braces."""
  1921. def __init__(self):
  1922. # Stack for tracking all braces. An object is pushed whenever we
  1923. # see a "{", and popped when we see a "}". Only 3 types of
  1924. # objects are possible:
  1925. # - _ClassInfo: a class or struct.
  1926. # - _NamespaceInfo: a namespace.
  1927. # - _BlockInfo: some other type of block.
  1928. self.stack = []
  1929. # Top of the previous stack before each Update().
  1930. #
  1931. # Because the nesting_stack is updated at the end of each line, we
  1932. # had to do some convoluted checks to find out what is the current
  1933. # scope at the beginning of the line. This check is simplified by
  1934. # saving the previous top of nesting stack.
  1935. #
  1936. # We could save the full stack, but we only need the top. Copying
  1937. # the full nesting stack would slow down cpplint by ~10%.
  1938. self.previous_stack_top = []
  1939. # Stack of _PreprocessorInfo objects.
  1940. self.pp_stack = []
  1941. def SeenOpenBrace(self):
  1942. """Check if we have seen the opening brace for the innermost block.
  1943. Returns:
  1944. True if we have seen the opening brace, False if the innermost
  1945. block is still expecting an opening brace.
  1946. """
  1947. return (not self.stack) or self.stack[-1].seen_open_brace
  1948. def InNamespaceBody(self):
  1949. """Check if we are currently one level inside a namespace body.
  1950. Returns:
  1951. True if top of the stack is a namespace block, False otherwise.
  1952. """
  1953. return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
  1954. def InExternC(self):
  1955. """Check if we are currently one level inside an 'extern "C"' block.
  1956. Returns:
  1957. True if top of the stack is an extern block, False otherwise.
  1958. """
  1959. return self.stack and isinstance(self.stack[-1], _ExternCInfo)
  1960. def InClassDeclaration(self):
  1961. """Check if we are currently one level inside a class or struct declaration.
  1962. Returns:
  1963. True if top of the stack is a class/struct, False otherwise.
  1964. """
  1965. return self.stack and isinstance(self.stack[-1], _ClassInfo)
  1966. def InAsmBlock(self):
  1967. """Check if we are currently one level inside an inline ASM block.
  1968. Returns:
  1969. True if the top of the stack is a block containing inline ASM.
  1970. """
  1971. return self.stack and self.stack[-1].inline_asm != _NO_ASM
  1972. def InTemplateArgumentList(self, clean_lines, linenum, pos):
  1973. """Check if current position is inside template argument list.
  1974. Args:
  1975. clean_lines: A CleansedLines instance containing the file.
  1976. linenum: The number of the line to check.
  1977. pos: position just after the suspected template argument.
  1978. Returns:
  1979. True if (linenum, pos) is inside template arguments.
  1980. """
  1981. while linenum < clean_lines.NumLines():
  1982. # Find the earliest character that might indicate a template argument
  1983. line = clean_lines.elided[linenum]
  1984. match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
  1985. if not match:
  1986. linenum += 1
  1987. pos = 0
  1988. continue
  1989. token = match.group(1)
  1990. pos += len(match.group(0))
  1991. # These things do not look like template argument list:
  1992. # class Suspect {
  1993. # class Suspect x; }
  1994. if token in ('{', '}', ';'): return False
  1995. # These things look like template argument list:
  1996. # template <class Suspect>
  1997. # template <class Suspect = default_value>
  1998. # template <class Suspect[]>
  1999. # template <class Suspect...>
  2000. if token in ('>', '=', '[', ']', '.'): return True
  2001. # Check if token is an unmatched '<'.
  2002. # If not, move on to the next character.
  2003. if token != '<':
  2004. pos += 1
  2005. if pos >= len(line):
  2006. linenum += 1
  2007. pos = 0
  2008. continue
  2009. # We can't be sure if we just find a single '<', and need to
  2010. # find the matching '>'.
  2011. (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
  2012. if end_pos < 0:
  2013. # Not sure if template argument list or syntax error in file
  2014. return False
  2015. linenum = end_line
  2016. pos = end_pos
  2017. return False
  2018. def UpdatePreprocessor(self, line):
  2019. """Update preprocessor stack.
  2020. We need to handle preprocessors due to classes like this:
  2021. #ifdef SWIG
  2022. struct ResultDetailsPageElementExtensionPoint {
  2023. #else
  2024. struct ResultDetailsPageElementExtensionPoint : public Extension {
  2025. #endif
  2026. We make the following assumptions (good enough for most files):
  2027. - Preprocessor condition evaluates to true from #if up to first
  2028. #else/#elif/#endif.
  2029. - Preprocessor condition evaluates to false from #else/#elif up
  2030. to #endif. We still perform lint checks on these lines, but
  2031. these do not affect nesting stack.
  2032. Args:
  2033. line: current line to check.
  2034. """
  2035. if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
  2036. # Beginning of #if block, save the nesting stack here. The saved
  2037. # stack will allow us to restore the parsing state in the #else case.
  2038. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
  2039. elif Match(r'^\s*#\s*(else|elif)\b', line):
  2040. # Beginning of #else block
  2041. if self.pp_stack:
  2042. if not self.pp_stack[-1].seen_else:
  2043. # This is the first #else or #elif block. Remember the
  2044. # whole nesting stack up to this point. This is what we
  2045. # keep after the #endif.
  2046. self.pp_stack[-1].seen_else = True
  2047. self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
  2048. # Restore the stack to how it was before the #if
  2049. self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
  2050. else:
  2051. # TODO(unknown): unexpected #else, issue warning?
  2052. pass
  2053. elif Match(r'^\s*#\s*endif\b', line):
  2054. # End of #if or #else blocks.
  2055. if self.pp_stack:
  2056. # If we saw an #else, we will need to restore the nesting
  2057. # stack to its former state before the #else, otherwise we
  2058. # will just continue from where we left off.
  2059. if self.pp_stack[-1].seen_else:
  2060. # Here we can just use a shallow copy since we are the last
  2061. # reference to it.
  2062. self.stack = self.pp_stack[-1].stack_before_else
  2063. # Drop the corresponding #if
  2064. self.pp_stack.pop()
  2065. else:
  2066. # TODO(unknown): unexpected #endif, issue warning?
  2067. pass
  2068. # TODO(unknown): Update() is too long, but we will refactor later.
  2069. def Update(self, filename, clean_lines, linenum, error):
  2070. """Update nesting state with current line.
  2071. Args:
  2072. filename: The name of the current file.
  2073. clean_lines: A CleansedLines instance containing the file.
  2074. linenum: The number of the line to check.
  2075. error: The function to call with any errors found.
  2076. """
  2077. line = clean_lines.elided[linenum]
  2078. # Remember top of the previous nesting stack.
  2079. #
  2080. # The stack is always pushed/popped and not modified in place, so
  2081. # we can just do a shallow copy instead of copy.deepcopy. Using
  2082. # deepcopy would slow down cpplint by ~28%.
  2083. if self.stack:
  2084. self.previous_stack_top = self.stack[-1]
  2085. else:
  2086. self.previous_stack_top = None
  2087. # Update pp_stack
  2088. self.UpdatePreprocessor(line)
  2089. # Count parentheses. This is to avoid adding struct arguments to
  2090. # the nesting stack.
  2091. if self.stack:
  2092. inner_block = self.stack[-1]
  2093. depth_change = line.count('(') - line.count(')')
  2094. inner_block.open_parentheses += depth_change
  2095. # Also check if we are starting or ending an inline assembly block.
  2096. if inner_block.inline_asm in (_NO_ASM, _END_ASM):
  2097. if (depth_change != 0 and
  2098. inner_block.open_parentheses == 1 and
  2099. _MATCH_ASM.match(line)):
  2100. # Enter assembly block
  2101. inner_block.inline_asm = _INSIDE_ASM
  2102. else:
  2103. # Not entering assembly block. If previous line was _END_ASM,
  2104. # we will now shift to _NO_ASM state.
  2105. inner_block.inline_asm = _NO_ASM
  2106. elif (inner_block.inline_asm == _INSIDE_ASM and
  2107. inner_block.open_parentheses == 0):
  2108. # Exit assembly block
  2109. inner_block.inline_asm = _END_ASM
  2110. # Consume namespace declaration at the beginning of the line. Do
  2111. # this in a loop so that we catch same line declarations like this:
  2112. # namespace proto2 { namespace bridge { class MessageSet; } }
  2113. while True:
  2114. # Match start of namespace. The "\b\s*" below catches namespace
  2115. # declarations even if it weren't followed by a whitespace, this
  2116. # is so that we don't confuse our namespace checker. The
  2117. # missing spaces will be flagged by CheckSpacing.
  2118. namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
  2119. if not namespace_decl_match:
  2120. break
  2121. new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
  2122. self.stack.append(new_namespace)
  2123. line = namespace_decl_match.group(2)
  2124. if line.find('{') != -1:
  2125. new_namespace.seen_open_brace = True
  2126. line = line[line.find('{') + 1:]
  2127. # Look for a class declaration in whatever is left of the line
  2128. # after parsing namespaces. The regexp accounts for decorated classes
  2129. # such as in:
  2130. # class LOCKABLE API Object {
  2131. # };
  2132. class_decl_match = Match(
  2133. r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'
  2134. r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))'
  2135. r'(.*)$', line)
  2136. if (class_decl_match and
  2137. (not self.stack or self.stack[-1].open_parentheses == 0)):
  2138. # We do not want to accept classes that are actually template arguments:
  2139. # template <class Ignore1,
  2140. # class Ignore2 = Default<Args>,
  2141. # template <Args> class Ignore3>
  2142. # void Function() {};
  2143. #
  2144. # To avoid template argument cases, we scan forward and look for
  2145. # an unmatched '>'. If we see one, assume we are inside a
  2146. # template argument list.
  2147. end_declaration = len(class_decl_match.group(1))
  2148. if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
  2149. self.stack.append(_ClassInfo(
  2150. class_decl_match.group(3), class_decl_match.group(2),
  2151. clean_lines, linenum))
  2152. line = class_decl_match.group(4)
  2153. # If we have not yet seen the opening brace for the innermost block,
  2154. # run checks here.
  2155. if not self.SeenOpenBrace():
  2156. self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
  2157. # Update access control if we are inside a class/struct
  2158. if self.stack and isinstance(self.stack[-1], _ClassInfo):
  2159. classinfo = self.stack[-1]
  2160. access_match = Match(
  2161. r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
  2162. r':(?:[^:]|$)',
  2163. line)
  2164. if access_match:
  2165. classinfo.access = access_match.group(2)
  2166. # Check that access keywords are indented +1 space. Skip this
  2167. # check if the keywords are not preceded by whitespaces.
  2168. indent = access_match.group(1)
  2169. if (len(indent) != classinfo.class_indent + 1 and
  2170. Match(r'^\s*$', indent)):
  2171. if classinfo.is_struct:
  2172. parent = 'struct ' + classinfo.name
  2173. else:
  2174. parent = 'class ' + classinfo.name
  2175. slots = ''
  2176. if access_match.group(3):
  2177. slots = access_match.group(3)
  2178. error(filename, linenum, 'whitespace/indent', 3,
  2179. '%s%s: should be indented +1 space inside %s' % (
  2180. access_match.group(2), slots, parent))
  2181. # Consume braces or semicolons from what's left of the line
  2182. while True:
  2183. # Match first brace, semicolon, or closed parenthesis.
  2184. matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
  2185. if not matched:
  2186. break
  2187. token = matched.group(1)
  2188. if token == '{':
  2189. # If namespace or class hasn't seen a opening brace yet, mark
  2190. # namespace/class head as complete. Push a new block onto the
  2191. # stack otherwise.
  2192. if not self.SeenOpenBrace():
  2193. self.stack[-1].seen_open_brace = True
  2194. elif Match(r'^extern\s*"[^"]*"\s*\{', line):
  2195. self.stack.append(_ExternCInfo(linenum))
  2196. else:
  2197. self.stack.append(_BlockInfo(linenum, True))
  2198. if _MATCH_ASM.match(line):
  2199. self.stack[-1].inline_asm = _BLOCK_ASM
  2200. elif token == ';' or token == ')':
  2201. # If we haven't seen an opening brace yet, but we already saw
  2202. # a semicolon, this is probably a forward declaration. Pop
  2203. # the stack for these.
  2204. #
  2205. # Similarly, if we haven't seen an opening brace yet, but we
  2206. # already saw a closing parenthesis, then these are probably
  2207. # function arguments with extra "class" or "struct" keywords.
  2208. # Also pop these stack for these.
  2209. if not self.SeenOpenBrace():
  2210. self.stack.pop()
  2211. else: # token == '}'
  2212. # Perform end of block checks and pop the stack.
  2213. if self.stack:
  2214. self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
  2215. self.stack.pop()
  2216. line = matched.group(2)
  2217. def InnermostClass(self):
  2218. """Get class info on the top of the stack.
  2219. Returns:
  2220. A _ClassInfo object if we are inside a class, or None otherwise.
  2221. """
  2222. for i in range(len(self.stack), 0, -1):
  2223. classinfo = self.stack[i - 1]
  2224. if isinstance(classinfo, _ClassInfo):
  2225. return classinfo
  2226. return None
  2227. def CheckCompletedBlocks(self, filename, error):
  2228. """Checks that all classes and namespaces have been completely parsed.
  2229. Call this when all lines in a file have been processed.
  2230. Args:
  2231. filename: The name of the current file.
  2232. error: The function to call with any errors found.
  2233. """
  2234. # Note: This test can result in false positives if #ifdef constructs
  2235. # get in the way of brace matching. See the testBuildClass test in
  2236. # cpplint_unittest.py for an example of this.
  2237. for obj in self.stack:
  2238. if isinstance(obj, _ClassInfo):
  2239. error(filename, obj.starting_linenum, 'build/class', 5,
  2240. 'Failed to find complete declaration of class %s' %
  2241. obj.name)
  2242. elif isinstance(obj, _NamespaceInfo):
  2243. error(filename, obj.starting_linenum, 'build/namespaces', 5,
  2244. 'Failed to find complete declaration of namespace %s' %
  2245. obj.name)
  2246. def CheckForNonStandardConstructs(filename, clean_lines, linenum,
  2247. nesting_state, error):
  2248. r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
  2249. Complain about several constructs which gcc-2 accepts, but which are
  2250. not standard C++. Warning about these in lint is one way to ease the
  2251. transition to new compilers.
  2252. - put storage class first (e.g. "static const" instead of "const static").
  2253. - "%lld" instead of %qd" in printf-type functions.
  2254. - "%1$d" is non-standard in printf-type functions.
  2255. - "\%" is an undefined character escape sequence.
  2256. - text after #endif is not allowed.
  2257. - invalid inner-style forward declaration.
  2258. - >? and <? operators, and their >?= and <?= cousins.
  2259. Additionally, check for constructor/destructor style violations and reference
  2260. members, as it is very convenient to do so while checking for
  2261. gcc-2 compliance.
  2262. Args:
  2263. filename: The name of the current file.
  2264. clean_lines: A CleansedLines instance containing the file.
  2265. linenum: The number of the line to check.
  2266. nesting_state: A NestingState instance which maintains information about
  2267. the current stack of nested blocks being parsed.
  2268. error: A callable to which errors are reported, which takes 4 arguments:
  2269. filename, line number, error level, and message
  2270. """
  2271. # Remove comments from the line, but leave in strings for now.
  2272. line = clean_lines.lines[linenum]
  2273. if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
  2274. error(filename, linenum, 'runtime/printf_format', 3,
  2275. '%q in format strings is deprecated. Use %ll instead.')
  2276. if Search(r'printf\s*\(.*".*%\d+\$', line):
  2277. error(filename, linenum, 'runtime/printf_format', 2,
  2278. '%N$ formats are unconventional. Try rewriting to avoid them.')
  2279. # Remove escaped backslashes before looking for undefined escapes.
  2280. line = line.replace('\\\\', '')
  2281. if Search(r'("|\').*\\(%|\[|\(|{)', line):
  2282. error(filename, linenum, 'build/printf_format', 3,
  2283. '%, [, (, and { are undefined character escapes. Unescape them.')
  2284. # For the rest, work with both comments and strings removed.
  2285. line = clean_lines.elided[linenum]
  2286. if Search(r'\b(const|volatile|void|char|short|int|long'
  2287. r'|float|double|signed|unsigned'
  2288. r'|schar|u?int8|u?int16|u?int32|u?int64)'
  2289. r'\s+(register|static|extern|typedef)\b',
  2290. line):
  2291. error(filename, linenum, 'build/storage_class', 5,
  2292. 'Storage-class specifier (static, extern, typedef, etc) should be '
  2293. 'at the beginning of the declaration.')
  2294. if Match(r'\s*#\s*endif\s*[^/\s]+', line):
  2295. error(filename, linenum, 'build/endif_comment', 5,
  2296. 'Uncommented text after #endif is non-standard. Use a comment.')
  2297. if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
  2298. error(filename, linenum, 'build/forward_decl', 5,
  2299. 'Inner-style forward declarations are invalid. Remove this line.')
  2300. if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
  2301. line):
  2302. error(filename, linenum, 'build/deprecated', 3,
  2303. '>? and <? (max and min) operators are non-standard and deprecated.')
  2304. if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
  2305. # TODO(unknown): Could it be expanded safely to arbitrary references,
  2306. # without triggering too many false positives? The first
  2307. # attempt triggered 5 warnings for mostly benign code in the regtest, hence
  2308. # the restriction.
  2309. # Here's the original regexp, for the reference:
  2310. # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
  2311. # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
  2312. error(filename, linenum, 'runtime/member_string_references', 2,
  2313. 'const string& members are dangerous. It is much better to use '
  2314. 'alternatives, such as pointers or simple constants.')
  2315. # Everything else in this function operates on class declarations.
  2316. # Return early if the top of the nesting stack is not a class, or if
  2317. # the class head is not completed yet.
  2318. classinfo = nesting_state.InnermostClass()
  2319. if not classinfo or not classinfo.seen_open_brace:
  2320. return
  2321. # The class may have been declared with namespace or classname qualifiers.
  2322. # The constructor and destructor will not have those qualifiers.
  2323. base_classname = classinfo.name.split('::')[-1]
  2324. # Look for single-argument constructors that aren't marked explicit.
  2325. # Technically a valid construct, but against style.
  2326. explicit_constructor_match = Match(
  2327. r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?'
  2328. r'(?:(?:inline|constexpr)\s+)*%s\s*'
  2329. r'\(((?:[^()]|\([^()]*\))*)\)'
  2330. % re.escape(base_classname),
  2331. line)
  2332. if explicit_constructor_match:
  2333. is_marked_explicit = explicit_constructor_match.group(1)
  2334. if not explicit_constructor_match.group(2):
  2335. constructor_args = []
  2336. else:
  2337. constructor_args = explicit_constructor_match.group(2).split(',')
  2338. # collapse arguments so that commas in template parameter lists and function
  2339. # argument parameter lists don't split arguments in two
  2340. i = 0
  2341. while i < len(constructor_args):
  2342. constructor_arg = constructor_args[i]
  2343. while (constructor_arg.count('<') > constructor_arg.count('>') or
  2344. constructor_arg.count('(') > constructor_arg.count(')')):
  2345. constructor_arg += ',' + constructor_args[i + 1]
  2346. del constructor_args[i + 1]
  2347. constructor_args[i] = constructor_arg
  2348. i += 1
  2349. defaulted_args = [arg for arg in constructor_args if '=' in arg]
  2350. noarg_constructor = (not constructor_args or # empty arg list
  2351. # 'void' arg specifier
  2352. (len(constructor_args) == 1 and
  2353. constructor_args[0].strip() == 'void'))
  2354. onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
  2355. not noarg_constructor) or
  2356. # all but at most one arg defaulted
  2357. (len(constructor_args) >= 1 and
  2358. not noarg_constructor and
  2359. len(defaulted_args) >= len(constructor_args) - 1))
  2360. initializer_list_constructor = bool(
  2361. onearg_constructor and
  2362. Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
  2363. copy_constructor = bool(
  2364. onearg_constructor and
  2365. Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
  2366. % re.escape(base_classname), constructor_args[0].strip()))
  2367. if (not is_marked_explicit and
  2368. onearg_constructor and
  2369. not initializer_list_constructor and
  2370. not copy_constructor):
  2371. if defaulted_args:
  2372. error(filename, linenum, 'runtime/explicit', 5,
  2373. 'Constructors callable with one argument '
  2374. 'should be marked explicit.')
  2375. else:
  2376. error(filename, linenum, 'runtime/explicit', 5,
  2377. 'Single-parameter constructors should be marked explicit.')
  2378. elif is_marked_explicit and not onearg_constructor:
  2379. if noarg_constructor:
  2380. error(filename, linenum, 'runtime/explicit', 5,
  2381. 'Zero-parameter constructors should not be marked explicit.')
  2382. def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
  2383. """Checks for the correctness of various spacing around function calls.
  2384. Args:
  2385. filename: The name of the current file.
  2386. clean_lines: A CleansedLines instance containing the file.
  2387. linenum: The number of the line to check.
  2388. error: The function to call with any errors found.
  2389. """
  2390. line = clean_lines.elided[linenum]
  2391. # Since function calls often occur inside if/for/while/switch
  2392. # expressions - which have their own, more liberal conventions - we
  2393. # first see if we should be looking inside such an expression for a
  2394. # function call, to which we can apply more strict standards.
  2395. fncall = line # if there's no control flow construct, look at whole line
  2396. for pattern in (r'\bif\s*\((.*)\)\s*{',
  2397. r'\bfor\s*\((.*)\)\s*{',
  2398. r'\bwhile\s*\((.*)\)\s*[{;]',
  2399. r'\bswitch\s*\((.*)\)\s*{'):
  2400. match = Search(pattern, line)
  2401. if match:
  2402. fncall = match.group(1) # look inside the parens for function calls
  2403. break
  2404. # Except in if/for/while/switch, there should never be space
  2405. # immediately inside parens (eg "f( 3, 4 )"). We make an exception
  2406. # for nested parens ( (a+b) + c ). Likewise, there should never be
  2407. # a space before a ( when it's a function argument. I assume it's a
  2408. # function argument when the char before the whitespace is legal in
  2409. # a function name (alnum + _) and we're not starting a macro. Also ignore
  2410. # pointers and references to arrays and functions coz they're too tricky:
  2411. # we use a very simple way to recognize these:
  2412. # " (something)(maybe-something)" or
  2413. # " (something)(maybe-something," or
  2414. # " (something)[something]"
  2415. # Note that we assume the contents of [] to be short enough that
  2416. # they'll never need to wrap.
  2417. if ( # Ignore control structures.
  2418. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
  2419. fncall) and
  2420. # Ignore pointers/references to functions.
  2421. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
  2422. # Ignore pointers/references to arrays.
  2423. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
  2424. if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
  2425. error(filename, linenum, 'whitespace/parens', 4,
  2426. 'Extra space after ( in function call')
  2427. elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
  2428. error(filename, linenum, 'whitespace/parens', 2,
  2429. 'Extra space after (')
  2430. if (Search(r'\w\s+\(', fncall) and
  2431. not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and
  2432. not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and
  2433. not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
  2434. not Search(r'\bcase\s+\(', fncall)):
  2435. # TODO(unknown): Space after an operator function seem to be a common
  2436. # error, silence those for now by restricting them to highest verbosity.
  2437. if Search(r'\boperator_*\b', line):
  2438. error(filename, linenum, 'whitespace/parens', 0,
  2439. 'Extra space before ( in function call')
  2440. else:
  2441. error(filename, linenum, 'whitespace/parens', 4,
  2442. 'Extra space before ( in function call')
  2443. # If the ) is followed only by a newline or a { + newline, assume it's
  2444. # part of a control statement (if/while/etc), and don't complain
  2445. if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
  2446. # If the closing parenthesis is preceded by only whitespaces,
  2447. # try to give a more descriptive error message.
  2448. if Search(r'^\s+\)', fncall):
  2449. error(filename, linenum, 'whitespace/parens', 2,
  2450. 'Closing ) should be moved to the previous line')
  2451. else:
  2452. error(filename, linenum, 'whitespace/parens', 2,
  2453. 'Extra space before )')
  2454. def IsBlankLine(line):
  2455. """Returns true if the given line is blank.
  2456. We consider a line to be blank if the line is empty or consists of
  2457. only white spaces.
  2458. Args:
  2459. line: A line of a string.
  2460. Returns:
  2461. True, if the given line is blank.
  2462. """
  2463. return not line or line.isspace()
  2464. def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
  2465. error):
  2466. is_namespace_indent_item = (
  2467. len(nesting_state.stack) > 1 and
  2468. nesting_state.stack[-1].check_namespace_indentation and
  2469. isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and
  2470. nesting_state.previous_stack_top == nesting_state.stack[-2])
  2471. if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
  2472. clean_lines.elided, line):
  2473. CheckItemIndentationInNamespace(filename, clean_lines.elided,
  2474. line, error)
  2475. def CheckForFunctionLengths(filename, clean_lines, linenum,
  2476. function_state, error):
  2477. """Reports for long function bodies.
  2478. For an overview why this is done, see:
  2479. https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
  2480. Uses a simplistic algorithm assuming other style guidelines
  2481. (especially spacing) are followed.
  2482. Only checks unindented functions, so class members are unchecked.
  2483. Trivial bodies are unchecked, so constructors with huge initializer lists
  2484. may be missed.
  2485. Blank/comment lines are not counted so as to avoid encouraging the removal
  2486. of vertical space and comments just to get through a lint check.
  2487. NOLINT *on the last line of a function* disables this check.
  2488. Args:
  2489. filename: The name of the current file.
  2490. clean_lines: A CleansedLines instance containing the file.
  2491. linenum: The number of the line to check.
  2492. function_state: Current function name and lines in body so far.
  2493. error: The function to call with any errors found.
  2494. """
  2495. lines = clean_lines.lines
  2496. line = lines[linenum]
  2497. joined_line = ''
  2498. starting_func = False
  2499. regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
  2500. match_result = Match(regexp, line)
  2501. if match_result:
  2502. # If the name is all caps and underscores, figure it's a macro and
  2503. # ignore it, unless it's TEST or TEST_F.
  2504. function_name = match_result.group(1).split()[-1]
  2505. if function_name == 'TEST' or function_name == 'TEST_F' or (
  2506. not Match(r'[A-Z_]+$', function_name)):
  2507. starting_func = True
  2508. if starting_func:
  2509. body_found = False
  2510. for start_linenum in xrange(linenum, clean_lines.NumLines()):
  2511. start_line = lines[start_linenum]
  2512. joined_line += ' ' + start_line.lstrip()
  2513. if Search(r'(;|})', start_line): # Declarations and trivial functions
  2514. body_found = True
  2515. break # ... ignore
  2516. elif Search(r'{', start_line):
  2517. body_found = True
  2518. function = Search(r'((\w|:)*)\(', line).group(1)
  2519. if Match(r'TEST', function): # Handle TEST... macros
  2520. parameter_regexp = Search(r'(\(.*\))', joined_line)
  2521. if parameter_regexp: # Ignore bad syntax
  2522. function += parameter_regexp.group(1)
  2523. else:
  2524. function += '()'
  2525. function_state.Begin(function)
  2526. break
  2527. if not body_found:
  2528. # No body for the function (or evidence of a non-function) was found.
  2529. error(filename, linenum, 'readability/fn_size', 5,
  2530. 'Lint failed to find start of function body.')
  2531. elif Match(r'^\}\s*$', line): # function end
  2532. function_state.Check(error, filename, linenum)
  2533. function_state.End()
  2534. elif not Match(r'^\s*$', line):
  2535. function_state.Count() # Count non-blank/non-comment lines.
  2536. _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
  2537. def CheckComment(line, filename, linenum, next_line_start, error):
  2538. """Checks for common mistakes in comments.
  2539. Args:
  2540. line: The line in question.
  2541. filename: The name of the current file.
  2542. linenum: The number of the line to check.
  2543. next_line_start: The first non-whitespace column of the next line.
  2544. error: The function to call with any errors found.
  2545. """
  2546. commentpos = line.find('//')
  2547. if commentpos != -1:
  2548. # Check if the // may be in quotes. If so, ignore it
  2549. if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
  2550. # Allow one space for new scopes, two spaces otherwise:
  2551. if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
  2552. ((commentpos >= 1 and
  2553. line[commentpos-1] not in string.whitespace) or
  2554. (commentpos >= 2 and
  2555. line[commentpos-2] not in string.whitespace))):
  2556. error(filename, linenum, 'whitespace/comments', 2,
  2557. 'At least two spaces is best between code and comments')
  2558. # Checks for common mistakes in TODO comments.
  2559. comment = line[commentpos:]
  2560. match = _RE_PATTERN_TODO.match(comment)
  2561. if match:
  2562. # One whitespace is correct; zero whitespace is handled elsewhere.
  2563. leading_whitespace = match.group(1)
  2564. if len(leading_whitespace) > 1:
  2565. error(filename, linenum, 'whitespace/todo', 2,
  2566. 'Too many spaces before TODO')
  2567. username = match.group(2)
  2568. if not username:
  2569. error(filename, linenum, 'readability/todo', 2,
  2570. 'Missing username in TODO; it should look like '
  2571. '"// TODO(my_username): Stuff."')
  2572. middle_whitespace = match.group(3)
  2573. # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
  2574. if middle_whitespace != ' ' and middle_whitespace != '':
  2575. error(filename, linenum, 'whitespace/todo', 2,
  2576. 'TODO(my_username) should be followed by a space')
  2577. # If the comment contains an alphanumeric character, there
  2578. # should be a space somewhere between it and the // unless
  2579. # it's a /// or //! Doxygen comment.
  2580. if (Match(r'//[^ ]*\w', comment) and
  2581. not Match(r'(///|//\!)(\s+|$)', comment)):
  2582. error(filename, linenum, 'whitespace/comments', 4,
  2583. 'Should have a space between // and comment')
  2584. def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
  2585. """Checks for the correctness of various spacing issues in the code.
  2586. Things we check for: spaces around operators, spaces after
  2587. if/for/while/switch, no spaces around parens in function calls, two
  2588. spaces between code and comment, don't start a block with a blank
  2589. line, don't end a function with a blank line, don't add a blank line
  2590. after public/protected/private, don't have too many blank lines in a row.
  2591. Args:
  2592. filename: The name of the current file.
  2593. clean_lines: A CleansedLines instance containing the file.
  2594. linenum: The number of the line to check.
  2595. nesting_state: A NestingState instance which maintains information about
  2596. the current stack of nested blocks being parsed.
  2597. error: The function to call with any errors found.
  2598. """
  2599. # Don't use "elided" lines here, otherwise we can't check commented lines.
  2600. # Don't want to use "raw" either, because we don't want to check inside C++11
  2601. # raw strings,
  2602. raw = clean_lines.lines_without_raw_strings
  2603. line = raw[linenum]
  2604. # Before nixing comments, check if the line is blank for no good
  2605. # reason. This includes the first line after a block is opened, and
  2606. # blank lines at the end of a function (ie, right before a line like '}'
  2607. #
  2608. # Skip all the blank line checks if we are immediately inside a
  2609. # namespace body. In other words, don't issue blank line warnings
  2610. # for this block:
  2611. # namespace {
  2612. #
  2613. # }
  2614. #
  2615. # A warning about missing end of namespace comments will be issued instead.
  2616. #
  2617. # Also skip blank line checks for 'extern "C"' blocks, which are formatted
  2618. # like namespaces.
  2619. if (IsBlankLine(line) and
  2620. not nesting_state.InNamespaceBody() and
  2621. not nesting_state.InExternC()):
  2622. elided = clean_lines.elided
  2623. prev_line = elided[linenum - 1]
  2624. prevbrace = prev_line.rfind('{')
  2625. # TODO(unknown): Don't complain if line before blank line, and line after,
  2626. # both start with alnums and are indented the same amount.
  2627. # This ignores whitespace at the start of a namespace block
  2628. # because those are not usually indented.
  2629. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
  2630. # OK, we have a blank line at the start of a code block. Before we
  2631. # complain, we check if it is an exception to the rule: The previous
  2632. # non-empty line has the parameters of a function header that are indented
  2633. # 4 spaces (because they did not fit in a 80 column line when placed on
  2634. # the same line as the function name). We also check for the case where
  2635. # the previous line is indented 6 spaces, which may happen when the
  2636. # initializers of a constructor do not fit into a 80 column line.
  2637. exception = False
  2638. if Match(r' {6}\w', prev_line): # Initializer list?
  2639. # We are looking for the opening column of initializer list, which
  2640. # should be indented 4 spaces to cause 6 space indentation afterwards.
  2641. search_position = linenum-2
  2642. while (search_position >= 0
  2643. and Match(r' {6}\w', elided[search_position])):
  2644. search_position -= 1
  2645. exception = (search_position >= 0
  2646. and elided[search_position][:5] == ' :')
  2647. else:
  2648. # Search for the function arguments or an initializer list. We use a
  2649. # simple heuristic here: If the line is indented 4 spaces; and we have a
  2650. # closing paren, without the opening paren, followed by an opening brace
  2651. # or colon (for initializer lists) we assume that it is the last line of
  2652. # a function header. If we have a colon indented 4 spaces, it is an
  2653. # initializer list.
  2654. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
  2655. prev_line)
  2656. or Match(r' {4}:', prev_line))
  2657. if not exception:
  2658. error(filename, linenum, 'whitespace/blank_line', 2,
  2659. 'Redundant blank line at the start of a code block '
  2660. 'should be deleted.')
  2661. # Ignore blank lines at the end of a block in a long if-else
  2662. # chain, like this:
  2663. # if (condition1) {
  2664. # // Something followed by a blank line
  2665. #
  2666. # } else if (condition2) {
  2667. # // Something else
  2668. # }
  2669. if linenum + 1 < clean_lines.NumLines():
  2670. next_line = raw[linenum + 1]
  2671. if (next_line
  2672. and Match(r'\s*}', next_line)
  2673. and next_line.find('} else ') == -1):
  2674. error(filename, linenum, 'whitespace/blank_line', 3,
  2675. 'Redundant blank line at the end of a code block '
  2676. 'should be deleted.')
  2677. matched = Match(r'\s*(public|protected|private):', prev_line)
  2678. if matched:
  2679. error(filename, linenum, 'whitespace/blank_line', 3,
  2680. 'Do not leave a blank line after "%s:"' % matched.group(1))
  2681. # Next, check comments
  2682. next_line_start = 0
  2683. if linenum + 1 < clean_lines.NumLines():
  2684. next_line = raw[linenum + 1]
  2685. next_line_start = len(next_line) - len(next_line.lstrip())
  2686. CheckComment(line, filename, linenum, next_line_start, error)
  2687. # get rid of comments and strings
  2688. line = clean_lines.elided[linenum]
  2689. # You shouldn't have spaces before your brackets, except maybe after
  2690. # 'delete []' or 'return []() {};'
  2691. if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line):
  2692. error(filename, linenum, 'whitespace/braces', 5,
  2693. 'Extra space before [')
  2694. # In range-based for, we wanted spaces before and after the colon, but
  2695. # not around "::" tokens that might appear.
  2696. if (Search(r'for *\(.*[^:]:[^: ]', line) or
  2697. Search(r'for *\(.*[^: ]:[^:]', line)):
  2698. error(filename, linenum, 'whitespace/forcolon', 2,
  2699. 'Missing space around colon in range-based for loop')
  2700. def CheckOperatorSpacing(filename, clean_lines, linenum, error):
  2701. """Checks for horizontal spacing around operators.
  2702. Args:
  2703. filename: The name of the current file.
  2704. clean_lines: A CleansedLines instance containing the file.
  2705. linenum: The number of the line to check.
  2706. error: The function to call with any errors found.
  2707. """
  2708. line = clean_lines.elided[linenum]
  2709. # Don't try to do spacing checks for operator methods. Do this by
  2710. # replacing the troublesome characters with something else,
  2711. # preserving column position for all other characters.
  2712. #
  2713. # The replacement is done repeatedly to avoid false positives from
  2714. # operators that call operators.
  2715. while True:
  2716. match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
  2717. if match:
  2718. line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
  2719. else:
  2720. break
  2721. # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
  2722. # Otherwise not. Note we only check for non-spaces on *both* sides;
  2723. # sometimes people put non-spaces on one side when aligning ='s among
  2724. # many lines (not that this is behavior that I approve of...)
  2725. if ((Search(r'[\w.]=', line) or
  2726. Search(r'=[\w.]', line))
  2727. and not Search(r'\b(if|while|for) ', line)
  2728. # Operators taken from [lex.operators] in C++11 standard.
  2729. and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
  2730. and not Search(r'operator=', line)):
  2731. error(filename, linenum, 'whitespace/operators', 4,
  2732. 'Missing spaces around =')
  2733. # It's ok not to have spaces around binary operators like + - * /, but if
  2734. # there's too little whitespace, we get concerned. It's hard to tell,
  2735. # though, so we punt on this one for now. TODO.
  2736. # You should always have whitespace around binary operators.
  2737. #
  2738. # Check <= and >= first to avoid false positives with < and >, then
  2739. # check non-include lines for spacing around < and >.
  2740. #
  2741. # If the operator is followed by a comma, assume it's be used in a
  2742. # macro context and don't do any checks. This avoids false
  2743. # positives.
  2744. #
  2745. # Note that && is not included here. This is because there are too
  2746. # many false positives due to RValue references.
  2747. match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
  2748. if match:
  2749. error(filename, linenum, 'whitespace/operators', 3,
  2750. 'Missing spaces around %s' % match.group(1))
  2751. elif not Match(r'#.*include', line):
  2752. # Look for < that is not surrounded by spaces. This is only
  2753. # triggered if both sides are missing spaces, even though
  2754. # technically should should flag if at least one side is missing a
  2755. # space. This is done to avoid some false positives with shifts.
  2756. match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
  2757. if match:
  2758. (_, _, end_pos) = CloseExpression(
  2759. clean_lines, linenum, len(match.group(1)))
  2760. if end_pos <= -1:
  2761. error(filename, linenum, 'whitespace/operators', 3,
  2762. 'Missing spaces around <')
  2763. # Look for > that is not surrounded by spaces. Similar to the
  2764. # above, we only trigger if both sides are missing spaces to avoid
  2765. # false positives with shifts.
  2766. match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
  2767. if match:
  2768. (_, _, start_pos) = ReverseCloseExpression(
  2769. clean_lines, linenum, len(match.group(1)))
  2770. if start_pos <= -1:
  2771. error(filename, linenum, 'whitespace/operators', 3,
  2772. 'Missing spaces around >')
  2773. # We allow no-spaces around << when used like this: 10<<20, but
  2774. # not otherwise (particularly, not when used as streams)
  2775. #
  2776. # We also allow operators following an opening parenthesis, since
  2777. # those tend to be macros that deal with operators.
  2778. match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
  2779. if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
  2780. not (match.group(1) == 'operator' and match.group(2) == ';')):
  2781. error(filename, linenum, 'whitespace/operators', 3,
  2782. 'Missing spaces around <<')
  2783. # We allow no-spaces around >> for almost anything. This is because
  2784. # C++11 allows ">>" to close nested templates, which accounts for
  2785. # most cases when ">>" is not followed by a space.
  2786. #
  2787. # We still warn on ">>" followed by alpha character, because that is
  2788. # likely due to ">>" being used for right shifts, e.g.:
  2789. # value >> alpha
  2790. #
  2791. # When ">>" is used to close templates, the alphanumeric letter that
  2792. # follows would be part of an identifier, and there should still be
  2793. # a space separating the template type and the identifier.
  2794. # type<type<type>> alpha
  2795. match = Search(r'>>[a-zA-Z_]', line)
  2796. if match:
  2797. error(filename, linenum, 'whitespace/operators', 3,
  2798. 'Missing spaces around >>')
  2799. # There shouldn't be space around unary operators
  2800. match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
  2801. if match:
  2802. error(filename, linenum, 'whitespace/operators', 4,
  2803. 'Extra space for operator %s' % match.group(1))
  2804. def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
  2805. """Checks for horizontal spacing around parentheses.
  2806. Args:
  2807. filename: The name of the current file.
  2808. clean_lines: A CleansedLines instance containing the file.
  2809. linenum: The number of the line to check.
  2810. error: The function to call with any errors found.
  2811. """
  2812. line = clean_lines.elided[linenum]
  2813. # No spaces after an if, while, switch, or for
  2814. match = Search(r' (if\(|for\(|while\(|switch\()', line)
  2815. if match:
  2816. error(filename, linenum, 'whitespace/parens', 5,
  2817. 'Missing space before ( in %s' % match.group(1))
  2818. # For if/for/while/switch, the left and right parens should be
  2819. # consistent about how many spaces are inside the parens, and
  2820. # there should either be zero or one spaces inside the parens.
  2821. # We don't want: "if ( foo)" or "if ( foo )".
  2822. # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
  2823. match = Search(r'\b(if|for|while|switch)\s*'
  2824. r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
  2825. line)
  2826. if match:
  2827. if len(match.group(2)) != len(match.group(4)):
  2828. if not (match.group(3) == ';' and
  2829. len(match.group(2)) == 1 + len(match.group(4)) or
  2830. not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
  2831. error(filename, linenum, 'whitespace/parens', 5,
  2832. 'Mismatching spaces inside () in %s' % match.group(1))
  2833. if len(match.group(2)) not in [0, 1]:
  2834. error(filename, linenum, 'whitespace/parens', 5,
  2835. 'Should have zero or one spaces inside ( and ) in %s' %
  2836. match.group(1))
  2837. def CheckCommaSpacing(filename, clean_lines, linenum, error):
  2838. """Checks for horizontal spacing near commas and semicolons.
  2839. Args:
  2840. filename: The name of the current file.
  2841. clean_lines: A CleansedLines instance containing the file.
  2842. linenum: The number of the line to check.
  2843. error: The function to call with any errors found.
  2844. """
  2845. raw = clean_lines.lines_without_raw_strings
  2846. line = clean_lines.elided[linenum]
  2847. # You should always have a space after a comma (either as fn arg or operator)
  2848. #
  2849. # This does not apply when the non-space character following the
  2850. # comma is another comma, since the only time when that happens is
  2851. # for empty macro arguments.
  2852. #
  2853. # We run this check in two passes: first pass on elided lines to
  2854. # verify that lines contain missing whitespaces, second pass on raw
  2855. # lines to confirm that those missing whitespaces are not due to
  2856. # elided comments.
  2857. if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
  2858. Search(r',[^,\s]', raw[linenum])):
  2859. error(filename, linenum, 'whitespace/comma', 3,
  2860. 'Missing space after ,')
  2861. # You should always have a space after a semicolon
  2862. # except for few corner cases
  2863. # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
  2864. # space after ;
  2865. if Search(r';[^\s};\\)/]', line):
  2866. error(filename, linenum, 'whitespace/semicolon', 3,
  2867. 'Missing space after ;')
  2868. def _IsType(clean_lines, nesting_state, expr):
  2869. """Check if expression looks like a type name, returns true if so.
  2870. Args:
  2871. clean_lines: A CleansedLines instance containing the file.
  2872. nesting_state: A NestingState instance which maintains information about
  2873. the current stack of nested blocks being parsed.
  2874. expr: The expression to check.
  2875. Returns:
  2876. True, if token looks like a type.
  2877. """
  2878. # Keep only the last token in the expression
  2879. last_word = Match(r'^.*(\b\S+)$', expr)
  2880. if last_word:
  2881. token = last_word.group(1)
  2882. else:
  2883. token = expr
  2884. # Match native types and stdint types
  2885. if _TYPES.match(token):
  2886. return True
  2887. # Try a bit harder to match templated types. Walk up the nesting
  2888. # stack until we find something that resembles a typename
  2889. # declaration for what we are looking for.
  2890. typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
  2891. r'\b')
  2892. block_index = len(nesting_state.stack) - 1
  2893. while block_index >= 0:
  2894. if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
  2895. return False
  2896. # Found where the opening brace is. We want to scan from this
  2897. # line up to the beginning of the function, minus a few lines.
  2898. # template <typename Type1, // stop scanning here
  2899. # ...>
  2900. # class C
  2901. # : public ... { // start scanning here
  2902. last_line = nesting_state.stack[block_index].starting_linenum
  2903. next_block_start = 0
  2904. if block_index > 0:
  2905. next_block_start = nesting_state.stack[block_index - 1].starting_linenum
  2906. first_line = last_line
  2907. while first_line >= next_block_start:
  2908. if clean_lines.elided[first_line].find('template') >= 0:
  2909. break
  2910. first_line -= 1
  2911. if first_line < next_block_start:
  2912. # Didn't find any "template" keyword before reaching the next block,
  2913. # there are probably no template things to check for this block
  2914. block_index -= 1
  2915. continue
  2916. # Look for typename in the specified range
  2917. for i in xrange(first_line, last_line + 1, 1):
  2918. if Search(typename_pattern, clean_lines.elided[i]):
  2919. return True
  2920. block_index -= 1
  2921. return False
  2922. def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
  2923. """Checks for horizontal spacing near commas.
  2924. Args:
  2925. filename: The name of the current file.
  2926. clean_lines: A CleansedLines instance containing the file.
  2927. linenum: The number of the line to check.
  2928. nesting_state: A NestingState instance which maintains information about
  2929. the current stack of nested blocks being parsed.
  2930. error: The function to call with any errors found.
  2931. """
  2932. line = clean_lines.elided[linenum]
  2933. # Except after an opening paren, or after another opening brace (in case of
  2934. # an initializer list, for instance), you should have spaces before your
  2935. # braces when they are delimiting blocks, classes, namespaces etc.
  2936. # And since you should never have braces at the beginning of a line,
  2937. # this is an easy test. Except that braces used for initialization don't
  2938. # follow the same rule; we often don't want spaces before those.
  2939. match = Match(r'^(.*[^ ({>]){', line)
  2940. if match:
  2941. # Try a bit harder to check for brace initialization. This
  2942. # happens in one of the following forms:
  2943. # Constructor() : initializer_list_{} { ... }
  2944. # Constructor{}.MemberFunction()
  2945. # Type variable{};
  2946. # FunctionCall(type{}, ...);
  2947. # LastArgument(..., type{});
  2948. # LOG(INFO) << type{} << " ...";
  2949. # map_of_type[{...}] = ...;
  2950. # ternary = expr ? new type{} : nullptr;
  2951. # OuterTemplate<InnerTemplateConstructor<Type>{}>
  2952. #
  2953. # We check for the character following the closing brace, and
  2954. # silence the warning if it's one of those listed above, i.e.
  2955. # "{.;,)<>]:".
  2956. #
  2957. # To account for nested initializer list, we allow any number of
  2958. # closing braces up to "{;,)<". We can't simply silence the
  2959. # warning on first sight of closing brace, because that would
  2960. # cause false negatives for things that are not initializer lists.
  2961. # Silence this: But not this:
  2962. # Outer{ if (...) {
  2963. # Inner{...} if (...){ // Missing space before {
  2964. # }; }
  2965. #
  2966. # There is a false negative with this approach if people inserted
  2967. # spurious semicolons, e.g. "if (cond){};", but we will catch the
  2968. # spurious semicolon with a separate check.
  2969. leading_text = match.group(1)
  2970. (endline, endlinenum, endpos) = CloseExpression(
  2971. clean_lines, linenum, len(match.group(1)))
  2972. trailing_text = ''
  2973. if endpos > -1:
  2974. trailing_text = endline[endpos:]
  2975. for offset in xrange(endlinenum + 1,
  2976. min(endlinenum + 3, clean_lines.NumLines() - 1)):
  2977. trailing_text += clean_lines.elided[offset]
  2978. # We also suppress warnings for `uint64_t{expression}` etc., as the style
  2979. # guide recommends brace initialization for integral types to avoid
  2980. # overflow/truncation.
  2981. if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
  2982. and not _IsType(clean_lines, nesting_state, leading_text)):
  2983. error(filename, linenum, 'whitespace/braces', 5,
  2984. 'Missing space before {')
  2985. # Make sure '} else {' has spaces.
  2986. if Search(r'}else', line):
  2987. error(filename, linenum, 'whitespace/braces', 5,
  2988. 'Missing space before else')
  2989. # You shouldn't have a space before a semicolon at the end of the line.
  2990. # There's a special case for "for" since the style guide allows space before
  2991. # the semicolon there.
  2992. if Search(r':\s*;\s*$', line):
  2993. error(filename, linenum, 'whitespace/semicolon', 5,
  2994. 'Semicolon defining empty statement. Use {} instead.')
  2995. elif Search(r'^\s*;\s*$', line):
  2996. error(filename, linenum, 'whitespace/semicolon', 5,
  2997. 'Line contains only semicolon. If this should be an empty statement, '
  2998. 'use {} instead.')
  2999. elif (Search(r'\s+;\s*$', line) and
  3000. not Search(r'\bfor\b', line)):
  3001. error(filename, linenum, 'whitespace/semicolon', 5,
  3002. 'Extra space before last semicolon. If this should be an empty '
  3003. 'statement, use {} instead.')
  3004. def IsDecltype(clean_lines, linenum, column):
  3005. """Check if the token ending on (linenum, column) is decltype().
  3006. Args:
  3007. clean_lines: A CleansedLines instance containing the file.
  3008. linenum: the number of the line to check.
  3009. column: end column of the token to check.
  3010. Returns:
  3011. True if this token is decltype() expression, False otherwise.
  3012. """
  3013. (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
  3014. if start_col < 0:
  3015. return False
  3016. if Search(r'\bdecltype\s*$', text[0:start_col]):
  3017. return True
  3018. return False
  3019. def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
  3020. """Checks for additional blank line issues related to sections.
  3021. Currently the only thing checked here is blank line before protected/private.
  3022. Args:
  3023. filename: The name of the current file.
  3024. clean_lines: A CleansedLines instance containing the file.
  3025. class_info: A _ClassInfo objects.
  3026. linenum: The number of the line to check.
  3027. error: The function to call with any errors found.
  3028. """
  3029. # Skip checks if the class is small, where small means 25 lines or less.
  3030. # 25 lines seems like a good cutoff since that's the usual height of
  3031. # terminals, and any class that can't fit in one screen can't really
  3032. # be considered "small".
  3033. #
  3034. # Also skip checks if we are on the first line. This accounts for
  3035. # classes that look like
  3036. # class Foo { public: ... };
  3037. #
  3038. # If we didn't find the end of the class, last_line would be zero,
  3039. # and the check will be skipped by the first condition.
  3040. if (class_info.last_line - class_info.starting_linenum <= 24 or
  3041. linenum <= class_info.starting_linenum):
  3042. return
  3043. matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
  3044. if matched:
  3045. # Issue warning if the line before public/protected/private was
  3046. # not a blank line, but don't do this if the previous line contains
  3047. # "class" or "struct". This can happen two ways:
  3048. # - We are at the beginning of the class.
  3049. # - We are forward-declaring an inner class that is semantically
  3050. # private, but needed to be public for implementation reasons.
  3051. # Also ignores cases where the previous line ends with a backslash as can be
  3052. # common when defining classes in C macros.
  3053. prev_line = clean_lines.lines[linenum - 1]
  3054. if (not IsBlankLine(prev_line) and
  3055. not Search(r'\b(class|struct)\b', prev_line) and
  3056. not Search(r'\\$', prev_line)):
  3057. # Try a bit harder to find the beginning of the class. This is to
  3058. # account for multi-line base-specifier lists, e.g.:
  3059. # class Derived
  3060. # : public Base {
  3061. end_class_head = class_info.starting_linenum
  3062. for i in range(class_info.starting_linenum, linenum):
  3063. if Search(r'\{\s*$', clean_lines.lines[i]):
  3064. end_class_head = i
  3065. break
  3066. if end_class_head < linenum - 1:
  3067. error(filename, linenum, 'whitespace/blank_line', 3,
  3068. '"%s:" should be preceded by a blank line' % matched.group(1))
  3069. def GetPreviousNonBlankLine(clean_lines, linenum):
  3070. """Return the most recent non-blank line and its line number.
  3071. Args:
  3072. clean_lines: A CleansedLines instance containing the file contents.
  3073. linenum: The number of the line to check.
  3074. Returns:
  3075. A tuple with two elements. The first element is the contents of the last
  3076. non-blank line before the current line, or the empty string if this is the
  3077. first non-blank line. The second is the line number of that line, or -1
  3078. if this is the first non-blank line.
  3079. """
  3080. prevlinenum = linenum - 1
  3081. while prevlinenum >= 0:
  3082. prevline = clean_lines.elided[prevlinenum]
  3083. if not IsBlankLine(prevline): # if not a blank line...
  3084. return (prevline, prevlinenum)
  3085. prevlinenum -= 1
  3086. return ('', -1)
  3087. def CheckBraces(filename, clean_lines, linenum, error):
  3088. """Looks for misplaced braces (e.g. at the end of line).
  3089. Args:
  3090. filename: The name of the current file.
  3091. clean_lines: A CleansedLines instance containing the file.
  3092. linenum: The number of the line to check.
  3093. error: The function to call with any errors found.
  3094. """
  3095. line = clean_lines.elided[linenum] # get rid of comments and strings
  3096. if Match(r'\s*{\s*$', line):
  3097. # We allow an open brace to start a line in the case where someone is using
  3098. # braces in a block to explicitly create a new scope, which is commonly used
  3099. # to control the lifetime of stack-allocated variables. Braces are also
  3100. # used for brace initializers inside function calls. We don't detect this
  3101. # perfectly: we just don't complain if the last non-whitespace character on
  3102. # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
  3103. # previous line starts a preprocessor block. We also allow a brace on the
  3104. # following line if it is part of an array initialization and would not fit
  3105. # within the 80 character limit of the preceding line.
  3106. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  3107. if (not Search(r'[,;:}{(]\s*$', prevline) and
  3108. not Match(r'\s*#', prevline) and
  3109. not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
  3110. error(filename, linenum, 'whitespace/braces', 4,
  3111. '{ should almost always be at the end of the previous line')
  3112. # An else clause should be on the same line as the preceding closing brace.
  3113. if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
  3114. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  3115. if Match(r'\s*}\s*$', prevline):
  3116. error(filename, linenum, 'whitespace/newline', 4,
  3117. 'An else should appear on the same line as the preceding }')
  3118. # If braces come on one side of an else, they should be on both.
  3119. # However, we have to worry about "else if" that spans multiple lines!
  3120. if Search(r'else if\s*\(', line): # could be multi-line if
  3121. brace_on_left = bool(Search(r'}\s*else if\s*\(', line))
  3122. # find the ( after the if
  3123. pos = line.find('else if')
  3124. pos = line.find('(', pos)
  3125. if pos > 0:
  3126. (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
  3127. brace_on_right = endline[endpos:].find('{') != -1
  3128. if brace_on_left != brace_on_right: # must be brace after if
  3129. error(filename, linenum, 'readability/braces', 5,
  3130. 'If an else has a brace on one side, it should have it on both')
  3131. elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
  3132. error(filename, linenum, 'readability/braces', 5,
  3133. 'If an else has a brace on one side, it should have it on both')
  3134. # Likewise, an else should never have the else clause on the same line
  3135. if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
  3136. error(filename, linenum, 'whitespace/newline', 4,
  3137. 'Else clause should never be on same line as else (use 2 lines)')
  3138. # In the same way, a do/while should never be on one line
  3139. if Match(r'\s*do [^\s{]', line):
  3140. error(filename, linenum, 'whitespace/newline', 4,
  3141. 'do/while clauses should not be on a single line')
  3142. # Check single-line if/else bodies. The style guide says 'curly braces are not
  3143. # required for single-line statements'. We additionally allow multi-line,
  3144. # single statements, but we reject anything with more than one semicolon in
  3145. # it. This means that the first semicolon after the if should be at the end of
  3146. # its line, and the line after that should have an indent level equal to or
  3147. # lower than the if. We also check for ambiguous if/else nesting without
  3148. # braces.
  3149. if_else_match = Search(r'\b(if\s*\(|else\b)', line)
  3150. if if_else_match and not Match(r'\s*#', line):
  3151. if_indent = GetIndentLevel(line)
  3152. endline, endlinenum, endpos = line, linenum, if_else_match.end()
  3153. if_match = Search(r'\bif\s*\(', line)
  3154. if if_match:
  3155. # This could be a multiline if condition, so find the end first.
  3156. pos = if_match.end() - 1
  3157. (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
  3158. # Check for an opening brace, either directly after the if or on the next
  3159. # line. If found, this isn't a single-statement conditional.
  3160. if (not Match(r'\s*{', endline[endpos:])
  3161. and not (Match(r'\s*$', endline[endpos:])
  3162. and endlinenum < (len(clean_lines.elided) - 1)
  3163. and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
  3164. while (endlinenum < len(clean_lines.elided)
  3165. and ';' not in clean_lines.elided[endlinenum][endpos:]):
  3166. endlinenum += 1
  3167. endpos = 0
  3168. if endlinenum < len(clean_lines.elided):
  3169. endline = clean_lines.elided[endlinenum]
  3170. # We allow a mix of whitespace and closing braces (e.g. for one-liner
  3171. # methods) and a single \ after the semicolon (for macros)
  3172. endpos = endline.find(';')
  3173. if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
  3174. # Semicolon isn't the last character, there's something trailing.
  3175. # Output a warning if the semicolon is not contained inside
  3176. # a lambda expression.
  3177. if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
  3178. endline):
  3179. error(filename, linenum, 'readability/braces', 4,
  3180. 'If/else bodies with multiple statements require braces')
  3181. elif endlinenum < len(clean_lines.elided) - 1:
  3182. # Make sure the next line is dedented
  3183. next_line = clean_lines.elided[endlinenum + 1]
  3184. next_indent = GetIndentLevel(next_line)
  3185. # With ambiguous nested if statements, this will error out on the
  3186. # if that *doesn't* match the else, regardless of whether it's the
  3187. # inner one or outer one.
  3188. if (if_match and Match(r'\s*else\b', next_line)
  3189. and next_indent != if_indent):
  3190. error(filename, linenum, 'readability/braces', 4,
  3191. 'Else clause should be indented at the same level as if. '
  3192. 'Ambiguous nested if/else chains require braces.')
  3193. elif next_indent > if_indent:
  3194. error(filename, linenum, 'readability/braces', 4,
  3195. 'If/else bodies with multiple statements require braces')
  3196. def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
  3197. """Looks for redundant trailing semicolon.
  3198. Args:
  3199. filename: The name of the current file.
  3200. clean_lines: A CleansedLines instance containing the file.
  3201. linenum: The number of the line to check.
  3202. error: The function to call with any errors found.
  3203. """
  3204. line = clean_lines.elided[linenum]
  3205. # Block bodies should not be followed by a semicolon. Due to C++11
  3206. # brace initialization, there are more places where semicolons are
  3207. # required than not, so we use a whitelist approach to check these
  3208. # rather than a blacklist. These are the places where "};" should
  3209. # be replaced by just "}":
  3210. # 1. Some flavor of block following closing parenthesis:
  3211. # for (;;) {};
  3212. # while (...) {};
  3213. # switch (...) {};
  3214. # Function(...) {};
  3215. # if (...) {};
  3216. # if (...) else if (...) {};
  3217. #
  3218. # 2. else block:
  3219. # if (...) else {};
  3220. #
  3221. # 3. const member function:
  3222. # Function(...) const {};
  3223. #
  3224. # 4. Block following some statement:
  3225. # x = 42;
  3226. # {};
  3227. #
  3228. # 5. Block at the beginning of a function:
  3229. # Function(...) {
  3230. # {};
  3231. # }
  3232. #
  3233. # Note that naively checking for the preceding "{" will also match
  3234. # braces inside multi-dimensional arrays, but this is fine since
  3235. # that expression will not contain semicolons.
  3236. #
  3237. # 6. Block following another block:
  3238. # while (true) {}
  3239. # {};
  3240. #
  3241. # 7. End of namespaces:
  3242. # namespace {};
  3243. #
  3244. # These semicolons seems far more common than other kinds of
  3245. # redundant semicolons, possibly due to people converting classes
  3246. # to namespaces. For now we do not warn for this case.
  3247. #
  3248. # Try matching case 1 first.
  3249. match = Match(r'^(.*\)\s*)\{', line)
  3250. if match:
  3251. # Matched closing parenthesis (case 1). Check the token before the
  3252. # matching opening parenthesis, and don't warn if it looks like a
  3253. # macro. This avoids these false positives:
  3254. # - macro that defines a base class
  3255. # - multi-line macro that defines a base class
  3256. # - macro that defines the whole class-head
  3257. #
  3258. # But we still issue warnings for macros that we know are safe to
  3259. # warn, specifically:
  3260. # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
  3261. # - TYPED_TEST
  3262. # - INTERFACE_DEF
  3263. # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
  3264. #
  3265. # We implement a whitelist of safe macros instead of a blacklist of
  3266. # unsafe macros, even though the latter appears less frequently in
  3267. # google code and would have been easier to implement. This is because
  3268. # the downside for getting the whitelist wrong means some extra
  3269. # semicolons, while the downside for getting the blacklist wrong
  3270. # would result in compile errors.
  3271. #
  3272. # In addition to macros, we also don't want to warn on
  3273. # - Compound literals
  3274. # - Lambdas
  3275. # - alignas specifier with anonymous structs
  3276. # - decltype
  3277. closing_brace_pos = match.group(1).rfind(')')
  3278. opening_parenthesis = ReverseCloseExpression(
  3279. clean_lines, linenum, closing_brace_pos)
  3280. if opening_parenthesis[2] > -1:
  3281. line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
  3282. macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
  3283. func = Match(r'^(.*\])\s*$', line_prefix)
  3284. if ((macro and
  3285. macro.group(1) not in (
  3286. 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
  3287. 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
  3288. 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
  3289. (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
  3290. Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
  3291. Search(r'\bdecltype$', line_prefix) or
  3292. Search(r'\s+=\s*$', line_prefix)):
  3293. match = None
  3294. if (match and
  3295. opening_parenthesis[1] > 1 and
  3296. Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
  3297. # Multi-line lambda-expression
  3298. match = None
  3299. else:
  3300. # Try matching cases 2-3.
  3301. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
  3302. if not match:
  3303. # Try matching cases 4-6. These are always matched on separate lines.
  3304. #
  3305. # Note that we can't simply concatenate the previous line to the
  3306. # current line and do a single match, otherwise we may output
  3307. # duplicate warnings for the blank line case:
  3308. # if (cond) {
  3309. # // blank line
  3310. # }
  3311. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  3312. if prevline and Search(r'[;{}]\s*$', prevline):
  3313. match = Match(r'^(\s*)\{', line)
  3314. # Check matching closing brace
  3315. if match:
  3316. (endline, endlinenum, endpos) = CloseExpression(
  3317. clean_lines, linenum, len(match.group(1)))
  3318. if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
  3319. # Current {} pair is eligible for semicolon check, and we have found
  3320. # the redundant semicolon, output warning here.
  3321. #
  3322. # Note: because we are scanning forward for opening braces, and
  3323. # outputting warnings for the matching closing brace, if there are
  3324. # nested blocks with trailing semicolons, we will get the error
  3325. # messages in reversed order.
  3326. # We need to check the line forward for NOLINT
  3327. raw_lines = clean_lines.raw_lines
  3328. ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,
  3329. error)
  3330. ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum,
  3331. error)
  3332. error(filename, endlinenum, 'readability/braces', 4,
  3333. "You don't need a ; after a }")
  3334. def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
  3335. """Look for empty loop/conditional body with only a single semicolon.
  3336. Args:
  3337. filename: The name of the current file.
  3338. clean_lines: A CleansedLines instance containing the file.
  3339. linenum: The number of the line to check.
  3340. error: The function to call with any errors found.
  3341. """
  3342. # Search for loop keywords at the beginning of the line. Because only
  3343. # whitespaces are allowed before the keywords, this will also ignore most
  3344. # do-while-loops, since those lines should start with closing brace.
  3345. #
  3346. # We also check "if" blocks here, since an empty conditional block
  3347. # is likely an error.
  3348. line = clean_lines.elided[linenum]
  3349. matched = Match(r'\s*(for|while|if)\s*\(', line)
  3350. if matched:
  3351. # Find the end of the conditional expression.
  3352. (end_line, end_linenum, end_pos) = CloseExpression(
  3353. clean_lines, linenum, line.find('('))
  3354. # Output warning if what follows the condition expression is a semicolon.
  3355. # No warning for all other cases, including whitespace or newline, since we
  3356. # have a separate check for semicolons preceded by whitespace.
  3357. if end_pos >= 0 and Match(r';', end_line[end_pos:]):
  3358. if matched.group(1) == 'if':
  3359. error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
  3360. 'Empty conditional bodies should use {}')
  3361. else:
  3362. error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
  3363. 'Empty loop bodies should use {} or continue')
  3364. # Check for if statements that have completely empty bodies (no comments)
  3365. # and no else clauses.
  3366. if end_pos >= 0 and matched.group(1) == 'if':
  3367. # Find the position of the opening { for the if statement.
  3368. # Return without logging an error if it has no brackets.
  3369. opening_linenum = end_linenum
  3370. opening_line_fragment = end_line[end_pos:]
  3371. # Loop until EOF or find anything that's not whitespace or opening {.
  3372. while not Search(r'^\s*\{', opening_line_fragment):
  3373. if Search(r'^(?!\s*$)', opening_line_fragment):
  3374. # Conditional has no brackets.
  3375. return
  3376. opening_linenum += 1
  3377. if opening_linenum == len(clean_lines.elided):
  3378. # Couldn't find conditional's opening { or any code before EOF.
  3379. return
  3380. opening_line_fragment = clean_lines.elided[opening_linenum]
  3381. # Set opening_line (opening_line_fragment may not be entire opening line).
  3382. opening_line = clean_lines.elided[opening_linenum]
  3383. # Find the position of the closing }.
  3384. opening_pos = opening_line_fragment.find('{')
  3385. if opening_linenum == end_linenum:
  3386. # We need to make opening_pos relative to the start of the entire line.
  3387. opening_pos += end_pos
  3388. (closing_line, closing_linenum, closing_pos) = CloseExpression(
  3389. clean_lines, opening_linenum, opening_pos)
  3390. if closing_pos < 0:
  3391. return
  3392. # Now construct the body of the conditional. This consists of the portion
  3393. # of the opening line after the {, all lines until the closing line,
  3394. # and the portion of the closing line before the }.
  3395. if (clean_lines.raw_lines[opening_linenum] !=
  3396. CleanseComments(clean_lines.raw_lines[opening_linenum])):
  3397. # Opening line ends with a comment, so conditional isn't empty.
  3398. return
  3399. if closing_linenum > opening_linenum:
  3400. # Opening line after the {. Ignore comments here since we checked above.
  3401. body = list(opening_line[opening_pos+1:])
  3402. # All lines until closing line, excluding closing line, with comments.
  3403. body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
  3404. # Closing line before the }. Won't (and can't) have comments.
  3405. body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
  3406. body = '\n'.join(body)
  3407. else:
  3408. # If statement has brackets and fits on a single line.
  3409. body = opening_line[opening_pos+1:closing_pos-1]
  3410. # Check if the body is empty
  3411. if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
  3412. return
  3413. # The body is empty. Now make sure there's not an else clause.
  3414. current_linenum = closing_linenum
  3415. current_line_fragment = closing_line[closing_pos:]
  3416. # Loop until EOF or find anything that's not whitespace or else clause.
  3417. while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
  3418. if Search(r'^(?=\s*else)', current_line_fragment):
  3419. # Found an else clause, so don't log an error.
  3420. return
  3421. current_linenum += 1
  3422. if current_linenum == len(clean_lines.elided):
  3423. break
  3424. current_line_fragment = clean_lines.elided[current_linenum]
  3425. # The body is empty and there's no else clause until EOF or other code.
  3426. error(filename, end_linenum, 'whitespace/empty_if_body', 4,
  3427. ('If statement had no body and no else clause'))
  3428. def FindCheckMacro(line):
  3429. """Find a replaceable CHECK-like macro.
  3430. Args:
  3431. line: line to search on.
  3432. Returns:
  3433. (macro name, start position), or (None, -1) if no replaceable
  3434. macro is found.
  3435. """
  3436. for macro in _CHECK_MACROS:
  3437. i = line.find(macro)
  3438. if i >= 0:
  3439. # Find opening parenthesis. Do a regular expression match here
  3440. # to make sure that we are matching the expected CHECK macro, as
  3441. # opposed to some other macro that happens to contain the CHECK
  3442. # substring.
  3443. matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
  3444. if not matched:
  3445. continue
  3446. return (macro, len(matched.group(1)))
  3447. return (None, -1)
  3448. def CheckCheck(filename, clean_lines, linenum, error):
  3449. """Checks the use of CHECK and EXPECT macros.
  3450. Args:
  3451. filename: The name of the current file.
  3452. clean_lines: A CleansedLines instance containing the file.
  3453. linenum: The number of the line to check.
  3454. error: The function to call with any errors found.
  3455. """
  3456. # Decide the set of replacement macros that should be suggested
  3457. lines = clean_lines.elided
  3458. (check_macro, start_pos) = FindCheckMacro(lines[linenum])
  3459. if not check_macro:
  3460. return
  3461. # Find end of the boolean expression by matching parentheses
  3462. (last_line, end_line, end_pos) = CloseExpression(
  3463. clean_lines, linenum, start_pos)
  3464. if end_pos < 0:
  3465. return
  3466. # If the check macro is followed by something other than a
  3467. # semicolon, assume users will log their own custom error messages
  3468. # and don't suggest any replacements.
  3469. if not Match(r'\s*;', last_line[end_pos:]):
  3470. return
  3471. if linenum == end_line:
  3472. expression = lines[linenum][start_pos + 1:end_pos - 1]
  3473. else:
  3474. expression = lines[linenum][start_pos + 1:]
  3475. for i in xrange(linenum + 1, end_line):
  3476. expression += lines[i]
  3477. expression += last_line[0:end_pos - 1]
  3478. # Parse expression so that we can take parentheses into account.
  3479. # This avoids false positives for inputs like "CHECK((a < 4) == b)",
  3480. # which is not replaceable by CHECK_LE.
  3481. lhs = ''
  3482. rhs = ''
  3483. operator = None
  3484. while expression:
  3485. matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
  3486. r'==|!=|>=|>|<=|<|\()(.*)$', expression)
  3487. if matched:
  3488. token = matched.group(1)
  3489. if token == '(':
  3490. # Parenthesized operand
  3491. expression = matched.group(2)
  3492. (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
  3493. if end < 0:
  3494. return # Unmatched parenthesis
  3495. lhs += '(' + expression[0:end]
  3496. expression = expression[end:]
  3497. elif token in ('&&', '||'):
  3498. # Logical and/or operators. This means the expression
  3499. # contains more than one term, for example:
  3500. # CHECK(42 < a && a < b);
  3501. #
  3502. # These are not replaceable with CHECK_LE, so bail out early.
  3503. return
  3504. elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
  3505. # Non-relational operator
  3506. lhs += token
  3507. expression = matched.group(2)
  3508. else:
  3509. # Relational operator
  3510. operator = token
  3511. rhs = matched.group(2)
  3512. break
  3513. else:
  3514. # Unparenthesized operand. Instead of appending to lhs one character
  3515. # at a time, we do another regular expression match to consume several
  3516. # characters at once if possible. Trivial benchmark shows that this
  3517. # is more efficient when the operands are longer than a single
  3518. # character, which is generally the case.
  3519. matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
  3520. if not matched:
  3521. matched = Match(r'^(\s*\S)(.*)$', expression)
  3522. if not matched:
  3523. break
  3524. lhs += matched.group(1)
  3525. expression = matched.group(2)
  3526. # Only apply checks if we got all parts of the boolean expression
  3527. if not (lhs and operator and rhs):
  3528. return
  3529. # Check that rhs do not contain logical operators. We already know
  3530. # that lhs is fine since the loop above parses out && and ||.
  3531. if rhs.find('&&') > -1 or rhs.find('||') > -1:
  3532. return
  3533. # At least one of the operands must be a constant literal. This is
  3534. # to avoid suggesting replacements for unprintable things like
  3535. # CHECK(variable != iterator)
  3536. #
  3537. # The following pattern matches decimal, hex integers, strings, and
  3538. # characters (in that order).
  3539. lhs = lhs.strip()
  3540. rhs = rhs.strip()
  3541. match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
  3542. if Match(match_constant, lhs) or Match(match_constant, rhs):
  3543. # Note: since we know both lhs and rhs, we can provide a more
  3544. # descriptive error message like:
  3545. # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
  3546. # Instead of:
  3547. # Consider using CHECK_EQ instead of CHECK(a == b)
  3548. #
  3549. # We are still keeping the less descriptive message because if lhs
  3550. # or rhs gets long, the error message might become unreadable.
  3551. error(filename, linenum, 'readability/check', 2,
  3552. 'Consider using %s instead of %s(a %s b)' % (
  3553. _CHECK_REPLACEMENT[check_macro][operator],
  3554. check_macro, operator))
  3555. def CheckAltTokens(filename, clean_lines, linenum, error):
  3556. """Check alternative keywords being used in boolean expressions.
  3557. Args:
  3558. filename: The name of the current file.
  3559. clean_lines: A CleansedLines instance containing the file.
  3560. linenum: The number of the line to check.
  3561. error: The function to call with any errors found.
  3562. """
  3563. line = clean_lines.elided[linenum]
  3564. # Avoid preprocessor lines
  3565. if Match(r'^\s*#', line):
  3566. return
  3567. # Last ditch effort to avoid multi-line comments. This will not help
  3568. # if the comment started before the current line or ended after the
  3569. # current line, but it catches most of the false positives. At least,
  3570. # it provides a way to workaround this warning for people who use
  3571. # multi-line comments in preprocessor macros.
  3572. #
  3573. # TODO(unknown): remove this once cpplint has better support for
  3574. # multi-line comments.
  3575. if line.find('/*') >= 0 or line.find('*/') >= 0:
  3576. return
  3577. for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
  3578. error(filename, linenum, 'readability/alt_tokens', 2,
  3579. 'Use operator %s instead of %s' % (
  3580. _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
  3581. def GetLineWidth(line):
  3582. """Determines the width of the line in column positions.
  3583. Args:
  3584. line: A string, which may be a Unicode string.
  3585. Returns:
  3586. The width of the line in column positions, accounting for Unicode
  3587. combining characters and wide characters.
  3588. """
  3589. if isinstance(line, unicode):
  3590. width = 0
  3591. for uc in unicodedata.normalize('NFC', line):
  3592. if unicodedata.east_asian_width(uc) in ('W', 'F'):
  3593. width += 2
  3594. elif not unicodedata.combining(uc):
  3595. width += 1
  3596. return width
  3597. else:
  3598. return len(line)
  3599. def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
  3600. error):
  3601. """Checks rules from the 'C++ style rules' section of cppguide.html.
  3602. Most of these rules are hard to test (naming, comment style), but we
  3603. do what we can. In particular we check for 2-space indents, line lengths,
  3604. tab usage, spaces inside code, etc.
  3605. Args:
  3606. filename: The name of the current file.
  3607. clean_lines: A CleansedLines instance containing the file.
  3608. linenum: The number of the line to check.
  3609. file_extension: The extension (without the dot) of the filename.
  3610. nesting_state: A NestingState instance which maintains information about
  3611. the current stack of nested blocks being parsed.
  3612. error: The function to call with any errors found.
  3613. """
  3614. # Don't use "elided" lines here, otherwise we can't check commented lines.
  3615. # Don't want to use "raw" either, because we don't want to check inside C++11
  3616. # raw strings,
  3617. raw_lines = clean_lines.lines_without_raw_strings
  3618. line = raw_lines[linenum]
  3619. prev = raw_lines[linenum - 1] if linenum > 0 else ''
  3620. if line.find('\t') != -1:
  3621. error(filename, linenum, 'whitespace/tab', 1,
  3622. 'Tab found; better to use spaces')
  3623. # One or three blank spaces at the beginning of the line is weird; it's
  3624. # hard to reconcile that with 2-space indents.
  3625. # NOTE: here are the conditions rob pike used for his tests. Mine aren't
  3626. # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
  3627. # if(RLENGTH > 20) complain = 0;
  3628. # if(match($0, " +(error|private|public|protected):")) complain = 0;
  3629. # if(match(prev, "&& *$")) complain = 0;
  3630. # if(match(prev, "\\|\\| *$")) complain = 0;
  3631. # if(match(prev, "[\",=><] *$")) complain = 0;
  3632. # if(match($0, " <<")) complain = 0;
  3633. # if(match(prev, " +for \\(")) complain = 0;
  3634. # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
  3635. scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
  3636. classinfo = nesting_state.InnermostClass()
  3637. initial_spaces = 0
  3638. cleansed_line = clean_lines.elided[linenum]
  3639. while initial_spaces < len(line) and line[initial_spaces] == ' ':
  3640. initial_spaces += 1
  3641. # There are certain situations we allow one space, notably for
  3642. # section labels, and also lines containing multi-line raw strings.
  3643. # We also don't check for lines that look like continuation lines
  3644. # (of lines ending in double quotes, commas, equals, or angle brackets)
  3645. # because the rules for how to indent those are non-trivial.
  3646. if (not Search(r'[",=><] *$', prev) and
  3647. (initial_spaces == 1 or initial_spaces == 3) and
  3648. not Match(scope_or_label_pattern, cleansed_line) and
  3649. not (clean_lines.raw_lines[linenum] != line and
  3650. Match(r'^\s*""', line))):
  3651. error(filename, linenum, 'whitespace/indent', 3,
  3652. 'Weird number of spaces at line-start. '
  3653. 'Are you using a 2-space indent?')
  3654. if line and line[-1].isspace():
  3655. error(filename, linenum, 'whitespace/end_of_line', 4,
  3656. 'Line ends in whitespace. Consider deleting these extra spaces.')
  3657. # Check if the line is a header guard.
  3658. is_header_guard = False
  3659. if IsHeaderExtension(file_extension):
  3660. cppvar = GetHeaderGuardCPPVariable(filename)
  3661. if (line.startswith('#ifndef %s' % cppvar) or
  3662. line.startswith('#define %s' % cppvar) or
  3663. line.startswith('#endif // %s' % cppvar)):
  3664. is_header_guard = True
  3665. # #include lines and header guards can be long, since there's no clean way to
  3666. # split them.
  3667. #
  3668. # URLs can be long too. It's possible to split these, but it makes them
  3669. # harder to cut&paste.
  3670. #
  3671. # The "$Id:...$" comment may also get very long without it being the
  3672. # developers fault.
  3673. if (not line.startswith('#include') and not is_header_guard and
  3674. not Match(r'^\s*//.*http(s?)://\S*$', line) and
  3675. not Match(r'^\s*//\s*[^\s]*$', line) and
  3676. not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
  3677. line_width = GetLineWidth(line)
  3678. if line_width > _line_length:
  3679. error(filename, linenum, 'whitespace/line_length', 2,
  3680. 'Lines should be <= %i characters long' % _line_length)
  3681. if (cleansed_line.count(';') > 1 and
  3682. # for loops are allowed two ;'s (and may run over two lines).
  3683. cleansed_line.find('for') == -1 and
  3684. (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
  3685. GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
  3686. # It's ok to have many commands in a switch case that fits in 1 line
  3687. not ((cleansed_line.find('case ') != -1 or
  3688. cleansed_line.find('default:') != -1) and
  3689. cleansed_line.find('break;') != -1)):
  3690. error(filename, linenum, 'whitespace/newline', 0,
  3691. 'More than one command on the same line')
  3692. # Some more style checks
  3693. CheckBraces(filename, clean_lines, linenum, error)
  3694. CheckTrailingSemicolon(filename, clean_lines, linenum, error)
  3695. CheckEmptyBlockBody(filename, clean_lines, linenum, error)
  3696. CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
  3697. CheckOperatorSpacing(filename, clean_lines, linenum, error)
  3698. CheckParenthesisSpacing(filename, clean_lines, linenum, error)
  3699. CheckCommaSpacing(filename, clean_lines, linenum, error)
  3700. CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
  3701. CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
  3702. CheckCheck(filename, clean_lines, linenum, error)
  3703. CheckAltTokens(filename, clean_lines, linenum, error)
  3704. classinfo = nesting_state.InnermostClass()
  3705. if classinfo:
  3706. CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
  3707. _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
  3708. # Matches the first component of a filename delimited by -s and _s. That is:
  3709. # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
  3710. # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
  3711. # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
  3712. # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
  3713. _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
  3714. def _DropCommonSuffixes(filename):
  3715. """Drops common suffixes like _test.cc or -inl.h from filename.
  3716. For example:
  3717. >>> _DropCommonSuffixes('foo/foo-inl.h')
  3718. 'foo/foo'
  3719. >>> _DropCommonSuffixes('foo/bar/foo.cc')
  3720. 'foo/bar/foo'
  3721. >>> _DropCommonSuffixes('foo/foo_internal.h')
  3722. 'foo/foo'
  3723. >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
  3724. 'foo/foo_unusualinternal'
  3725. Args:
  3726. filename: The input filename.
  3727. Returns:
  3728. The filename with the common suffix removed.
  3729. """
  3730. for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
  3731. 'inl.h', 'impl.h', 'internal.h'):
  3732. if (filename.endswith(suffix) and len(filename) > len(suffix) and
  3733. filename[-len(suffix) - 1] in ('-', '_')):
  3734. return filename[:-len(suffix) - 1]
  3735. return os.path.splitext(filename)[0]
  3736. def _ClassifyInclude(fileinfo, include, is_system):
  3737. """Figures out what kind of header 'include' is.
  3738. Args:
  3739. fileinfo: The current file cpplint is running over. A FileInfo instance.
  3740. include: The path to a #included file.
  3741. is_system: True if the #include used <> rather than "".
  3742. Returns:
  3743. One of the _XXX_HEADER constants.
  3744. For example:
  3745. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
  3746. _C_SYS_HEADER
  3747. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
  3748. _CPP_SYS_HEADER
  3749. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
  3750. _LIKELY_MY_HEADER
  3751. >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
  3752. ... 'bar/foo_other_ext.h', False)
  3753. _POSSIBLE_MY_HEADER
  3754. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
  3755. _OTHER_HEADER
  3756. """
  3757. # This is a list of all standard c++ header files, except
  3758. # those already checked for above.
  3759. is_cpp_h = include in _CPP_HEADERS
  3760. if is_system:
  3761. if is_cpp_h:
  3762. return _CPP_SYS_HEADER
  3763. else:
  3764. return _C_SYS_HEADER
  3765. # If the target file and the include we're checking share a
  3766. # basename when we drop common extensions, and the include
  3767. # lives in . , then it's likely to be owned by the target file.
  3768. target_dir, target_base = (
  3769. os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
  3770. include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
  3771. if target_base == include_base and (
  3772. include_dir == target_dir or
  3773. include_dir == os.path.normpath(target_dir + '/../public')):
  3774. return _LIKELY_MY_HEADER
  3775. # If the target and include share some initial basename
  3776. # component, it's possible the target is implementing the
  3777. # include, so it's allowed to be first, but we'll never
  3778. # complain if it's not there.
  3779. target_first_component = _RE_FIRST_COMPONENT.match(target_base)
  3780. include_first_component = _RE_FIRST_COMPONENT.match(include_base)
  3781. if (target_first_component and include_first_component and
  3782. target_first_component.group(0) ==
  3783. include_first_component.group(0)):
  3784. return _POSSIBLE_MY_HEADER
  3785. return _OTHER_HEADER
  3786. def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
  3787. """Check rules that are applicable to #include lines.
  3788. Strings on #include lines are NOT removed from elided line, to make
  3789. certain tasks easier. However, to prevent false positives, checks
  3790. applicable to #include lines in CheckLanguage must be put here.
  3791. Args:
  3792. filename: The name of the current file.
  3793. clean_lines: A CleansedLines instance containing the file.
  3794. linenum: The number of the line to check.
  3795. include_state: An _IncludeState instance in which the headers are inserted.
  3796. error: The function to call with any errors found.
  3797. """
  3798. fileinfo = FileInfo(filename)
  3799. line = clean_lines.lines[linenum]
  3800. # "include" should use the new style "foo/bar.h" instead of just "bar.h"
  3801. # Only do this check if the included header follows google naming
  3802. # conventions. If not, assume that it's a 3rd party API that
  3803. # requires special include conventions.
  3804. #
  3805. # We also make an exception for Lua headers, which follow google
  3806. # naming convention but not the include convention.
  3807. match = Match(r'#include\s*"([^/]+\.h)"', line)
  3808. if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
  3809. error(filename, linenum, 'build/include', 4,
  3810. 'Include the directory when naming .h files')
  3811. # we shouldn't include a file more than once. actually, there are a
  3812. # handful of instances where doing so is okay, but in general it's
  3813. # not.
  3814. match = _RE_PATTERN_INCLUDE.search(line)
  3815. if match:
  3816. include = match.group(2)
  3817. is_system = (match.group(1) == '<')
  3818. duplicate_line = include_state.FindHeader(include)
  3819. if duplicate_line >= 0:
  3820. error(filename, linenum, 'build/include', 4,
  3821. '"%s" already included at %s:%s' %
  3822. (include, filename, duplicate_line))
  3823. elif (include.endswith('.cc') and
  3824. os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
  3825. error(filename, linenum, 'build/include', 4,
  3826. 'Do not include .cc files from other packages')
  3827. elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
  3828. include_state.include_list[-1].append((include, linenum))
  3829. # We want to ensure that headers appear in the right order:
  3830. # 1) for foo.cc, foo.h (preferred location)
  3831. # 2) c system files
  3832. # 3) cpp system files
  3833. # 4) for foo.cc, foo.h (deprecated location)
  3834. # 5) other google headers
  3835. #
  3836. # We classify each include statement as one of those 5 types
  3837. # using a number of techniques. The include_state object keeps
  3838. # track of the highest type seen, and complains if we see a
  3839. # lower type after that.
  3840. error_message = include_state.CheckNextIncludeOrder(
  3841. _ClassifyInclude(fileinfo, include, is_system))
  3842. if error_message:
  3843. error(filename, linenum, 'build/include_order', 4,
  3844. '%s. Should be: %s.h, c system, c++ system, other.' %
  3845. (error_message, fileinfo.BaseName()))
  3846. canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
  3847. if not include_state.IsInAlphabeticalOrder(
  3848. clean_lines, linenum, canonical_include):
  3849. error(filename, linenum, 'build/include_alpha', 4,
  3850. 'Include "%s" not in alphabetical order' % include)
  3851. include_state.SetLastHeader(canonical_include)
  3852. def _GetTextInside(text, start_pattern):
  3853. r"""Retrieves all the text between matching open and close parentheses.
  3854. Given a string of lines and a regular expression string, retrieve all the text
  3855. following the expression and between opening punctuation symbols like
  3856. (, [, or {, and the matching close-punctuation symbol. This properly nested
  3857. occurrences of the punctuations, so for the text like
  3858. printf(a(), b(c()));
  3859. a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
  3860. start_pattern must match string having an open punctuation symbol at the end.
  3861. Args:
  3862. text: The lines to extract text. Its comments and strings must be elided.
  3863. It can be single line and can span multiple lines.
  3864. start_pattern: The regexp string indicating where to start extracting
  3865. the text.
  3866. Returns:
  3867. The extracted text.
  3868. None if either the opening string or ending punctuation could not be found.
  3869. """
  3870. # TODO(unknown): Audit cpplint.py to see what places could be profitably
  3871. # rewritten to use _GetTextInside (and use inferior regexp matching today).
  3872. # Give opening punctuations to get the matching close-punctuations.
  3873. matching_punctuation = {'(': ')', '{': '}', '[': ']'}
  3874. closing_punctuation = set(matching_punctuation.itervalues())
  3875. # Find the position to start extracting text.
  3876. match = re.search(start_pattern, text, re.M)
  3877. if not match: # start_pattern not found in text.
  3878. return None
  3879. start_position = match.end(0)
  3880. assert start_position > 0, (
  3881. 'start_pattern must ends with an opening punctuation.')
  3882. assert text[start_position - 1] in matching_punctuation, (
  3883. 'start_pattern must ends with an opening punctuation.')
  3884. # Stack of closing punctuations we expect to have in text after position.
  3885. punctuation_stack = [matching_punctuation[text[start_position - 1]]]
  3886. position = start_position
  3887. while punctuation_stack and position < len(text):
  3888. if text[position] == punctuation_stack[-1]:
  3889. punctuation_stack.pop()
  3890. elif text[position] in closing_punctuation:
  3891. # A closing punctuation without matching opening punctuations.
  3892. return None
  3893. elif text[position] in matching_punctuation:
  3894. punctuation_stack.append(matching_punctuation[text[position]])
  3895. position += 1
  3896. if punctuation_stack:
  3897. # Opening punctuations left without matching close-punctuations.
  3898. return None
  3899. # punctuations match.
  3900. return text[start_position:position - 1]
  3901. # Patterns for matching call-by-reference parameters.
  3902. #
  3903. # Supports nested templates up to 2 levels deep using this messy pattern:
  3904. # < (?: < (?: < [^<>]*
  3905. # >
  3906. # | [^<>] )*
  3907. # >
  3908. # | [^<>] )*
  3909. # >
  3910. _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
  3911. _RE_PATTERN_TYPE = (
  3912. r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
  3913. r'(?:\w|'
  3914. r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
  3915. r'::)+')
  3916. # A call-by-reference parameter ends with '& identifier'.
  3917. _RE_PATTERN_REF_PARAM = re.compile(
  3918. r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
  3919. r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
  3920. # A call-by-const-reference parameter either ends with 'const& identifier'
  3921. # or looks like 'const type& identifier' when 'type' is atomic.
  3922. _RE_PATTERN_CONST_REF_PARAM = (
  3923. r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
  3924. r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
  3925. # Stream types.
  3926. _RE_PATTERN_REF_STREAM_PARAM = (
  3927. r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')
  3928. def CheckLanguage(filename, clean_lines, linenum, file_extension,
  3929. include_state, nesting_state, error):
  3930. """Checks rules from the 'C++ language rules' section of cppguide.html.
  3931. Some of these rules are hard to test (function overloading, using
  3932. uint32 inappropriately), but we do the best we can.
  3933. Args:
  3934. filename: The name of the current file.
  3935. clean_lines: A CleansedLines instance containing the file.
  3936. linenum: The number of the line to check.
  3937. file_extension: The extension (without the dot) of the filename.
  3938. include_state: An _IncludeState instance in which the headers are inserted.
  3939. nesting_state: A NestingState instance which maintains information about
  3940. the current stack of nested blocks being parsed.
  3941. error: The function to call with any errors found.
  3942. """
  3943. # If the line is empty or consists of entirely a comment, no need to
  3944. # check it.
  3945. line = clean_lines.elided[linenum]
  3946. if not line:
  3947. return
  3948. match = _RE_PATTERN_INCLUDE.search(line)
  3949. if match:
  3950. CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
  3951. return
  3952. # Reset include state across preprocessor directives. This is meant
  3953. # to silence warnings for conditional includes.
  3954. match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
  3955. if match:
  3956. include_state.ResetSection(match.group(1))
  3957. # Make Windows paths like Unix.
  3958. fullname = os.path.abspath(filename).replace('\\', '/')
  3959. # Perform other checks now that we are sure that this is not an include line
  3960. CheckCasts(filename, clean_lines, linenum, error)
  3961. CheckGlobalStatic(filename, clean_lines, linenum, error)
  3962. CheckPrintf(filename, clean_lines, linenum, error)
  3963. if IsHeaderExtension(file_extension):
  3964. # TODO(unknown): check that 1-arg constructors are explicit.
  3965. # How to tell it's a constructor?
  3966. # (handled in CheckForNonStandardConstructs for now)
  3967. # TODO(unknown): check that classes declare or disable copy/assign
  3968. # (level 1 error)
  3969. pass
  3970. # Check if people are using the verboten C basic types. The only exception
  3971. # we regularly allow is "unsigned short port" for port.
  3972. if Search(r'\bshort port\b', line):
  3973. if not Search(r'\bunsigned short port\b', line):
  3974. error(filename, linenum, 'runtime/int', 4,
  3975. 'Use "unsigned short" for ports, not "short"')
  3976. else:
  3977. match = Search(r'\b(short|long(?! +double)|long long)\b', line)
  3978. if match:
  3979. error(filename, linenum, 'runtime/int', 4,
  3980. 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
  3981. # Check if some verboten operator overloading is going on
  3982. # TODO(unknown): catch out-of-line unary operator&:
  3983. # class X {};
  3984. # int operator&(const X& x) { return 42; } // unary operator&
  3985. # The trick is it's hard to tell apart from binary operator&:
  3986. # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
  3987. if Search(r'\boperator\s*&\s*\(\s*\)', line):
  3988. error(filename, linenum, 'runtime/operator', 4,
  3989. 'Unary operator& is dangerous. Do not use it.')
  3990. # Check for suspicious usage of "if" like
  3991. # } if (a == b) {
  3992. if Search(r'\}\s*if\s*\(', line):
  3993. error(filename, linenum, 'readability/braces', 4,
  3994. 'Did you mean "else if"? If not, start a new line for "if".')
  3995. # Check for potential format string bugs like printf(foo).
  3996. # We constrain the pattern not to pick things like DocidForPrintf(foo).
  3997. # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
  3998. # TODO(unknown): Catch the following case. Need to change the calling
  3999. # convention of the whole function to process multiple line to handle it.
  4000. # printf(
  4001. # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
  4002. printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
  4003. if printf_args:
  4004. match = Match(r'([\w.\->()]+)$', printf_args)
  4005. if match and match.group(1) != '__VA_ARGS__':
  4006. function_name = re.search(r'\b((?:string)?printf)\s*\(',
  4007. line, re.I).group(1)
  4008. error(filename, linenum, 'runtime/printf', 4,
  4009. 'Potential format string bug. Do %s("%%s", %s) instead.'
  4010. % (function_name, match.group(1)))
  4011. # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
  4012. match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
  4013. if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
  4014. error(filename, linenum, 'runtime/memset', 4,
  4015. 'Did you mean "memset(%s, 0, %s)"?'
  4016. % (match.group(1), match.group(2)))
  4017. if Search(r'\busing namespace\b', line):
  4018. error(filename, linenum, 'build/namespaces', 5,
  4019. 'Do not use namespace using-directives. '
  4020. 'Use using-declarations instead.')
  4021. # Detect variable-length arrays.
  4022. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
  4023. if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
  4024. match.group(3).find(']') == -1):
  4025. # Split the size using space and arithmetic operators as delimiters.
  4026. # If any of the resulting tokens are not compile time constants then
  4027. # report the error.
  4028. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
  4029. is_const = True
  4030. skip_next = False
  4031. for tok in tokens:
  4032. if skip_next:
  4033. skip_next = False
  4034. continue
  4035. if Search(r'sizeof\(.+\)', tok): continue
  4036. if Search(r'arraysize\(\w+\)', tok): continue
  4037. tok = tok.lstrip('(')
  4038. tok = tok.rstrip(')')
  4039. if not tok: continue
  4040. if Match(r'\d+', tok): continue
  4041. if Match(r'0[xX][0-9a-fA-F]+', tok): continue
  4042. if Match(r'k[A-Z0-9]\w*', tok): continue
  4043. if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
  4044. if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
  4045. # A catch all for tricky sizeof cases, including 'sizeof expression',
  4046. # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
  4047. # requires skipping the next token because we split on ' ' and '*'.
  4048. if tok.startswith('sizeof'):
  4049. skip_next = True
  4050. continue
  4051. is_const = False
  4052. break
  4053. if not is_const:
  4054. error(filename, linenum, 'runtime/arrays', 1,
  4055. 'Do not use variable-length arrays. Use an appropriately named '
  4056. "('k' followed by CamelCase) compile-time constant for the size.")
  4057. # Check for use of unnamed namespaces in header files. Registration
  4058. # macros are typically OK, so we allow use of "namespace {" on lines
  4059. # that end with backslashes.
  4060. if (IsHeaderExtension(file_extension)
  4061. and Search(r'\bnamespace\s*{', line)
  4062. and line[-1] != '\\'):
  4063. error(filename, linenum, 'build/namespaces', 4,
  4064. 'Do not use unnamed namespaces in header files. See '
  4065. 'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
  4066. ' for more information.')
  4067. def CheckGlobalStatic(filename, clean_lines, linenum, error):
  4068. """Check for unsafe global or static objects.
  4069. Args:
  4070. filename: The name of the current file.
  4071. clean_lines: A CleansedLines instance containing the file.
  4072. linenum: The number of the line to check.
  4073. error: The function to call with any errors found.
  4074. """
  4075. line = clean_lines.elided[linenum]
  4076. # Match two lines at a time to support multiline declarations
  4077. if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
  4078. line += clean_lines.elided[linenum + 1].strip()
  4079. # Check for people declaring static/global STL strings at the top level.
  4080. # This is dangerous because the C++ language does not guarantee that
  4081. # globals with constructors are initialized before the first access, and
  4082. # also because globals can be destroyed when some threads are still running.
  4083. # TODO(unknown): Generalize this to also find static unique_ptr instances.
  4084. # TODO(unknown): File bugs for clang-tidy to find these.
  4085. match = Match(
  4086. r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'
  4087. r'([a-zA-Z0-9_:]+)\b(.*)',
  4088. line)
  4089. # Remove false positives:
  4090. # - String pointers (as opposed to values).
  4091. # string *pointer
  4092. # const string *pointer
  4093. # string const *pointer
  4094. # string *const pointer
  4095. #
  4096. # - Functions and template specializations.
  4097. # string Function<Type>(...
  4098. # string Class<Type>::Method(...
  4099. #
  4100. # - Operators. These are matched separately because operator names
  4101. # cross non-word boundaries, and trying to match both operators
  4102. # and functions at the same time would decrease accuracy of
  4103. # matching identifiers.
  4104. # string Class::operator*()
  4105. if (match and
  4106. not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and
  4107. not Search(r'\boperator\W', line) and
  4108. not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
  4109. if Search(r'\bconst\b', line):
  4110. error(filename, linenum, 'runtime/string', 4,
  4111. 'For a static/global string constant, use a C style string '
  4112. 'instead: "%schar%s %s[]".' %
  4113. (match.group(1), match.group(2) or '', match.group(3)))
  4114. else:
  4115. error(filename, linenum, 'runtime/string', 4,
  4116. 'Static/global string variables are not permitted.')
  4117. if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
  4118. Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
  4119. error(filename, linenum, 'runtime/init', 4,
  4120. 'You seem to be initializing a member variable with itself.')
  4121. def CheckPrintf(filename, clean_lines, linenum, error):
  4122. """Check for printf related issues.
  4123. Args:
  4124. filename: The name of the current file.
  4125. clean_lines: A CleansedLines instance containing the file.
  4126. linenum: The number of the line to check.
  4127. error: The function to call with any errors found.
  4128. """
  4129. line = clean_lines.elided[linenum]
  4130. # When snprintf is used, the second argument shouldn't be a literal.
  4131. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
  4132. if match and match.group(2) != '0':
  4133. # If 2nd arg is zero, snprintf is used to calculate size.
  4134. error(filename, linenum, 'runtime/printf', 3,
  4135. 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
  4136. 'to snprintf.' % (match.group(1), match.group(2)))
  4137. # Check if some verboten C functions are being used.
  4138. if Search(r'\bsprintf\s*\(', line):
  4139. error(filename, linenum, 'runtime/printf', 5,
  4140. 'Never use sprintf. Use snprintf instead.')
  4141. match = Search(r'\b(strcpy|strcat)\s*\(', line)
  4142. if match:
  4143. error(filename, linenum, 'runtime/printf', 4,
  4144. 'Almost always, snprintf is better than %s' % match.group(1))
  4145. def IsDerivedFunction(clean_lines, linenum):
  4146. """Check if current line contains an inherited function.
  4147. Args:
  4148. clean_lines: A CleansedLines instance containing the file.
  4149. linenum: The number of the line to check.
  4150. Returns:
  4151. True if current line contains a function with "override"
  4152. virt-specifier.
  4153. """
  4154. # Scan back a few lines for start of current function
  4155. for i in xrange(linenum, max(-1, linenum - 10), -1):
  4156. match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
  4157. if match:
  4158. # Look for "override" after the matching closing parenthesis
  4159. line, _, closing_paren = CloseExpression(
  4160. clean_lines, i, len(match.group(1)))
  4161. return (closing_paren >= 0 and
  4162. Search(r'\boverride\b', line[closing_paren:]))
  4163. return False
  4164. def IsOutOfLineMethodDefinition(clean_lines, linenum):
  4165. """Check if current line contains an out-of-line method definition.
  4166. Args:
  4167. clean_lines: A CleansedLines instance containing the file.
  4168. linenum: The number of the line to check.
  4169. Returns:
  4170. True if current line contains an out-of-line method definition.
  4171. """
  4172. # Scan back a few lines for start of current function
  4173. for i in xrange(linenum, max(-1, linenum - 10), -1):
  4174. if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
  4175. return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
  4176. return False
  4177. def IsInitializerList(clean_lines, linenum):
  4178. """Check if current line is inside constructor initializer list.
  4179. Args:
  4180. clean_lines: A CleansedLines instance containing the file.
  4181. linenum: The number of the line to check.
  4182. Returns:
  4183. True if current line appears to be inside constructor initializer
  4184. list, False otherwise.
  4185. """
  4186. for i in xrange(linenum, 1, -1):
  4187. line = clean_lines.elided[i]
  4188. if i == linenum:
  4189. remove_function_body = Match(r'^(.*)\{\s*$', line)
  4190. if remove_function_body:
  4191. line = remove_function_body.group(1)
  4192. if Search(r'\s:\s*\w+[({]', line):
  4193. # A lone colon tend to indicate the start of a constructor
  4194. # initializer list. It could also be a ternary operator, which
  4195. # also tend to appear in constructor initializer lists as
  4196. # opposed to parameter lists.
  4197. return True
  4198. if Search(r'\}\s*,\s*$', line):
  4199. # A closing brace followed by a comma is probably the end of a
  4200. # brace-initialized member in constructor initializer list.
  4201. return True
  4202. if Search(r'[{};]\s*$', line):
  4203. # Found one of the following:
  4204. # - A closing brace or semicolon, probably the end of the previous
  4205. # function.
  4206. # - An opening brace, probably the start of current class or namespace.
  4207. #
  4208. # Current line is probably not inside an initializer list since
  4209. # we saw one of those things without seeing the starting colon.
  4210. return False
  4211. # Got to the beginning of the file without seeing the start of
  4212. # constructor initializer list.
  4213. return False
  4214. def CheckForNonConstReference(filename, clean_lines, linenum,
  4215. nesting_state, error):
  4216. """Check for non-const references.
  4217. Separate from CheckLanguage since it scans backwards from current
  4218. line, instead of scanning forward.
  4219. Args:
  4220. filename: The name of the current file.
  4221. clean_lines: A CleansedLines instance containing the file.
  4222. linenum: The number of the line to check.
  4223. nesting_state: A NestingState instance which maintains information about
  4224. the current stack of nested blocks being parsed.
  4225. error: The function to call with any errors found.
  4226. """
  4227. # Do nothing if there is no '&' on current line.
  4228. line = clean_lines.elided[linenum]
  4229. if '&' not in line:
  4230. return
  4231. # If a function is inherited, current function doesn't have much of
  4232. # a choice, so any non-const references should not be blamed on
  4233. # derived function.
  4234. if IsDerivedFunction(clean_lines, linenum):
  4235. return
  4236. # Don't warn on out-of-line method definitions, as we would warn on the
  4237. # in-line declaration, if it isn't marked with 'override'.
  4238. if IsOutOfLineMethodDefinition(clean_lines, linenum):
  4239. return
  4240. # Long type names may be broken across multiple lines, usually in one
  4241. # of these forms:
  4242. # LongType
  4243. # ::LongTypeContinued &identifier
  4244. # LongType::
  4245. # LongTypeContinued &identifier
  4246. # LongType<
  4247. # ...>::LongTypeContinued &identifier
  4248. #
  4249. # If we detected a type split across two lines, join the previous
  4250. # line to current line so that we can match const references
  4251. # accordingly.
  4252. #
  4253. # Note that this only scans back one line, since scanning back
  4254. # arbitrary number of lines would be expensive. If you have a type
  4255. # that spans more than 2 lines, please use a typedef.
  4256. if linenum > 1:
  4257. previous = None
  4258. if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
  4259. # previous_line\n + ::current_line
  4260. previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
  4261. clean_lines.elided[linenum - 1])
  4262. elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
  4263. # previous_line::\n + current_line
  4264. previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
  4265. clean_lines.elided[linenum - 1])
  4266. if previous:
  4267. line = previous.group(1) + line.lstrip()
  4268. else:
  4269. # Check for templated parameter that is split across multiple lines
  4270. endpos = line.rfind('>')
  4271. if endpos > -1:
  4272. (_, startline, startpos) = ReverseCloseExpression(
  4273. clean_lines, linenum, endpos)
  4274. if startpos > -1 and startline < linenum:
  4275. # Found the matching < on an earlier line, collect all
  4276. # pieces up to current line.
  4277. line = ''
  4278. for i in xrange(startline, linenum + 1):
  4279. line += clean_lines.elided[i].strip()
  4280. # Check for non-const references in function parameters. A single '&' may
  4281. # found in the following places:
  4282. # inside expression: binary & for bitwise AND
  4283. # inside expression: unary & for taking the address of something
  4284. # inside declarators: reference parameter
  4285. # We will exclude the first two cases by checking that we are not inside a
  4286. # function body, including one that was just introduced by a trailing '{'.
  4287. # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
  4288. if (nesting_state.previous_stack_top and
  4289. not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
  4290. isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
  4291. # Not at toplevel, not within a class, and not within a namespace
  4292. return
  4293. # Avoid initializer lists. We only need to scan back from the
  4294. # current line for something that starts with ':'.
  4295. #
  4296. # We don't need to check the current line, since the '&' would
  4297. # appear inside the second set of parentheses on the current line as
  4298. # opposed to the first set.
  4299. if linenum > 0:
  4300. for i in xrange(linenum - 1, max(0, linenum - 10), -1):
  4301. previous_line = clean_lines.elided[i]
  4302. if not Search(r'[),]\s*$', previous_line):
  4303. break
  4304. if Match(r'^\s*:\s+\S', previous_line):
  4305. return
  4306. # Avoid preprocessors
  4307. if Search(r'\\\s*$', line):
  4308. return
  4309. # Avoid constructor initializer lists
  4310. if IsInitializerList(clean_lines, linenum):
  4311. return
  4312. # We allow non-const references in a few standard places, like functions
  4313. # called "swap()" or iostream operators like "<<" or ">>". Do not check
  4314. # those function parameters.
  4315. #
  4316. # We also accept & in static_assert, which looks like a function but
  4317. # it's actually a declaration expression.
  4318. whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
  4319. r'operator\s*[<>][<>]|'
  4320. r'static_assert|COMPILE_ASSERT'
  4321. r')\s*\(')
  4322. if Search(whitelisted_functions, line):
  4323. return
  4324. elif not Search(r'\S+\([^)]*$', line):
  4325. # Don't see a whitelisted function on this line. Actually we
  4326. # didn't see any function name on this line, so this is likely a
  4327. # multi-line parameter list. Try a bit harder to catch this case.
  4328. for i in xrange(2):
  4329. if (linenum > i and
  4330. Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
  4331. return
  4332. decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
  4333. for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
  4334. if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
  4335. not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
  4336. error(filename, linenum, 'runtime/references', 2,
  4337. 'Is this a non-const reference? '
  4338. 'If so, make const or use a pointer: ' +
  4339. ReplaceAll(' *<', '<', parameter))
  4340. def CheckCasts(filename, clean_lines, linenum, error):
  4341. """Various cast related checks.
  4342. Args:
  4343. filename: The name of the current file.
  4344. clean_lines: A CleansedLines instance containing the file.
  4345. linenum: The number of the line to check.
  4346. error: The function to call with any errors found.
  4347. """
  4348. line = clean_lines.elided[linenum]
  4349. # Check to see if they're using an conversion function cast.
  4350. # I just try to capture the most common basic types, though there are more.
  4351. # Parameterless conversion functions, such as bool(), are allowed as they are
  4352. # probably a member operator declaration or default constructor.
  4353. match = Search(
  4354. r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'
  4355. r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
  4356. r'(\([^)].*)', line)
  4357. expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
  4358. if match and not expecting_function:
  4359. matched_type = match.group(2)
  4360. # matched_new_or_template is used to silence two false positives:
  4361. # - New operators
  4362. # - Template arguments with function types
  4363. #
  4364. # For template arguments, we match on types immediately following
  4365. # an opening bracket without any spaces. This is a fast way to
  4366. # silence the common case where the function type is the first
  4367. # template argument. False negative with less-than comparison is
  4368. # avoided because those operators are usually followed by a space.
  4369. #
  4370. # function<double(double)> // bracket + no space = false positive
  4371. # value < double(42) // bracket + space = true positive
  4372. matched_new_or_template = match.group(1)
  4373. # Avoid arrays by looking for brackets that come after the closing
  4374. # parenthesis.
  4375. if Match(r'\([^()]+\)\s*\[', match.group(3)):
  4376. return
  4377. # Other things to ignore:
  4378. # - Function pointers
  4379. # - Casts to pointer types
  4380. # - Placement new
  4381. # - Alias declarations
  4382. matched_funcptr = match.group(3)
  4383. if (matched_new_or_template is None and
  4384. not (matched_funcptr and
  4385. (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
  4386. matched_funcptr) or
  4387. matched_funcptr.startswith('(*)'))) and
  4388. not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
  4389. not Search(r'new\(\S+\)\s*' + matched_type, line)):
  4390. error(filename, linenum, 'readability/casting', 4,
  4391. 'Using deprecated casting style. '
  4392. 'Use static_cast<%s>(...) instead' %
  4393. matched_type)
  4394. if not expecting_function:
  4395. CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
  4396. r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
  4397. # This doesn't catch all cases. Consider (const char * const)"hello".
  4398. #
  4399. # (char *) "foo" should always be a const_cast (reinterpret_cast won't
  4400. # compile).
  4401. if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
  4402. r'\((char\s?\*+\s?)\)\s*"', error):
  4403. pass
  4404. else:
  4405. # Check pointer casts for other than string constants
  4406. CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
  4407. r'\((\w+\s?\*+\s?)\)', error)
  4408. # In addition, we look for people taking the address of a cast. This
  4409. # is dangerous -- casts can assign to temporaries, so the pointer doesn't
  4410. # point where you think.
  4411. #
  4412. # Some non-identifier character is required before the '&' for the
  4413. # expression to be recognized as a cast. These are casts:
  4414. # expression = &static_cast<int*>(temporary());
  4415. # function(&(int*)(temporary()));
  4416. #
  4417. # This is not a cast:
  4418. # reference_type&(int* function_param);
  4419. match = Search(
  4420. r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
  4421. r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
  4422. if match:
  4423. # Try a better error message when the & is bound to something
  4424. # dereferenced by the casted pointer, as opposed to the casted
  4425. # pointer itself.
  4426. parenthesis_error = False
  4427. match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
  4428. if match:
  4429. _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
  4430. if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
  4431. _, y2, x2 = CloseExpression(clean_lines, y1, x1)
  4432. if x2 >= 0:
  4433. extended_line = clean_lines.elided[y2][x2:]
  4434. if y2 < clean_lines.NumLines() - 1:
  4435. extended_line += clean_lines.elided[y2 + 1]
  4436. if Match(r'\s*(?:->|\[)', extended_line):
  4437. parenthesis_error = True
  4438. if parenthesis_error:
  4439. error(filename, linenum, 'readability/casting', 4,
  4440. ('Are you taking an address of something dereferenced '
  4441. 'from a cast? Wrapping the dereferenced expression in '
  4442. 'parentheses will make the binding more obvious'))
  4443. else:
  4444. error(filename, linenum, 'runtime/casting', 4,
  4445. ('Are you taking an address of a cast? '
  4446. 'This is dangerous: could be a temp var. '
  4447. 'Take the address before doing the cast, rather than after'))
  4448. def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
  4449. """Checks for a C-style cast by looking for the pattern.
  4450. Args:
  4451. filename: The name of the current file.
  4452. clean_lines: A CleansedLines instance containing the file.
  4453. linenum: The number of the line to check.
  4454. cast_type: The string for the C++ cast to recommend. This is either
  4455. reinterpret_cast, static_cast, or const_cast, depending.
  4456. pattern: The regular expression used to find C-style casts.
  4457. error: The function to call with any errors found.
  4458. Returns:
  4459. True if an error was emitted.
  4460. False otherwise.
  4461. """
  4462. line = clean_lines.elided[linenum]
  4463. match = Search(pattern, line)
  4464. if not match:
  4465. return False
  4466. # Exclude lines with keywords that tend to look like casts
  4467. context = line[0:match.start(1) - 1]
  4468. if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
  4469. return False
  4470. # Try expanding current context to see if we one level of
  4471. # parentheses inside a macro.
  4472. if linenum > 0:
  4473. for i in xrange(linenum - 1, max(0, linenum - 5), -1):
  4474. context = clean_lines.elided[i] + context
  4475. if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
  4476. return False
  4477. # operator++(int) and operator--(int)
  4478. if context.endswith(' operator++') or context.endswith(' operator--'):
  4479. return False
  4480. # A single unnamed argument for a function tends to look like old style cast.
  4481. # If we see those, don't issue warnings for deprecated casts.
  4482. remainder = line[match.end(0):]
  4483. if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
  4484. remainder):
  4485. return False
  4486. # At this point, all that should be left is actual casts.
  4487. error(filename, linenum, 'readability/casting', 4,
  4488. 'Using C-style cast. Use %s<%s>(...) instead' %
  4489. (cast_type, match.group(1)))
  4490. return True
  4491. def ExpectingFunctionArgs(clean_lines, linenum):
  4492. """Checks whether where function type arguments are expected.
  4493. Args:
  4494. clean_lines: A CleansedLines instance containing the file.
  4495. linenum: The number of the line to check.
  4496. Returns:
  4497. True if the line at 'linenum' is inside something that expects arguments
  4498. of function types.
  4499. """
  4500. line = clean_lines.elided[linenum]
  4501. return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
  4502. (linenum >= 2 and
  4503. (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
  4504. clean_lines.elided[linenum - 1]) or
  4505. Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
  4506. clean_lines.elided[linenum - 2]) or
  4507. Search(r'\bstd::m?function\s*\<\s*$',
  4508. clean_lines.elided[linenum - 1]))))
  4509. _HEADERS_CONTAINING_TEMPLATES = (
  4510. ('<deque>', ('deque',)),
  4511. ('<functional>', ('unary_function', 'binary_function',
  4512. 'plus', 'minus', 'multiplies', 'divides', 'modulus',
  4513. 'negate',
  4514. 'equal_to', 'not_equal_to', 'greater', 'less',
  4515. 'greater_equal', 'less_equal',
  4516. 'logical_and', 'logical_or', 'logical_not',
  4517. 'unary_negate', 'not1', 'binary_negate', 'not2',
  4518. 'bind1st', 'bind2nd',
  4519. 'pointer_to_unary_function',
  4520. 'pointer_to_binary_function',
  4521. 'ptr_fun',
  4522. 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
  4523. 'mem_fun_ref_t',
  4524. 'const_mem_fun_t', 'const_mem_fun1_t',
  4525. 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
  4526. 'mem_fun_ref',
  4527. )),
  4528. ('<limits>', ('numeric_limits',)),
  4529. ('<list>', ('list',)),
  4530. ('<map>', ('map', 'multimap',)),
  4531. ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
  4532. 'unique_ptr', 'weak_ptr')),
  4533. ('<queue>', ('queue', 'priority_queue',)),
  4534. ('<set>', ('set', 'multiset',)),
  4535. ('<stack>', ('stack',)),
  4536. ('<string>', ('char_traits', 'basic_string',)),
  4537. ('<tuple>', ('tuple',)),
  4538. ('<unordered_map>', ('unordered_map', 'unordered_multimap')),
  4539. ('<unordered_set>', ('unordered_set', 'unordered_multiset')),
  4540. ('<utility>', ('pair',)),
  4541. ('<vector>', ('vector',)),
  4542. # gcc extensions.
  4543. # Note: std::hash is their hash, ::hash is our hash
  4544. ('<hash_map>', ('hash_map', 'hash_multimap',)),
  4545. ('<hash_set>', ('hash_set', 'hash_multiset',)),
  4546. ('<slist>', ('slist',)),
  4547. )
  4548. _HEADERS_MAYBE_TEMPLATES = (
  4549. ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',
  4550. 'transform',
  4551. )),
  4552. ('<utility>', ('forward', 'make_pair', 'move', 'swap')),
  4553. )
  4554. _RE_PATTERN_STRING = re.compile(r'\bstring\b')
  4555. _re_pattern_headers_maybe_templates = []
  4556. for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
  4557. for _template in _templates:
  4558. # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
  4559. # type::max().
  4560. _re_pattern_headers_maybe_templates.append(
  4561. (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
  4562. _template,
  4563. _header))
  4564. # Other scripts may reach in and modify this pattern.
  4565. _re_pattern_templates = []
  4566. for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
  4567. for _template in _templates:
  4568. _re_pattern_templates.append(
  4569. (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
  4570. _template + '<>',
  4571. _header))
  4572. def FilesBelongToSameModule(filename_cc, filename_h):
  4573. """Check if these two filenames belong to the same module.
  4574. The concept of a 'module' here is a as follows:
  4575. foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
  4576. same 'module' if they are in the same directory.
  4577. some/path/public/xyzzy and some/path/internal/xyzzy are also considered
  4578. to belong to the same module here.
  4579. If the filename_cc contains a longer path than the filename_h, for example,
  4580. '/absolute/path/to/base/sysinfo.cc', and this file would include
  4581. 'base/sysinfo.h', this function also produces the prefix needed to open the
  4582. header. This is used by the caller of this function to more robustly open the
  4583. header file. We don't have access to the real include paths in this context,
  4584. so we need this guesswork here.
  4585. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
  4586. according to this implementation. Because of this, this function gives
  4587. some false positives. This should be sufficiently rare in practice.
  4588. Args:
  4589. filename_cc: is the path for the .cc file
  4590. filename_h: is the path for the header path
  4591. Returns:
  4592. Tuple with a bool and a string:
  4593. bool: True if filename_cc and filename_h belong to the same module.
  4594. string: the additional prefix needed to open the header file.
  4595. """
  4596. fileinfo = FileInfo(filename_cc)
  4597. if not fileinfo.IsSource():
  4598. return (False, '')
  4599. filename_cc = filename_cc[:-len(fileinfo.Extension())]
  4600. matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())
  4601. if matched_test_suffix:
  4602. filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
  4603. filename_cc = filename_cc.replace('/public/', '/')
  4604. filename_cc = filename_cc.replace('/internal/', '/')
  4605. if not filename_h.endswith('.h'):
  4606. return (False, '')
  4607. filename_h = filename_h[:-len('.h')]
  4608. if filename_h.endswith('-inl'):
  4609. filename_h = filename_h[:-len('-inl')]
  4610. filename_h = filename_h.replace('/public/', '/')
  4611. filename_h = filename_h.replace('/internal/', '/')
  4612. files_belong_to_same_module = filename_cc.endswith(filename_h)
  4613. common_path = ''
  4614. if files_belong_to_same_module:
  4615. common_path = filename_cc[:-len(filename_h)]
  4616. return files_belong_to_same_module, common_path
  4617. def UpdateIncludeState(filename, include_dict, io=codecs):
  4618. """Fill up the include_dict with new includes found from the file.
  4619. Args:
  4620. filename: the name of the header to read.
  4621. include_dict: a dictionary in which the headers are inserted.
  4622. io: The io factory to use to read the file. Provided for testability.
  4623. Returns:
  4624. True if a header was successfully added. False otherwise.
  4625. """
  4626. headerfile = None
  4627. try:
  4628. headerfile = io.open(filename, 'r', 'utf8', 'replace')
  4629. except IOError:
  4630. return False
  4631. linenum = 0
  4632. for line in headerfile:
  4633. linenum += 1
  4634. clean_line = CleanseComments(line)
  4635. match = _RE_PATTERN_INCLUDE.search(clean_line)
  4636. if match:
  4637. include = match.group(2)
  4638. include_dict.setdefault(include, linenum)
  4639. return True
  4640. def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
  4641. io=codecs):
  4642. """Reports for missing stl includes.
  4643. This function will output warnings to make sure you are including the headers
  4644. necessary for the stl containers and functions that you use. We only give one
  4645. reason to include a header. For example, if you use both equal_to<> and
  4646. less<> in a .h file, only one (the latter in the file) of these will be
  4647. reported as a reason to include the <functional>.
  4648. Args:
  4649. filename: The name of the current file.
  4650. clean_lines: A CleansedLines instance containing the file.
  4651. include_state: An _IncludeState instance.
  4652. error: The function to call with any errors found.
  4653. io: The IO factory to use to read the header file. Provided for unittest
  4654. injection.
  4655. """
  4656. required = {} # A map of header name to linenumber and the template entity.
  4657. # Example of required: { '<functional>': (1219, 'less<>') }
  4658. for linenum in xrange(clean_lines.NumLines()):
  4659. line = clean_lines.elided[linenum]
  4660. if not line or line[0] == '#':
  4661. continue
  4662. # String is special -- it is a non-templatized type in STL.
  4663. matched = _RE_PATTERN_STRING.search(line)
  4664. if matched:
  4665. # Don't warn about strings in non-STL namespaces:
  4666. # (We check only the first match per line; good enough.)
  4667. prefix = line[:matched.start()]
  4668. if prefix.endswith('std::') or not prefix.endswith('::'):
  4669. required['<string>'] = (linenum, 'string')
  4670. for pattern, template, header in _re_pattern_headers_maybe_templates:
  4671. if pattern.search(line):
  4672. required[header] = (linenum, template)
  4673. # The following function is just a speed up, no semantics are changed.
  4674. if not '<' in line: # Reduces the cpu time usage by skipping lines.
  4675. continue
  4676. for pattern, template, header in _re_pattern_templates:
  4677. matched = pattern.search(line)
  4678. if matched:
  4679. # Don't warn about IWYU in non-STL namespaces:
  4680. # (We check only the first match per line; good enough.)
  4681. prefix = line[:matched.start()]
  4682. if prefix.endswith('std::') or not prefix.endswith('::'):
  4683. required[header] = (linenum, template)
  4684. # The policy is that if you #include something in foo.h you don't need to
  4685. # include it again in foo.cc. Here, we will look at possible includes.
  4686. # Let's flatten the include_state include_list and copy it into a dictionary.
  4687. include_dict = dict([item for sublist in include_state.include_list
  4688. for item in sublist])
  4689. # Did we find the header for this file (if any) and successfully load it?
  4690. header_found = False
  4691. # Use the absolute path so that matching works properly.
  4692. abs_filename = FileInfo(filename).FullName()
  4693. # For Emacs's flymake.
  4694. # If cpplint is invoked from Emacs's flymake, a temporary file is generated
  4695. # by flymake and that file name might end with '_flymake.cc'. In that case,
  4696. # restore original file name here so that the corresponding header file can be
  4697. # found.
  4698. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
  4699. # instead of 'foo_flymake.h'
  4700. abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
  4701. # include_dict is modified during iteration, so we iterate over a copy of
  4702. # the keys.
  4703. header_keys = include_dict.keys()
  4704. for header in header_keys:
  4705. (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
  4706. fullpath = common_path + header
  4707. if same_module and UpdateIncludeState(fullpath, include_dict, io):
  4708. header_found = True
  4709. # If we can't find the header file for a .cc, assume it's because we don't
  4710. # know where to look. In that case we'll give up as we're not sure they
  4711. # didn't include it in the .h file.
  4712. # TODO(unknown): Do a better job of finding .h files so we are confident that
  4713. # not having the .h file means there isn't one.
  4714. if filename.endswith('.cc') and not header_found:
  4715. return
  4716. # All the lines have been processed, report the errors found.
  4717. for required_header_unstripped in required:
  4718. template = required[required_header_unstripped][1]
  4719. if required_header_unstripped.strip('<>"') not in include_dict:
  4720. error(filename, required[required_header_unstripped][0],
  4721. 'build/include_what_you_use', 4,
  4722. 'Add #include ' + required_header_unstripped + ' for ' + template)
  4723. _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
  4724. def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
  4725. """Check that make_pair's template arguments are deduced.
  4726. G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
  4727. specified explicitly, and such use isn't intended in any case.
  4728. Args:
  4729. filename: The name of the current file.
  4730. clean_lines: A CleansedLines instance containing the file.
  4731. linenum: The number of the line to check.
  4732. error: The function to call with any errors found.
  4733. """
  4734. line = clean_lines.elided[linenum]
  4735. match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
  4736. if match:
  4737. error(filename, linenum, 'build/explicit_make_pair',
  4738. 4, # 4 = high confidence
  4739. 'For C++11-compatibility, omit template arguments from make_pair'
  4740. ' OR use pair directly OR if appropriate, construct a pair directly')
  4741. def CheckRedundantVirtual(filename, clean_lines, linenum, error):
  4742. """Check if line contains a redundant "virtual" function-specifier.
  4743. Args:
  4744. filename: The name of the current file.
  4745. clean_lines: A CleansedLines instance containing the file.
  4746. linenum: The number of the line to check.
  4747. error: The function to call with any errors found.
  4748. """
  4749. # Look for "virtual" on current line.
  4750. line = clean_lines.elided[linenum]
  4751. virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
  4752. if not virtual: return
  4753. # Ignore "virtual" keywords that are near access-specifiers. These
  4754. # are only used in class base-specifier and do not apply to member
  4755. # functions.
  4756. if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
  4757. Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
  4758. return
  4759. # Ignore the "virtual" keyword from virtual base classes. Usually
  4760. # there is a column on the same line in these cases (virtual base
  4761. # classes are rare in google3 because multiple inheritance is rare).
  4762. if Match(r'^.*[^:]:[^:].*$', line): return
  4763. # Look for the next opening parenthesis. This is the start of the
  4764. # parameter list (possibly on the next line shortly after virtual).
  4765. # TODO(unknown): doesn't work if there are virtual functions with
  4766. # decltype() or other things that use parentheses, but csearch suggests
  4767. # that this is rare.
  4768. end_col = -1
  4769. end_line = -1
  4770. start_col = len(virtual.group(2))
  4771. for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())):
  4772. line = clean_lines.elided[start_line][start_col:]
  4773. parameter_list = Match(r'^([^(]*)\(', line)
  4774. if parameter_list:
  4775. # Match parentheses to find the end of the parameter list
  4776. (_, end_line, end_col) = CloseExpression(
  4777. clean_lines, start_line, start_col + len(parameter_list.group(1)))
  4778. break
  4779. start_col = 0
  4780. if end_col < 0:
  4781. return # Couldn't find end of parameter list, give up
  4782. # Look for "override" or "final" after the parameter list
  4783. # (possibly on the next few lines).
  4784. for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())):
  4785. line = clean_lines.elided[i][end_col:]
  4786. match = Search(r'\b(override|final)\b', line)
  4787. if match:
  4788. error(filename, linenum, 'readability/inheritance', 4,
  4789. ('"virtual" is redundant since function is '
  4790. 'already declared as "%s"' % match.group(1)))
  4791. # Set end_col to check whole lines after we are done with the
  4792. # first line.
  4793. end_col = 0
  4794. if Search(r'[^\w]\s*$', line):
  4795. break
  4796. def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
  4797. """Check if line contains a redundant "override" or "final" virt-specifier.
  4798. Args:
  4799. filename: The name of the current file.
  4800. clean_lines: A CleansedLines instance containing the file.
  4801. linenum: The number of the line to check.
  4802. error: The function to call with any errors found.
  4803. """
  4804. # Look for closing parenthesis nearby. We need one to confirm where
  4805. # the declarator ends and where the virt-specifier starts to avoid
  4806. # false positives.
  4807. line = clean_lines.elided[linenum]
  4808. declarator_end = line.rfind(')')
  4809. if declarator_end >= 0:
  4810. fragment = line[declarator_end:]
  4811. else:
  4812. if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
  4813. fragment = line
  4814. else:
  4815. return
  4816. # Check that at most one of "override" or "final" is present, not both
  4817. if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
  4818. error(filename, linenum, 'readability/inheritance', 4,
  4819. ('"override" is redundant since function is '
  4820. 'already declared as "final"'))
  4821. # Returns true if we are at a new block, and it is directly
  4822. # inside of a namespace.
  4823. def IsBlockInNameSpace(nesting_state, is_forward_declaration):
  4824. """Checks that the new block is directly in a namespace.
  4825. Args:
  4826. nesting_state: The _NestingState object that contains info about our state.
  4827. is_forward_declaration: If the class is a forward declared class.
  4828. Returns:
  4829. Whether or not the new block is directly in a namespace.
  4830. """
  4831. if is_forward_declaration:
  4832. if len(nesting_state.stack) >= 1 and (
  4833. isinstance(nesting_state.stack[-1], _NamespaceInfo)):
  4834. return True
  4835. else:
  4836. return False
  4837. return (len(nesting_state.stack) > 1 and
  4838. nesting_state.stack[-1].check_namespace_indentation and
  4839. isinstance(nesting_state.stack[-2], _NamespaceInfo))
  4840. def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
  4841. raw_lines_no_comments, linenum):
  4842. """This method determines if we should apply our namespace indentation check.
  4843. Args:
  4844. nesting_state: The current nesting state.
  4845. is_namespace_indent_item: If we just put a new class on the stack, True.
  4846. If the top of the stack is not a class, or we did not recently
  4847. add the class, False.
  4848. raw_lines_no_comments: The lines without the comments.
  4849. linenum: The current line number we are processing.
  4850. Returns:
  4851. True if we should apply our namespace indentation check. Currently, it
  4852. only works for classes and namespaces inside of a namespace.
  4853. """
  4854. is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
  4855. linenum)
  4856. if not (is_namespace_indent_item or is_forward_declaration):
  4857. return False
  4858. # If we are in a macro, we do not want to check the namespace indentation.
  4859. if IsMacroDefinition(raw_lines_no_comments, linenum):
  4860. return False
  4861. return IsBlockInNameSpace(nesting_state, is_forward_declaration)
  4862. # Call this method if the line is directly inside of a namespace.
  4863. # If the line above is blank (excluding comments) or the start of
  4864. # an inner namespace, it cannot be indented.
  4865. def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
  4866. error):
  4867. line = raw_lines_no_comments[linenum]
  4868. if Match(r'^\s+', line):
  4869. error(filename, linenum, 'runtime/indentation_namespace', 4,
  4870. 'Do not indent within a namespace')
  4871. def ProcessLine(filename, file_extension, clean_lines, line,
  4872. include_state, function_state, nesting_state, error,
  4873. extra_check_functions=[]):
  4874. """Processes a single line in the file.
  4875. Args:
  4876. filename: Filename of the file that is being processed.
  4877. file_extension: The extension (dot not included) of the file.
  4878. clean_lines: An array of strings, each representing a line of the file,
  4879. with comments stripped.
  4880. line: Number of line being processed.
  4881. include_state: An _IncludeState instance in which the headers are inserted.
  4882. function_state: A _FunctionState instance which counts function lines, etc.
  4883. nesting_state: A NestingState instance which maintains information about
  4884. the current stack of nested blocks being parsed.
  4885. error: A callable to which errors are reported, which takes 4 arguments:
  4886. filename, line number, error level, and message
  4887. extra_check_functions: An array of additional check functions that will be
  4888. run on each source line. Each function takes 4
  4889. arguments: filename, clean_lines, line, error
  4890. """
  4891. raw_lines = clean_lines.raw_lines
  4892. ParseNolintSuppressions(filename, raw_lines[line], line, error)
  4893. nesting_state.Update(filename, clean_lines, line, error)
  4894. CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
  4895. error)
  4896. if nesting_state.InAsmBlock(): return
  4897. CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
  4898. CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
  4899. CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
  4900. CheckLanguage(filename, clean_lines, line, file_extension, include_state,
  4901. nesting_state, error)
  4902. CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
  4903. CheckForNonStandardConstructs(filename, clean_lines, line,
  4904. nesting_state, error)
  4905. CheckVlogArguments(filename, clean_lines, line, error)
  4906. CheckPosixThreading(filename, clean_lines, line, error)
  4907. CheckInvalidIncrement(filename, clean_lines, line, error)
  4908. CheckMakePairUsesDeduction(filename, clean_lines, line, error)
  4909. CheckRedundantVirtual(filename, clean_lines, line, error)
  4910. CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
  4911. for check_fn in extra_check_functions:
  4912. check_fn(filename, clean_lines, line, error)
  4913. def FlagCxx11Features(filename, clean_lines, linenum, error):
  4914. """Flag those c++11 features that we only allow in certain places.
  4915. Args:
  4916. filename: The name of the current file.
  4917. clean_lines: A CleansedLines instance containing the file.
  4918. linenum: The number of the line to check.
  4919. error: The function to call with any errors found.
  4920. """
  4921. line = clean_lines.elided[linenum]
  4922. include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
  4923. # Flag unapproved C++ TR1 headers.
  4924. if include and include.group(1).startswith('tr1/'):
  4925. error(filename, linenum, 'build/c++tr1', 5,
  4926. ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
  4927. # Flag unapproved C++11 headers.
  4928. if include and include.group(1) in ('cfenv',
  4929. 'condition_variable',
  4930. 'fenv.h',
  4931. 'future',
  4932. 'mutex',
  4933. 'thread',
  4934. 'chrono',
  4935. 'ratio',
  4936. 'regex',
  4937. 'system_error',
  4938. ):
  4939. error(filename, linenum, 'build/c++11', 5,
  4940. ('<%s> is an unapproved C++11 header.') % include.group(1))
  4941. # The only place where we need to worry about C++11 keywords and library
  4942. # features in preprocessor directives is in macro definitions.
  4943. if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
  4944. # These are classes and free functions. The classes are always
  4945. # mentioned as std::*, but we only catch the free functions if
  4946. # they're not found by ADL. They're alphabetical by header.
  4947. for top_name in (
  4948. # type_traits
  4949. 'alignment_of',
  4950. 'aligned_union',
  4951. ):
  4952. if Search(r'\bstd::%s\b' % top_name, line):
  4953. error(filename, linenum, 'build/c++11', 5,
  4954. ('std::%s is an unapproved C++11 class or function. Send c-style '
  4955. 'an example of where it would make your code more readable, and '
  4956. 'they may let you use it.') % top_name)
  4957. def FlagCxx14Features(filename, clean_lines, linenum, error):
  4958. """Flag those C++14 features that we restrict.
  4959. Args:
  4960. filename: The name of the current file.
  4961. clean_lines: A CleansedLines instance containing the file.
  4962. linenum: The number of the line to check.
  4963. error: The function to call with any errors found.
  4964. """
  4965. line = clean_lines.elided[linenum]
  4966. include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
  4967. # Flag unapproved C++14 headers.
  4968. if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
  4969. error(filename, linenum, 'build/c++14', 5,
  4970. ('<%s> is an unapproved C++14 header.') % include.group(1))
  4971. def ProcessFileData(filename, file_extension, lines, error,
  4972. extra_check_functions=[]):
  4973. """Performs lint checks and reports any errors to the given error function.
  4974. Args:
  4975. filename: Filename of the file that is being processed.
  4976. file_extension: The extension (dot not included) of the file.
  4977. lines: An array of strings, each representing a line of the file, with the
  4978. last element being empty if the file is terminated with a newline.
  4979. error: A callable to which errors are reported, which takes 4 arguments:
  4980. filename, line number, error level, and message
  4981. extra_check_functions: An array of additional check functions that will be
  4982. run on each source line. Each function takes 4
  4983. arguments: filename, clean_lines, line, error
  4984. """
  4985. lines = (['// marker so line numbers and indices both start at 1'] + lines +
  4986. ['// marker so line numbers end in a known way'])
  4987. include_state = _IncludeState()
  4988. function_state = _FunctionState()
  4989. nesting_state = NestingState()
  4990. ResetNolintSuppressions()
  4991. CheckForCopyright(filename, lines, error)
  4992. ProcessGlobalSuppresions(lines)
  4993. RemoveMultiLineComments(filename, lines, error)
  4994. clean_lines = CleansedLines(lines)
  4995. if IsHeaderExtension(file_extension):
  4996. CheckForHeaderGuard(filename, clean_lines, error)
  4997. for line in xrange(clean_lines.NumLines()):
  4998. ProcessLine(filename, file_extension, clean_lines, line,
  4999. include_state, function_state, nesting_state, error,
  5000. extra_check_functions)
  5001. FlagCxx11Features(filename, clean_lines, line, error)
  5002. nesting_state.CheckCompletedBlocks(filename, error)
  5003. CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
  5004. # Check that the .cc file has included its header if it exists.
  5005. if _IsSourceExtension(file_extension):
  5006. CheckHeaderFileIncluded(filename, include_state, error)
  5007. # We check here rather than inside ProcessLine so that we see raw
  5008. # lines rather than "cleaned" lines.
  5009. CheckForBadCharacters(filename, lines, error)
  5010. CheckForNewlineAtEOF(filename, lines, error)
  5011. def ProcessConfigOverrides(filename):
  5012. """ Loads the configuration files and processes the config overrides.
  5013. Args:
  5014. filename: The name of the file being processed by the linter.
  5015. Returns:
  5016. False if the current |filename| should not be processed further.
  5017. """
  5018. abs_filename = os.path.abspath(filename)
  5019. cfg_filters = []
  5020. keep_looking = True
  5021. while keep_looking:
  5022. abs_path, base_name = os.path.split(abs_filename)
  5023. if not base_name:
  5024. break # Reached the root directory.
  5025. cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
  5026. abs_filename = abs_path
  5027. if not os.path.isfile(cfg_file):
  5028. continue
  5029. try:
  5030. with open(cfg_file) as file_handle:
  5031. for line in file_handle:
  5032. line, _, _ = line.partition('#') # Remove comments.
  5033. if not line.strip():
  5034. continue
  5035. name, _, val = line.partition('=')
  5036. name = name.strip()
  5037. val = val.strip()
  5038. if name == 'set noparent':
  5039. keep_looking = False
  5040. elif name == 'filter':
  5041. cfg_filters.append(val)
  5042. elif name == 'exclude_files':
  5043. # When matching exclude_files pattern, use the base_name of
  5044. # the current file name or the directory name we are processing.
  5045. # For example, if we are checking for lint errors in /foo/bar/baz.cc
  5046. # and we found the .cfg file at /foo/CPPLINT.cfg, then the config
  5047. # file's "exclude_files" filter is meant to be checked against "bar"
  5048. # and not "baz" nor "bar/baz.cc".
  5049. if base_name:
  5050. pattern = re.compile(val)
  5051. if pattern.match(base_name):
  5052. sys.stderr.write('Ignoring "%s": file excluded by "%s". '
  5053. 'File path component "%s" matches '
  5054. 'pattern "%s"\n' %
  5055. (filename, cfg_file, base_name, val))
  5056. return False
  5057. elif name == 'linelength':
  5058. global _line_length
  5059. try:
  5060. _line_length = int(val)
  5061. except ValueError:
  5062. sys.stderr.write('Line length must be numeric.')
  5063. elif name == 'root':
  5064. global _root
  5065. _root = val
  5066. elif name == 'headers':
  5067. ProcessHppHeadersOption(val)
  5068. else:
  5069. sys.stderr.write(
  5070. 'Invalid configuration option (%s) in file %s\n' %
  5071. (name, cfg_file))
  5072. except IOError:
  5073. sys.stderr.write(
  5074. "Skipping config file '%s': Can't open for reading\n" % cfg_file)
  5075. keep_looking = False
  5076. # Apply all the accumulated filters in reverse order (top-level directory
  5077. # config options having the least priority).
  5078. for filter in reversed(cfg_filters):
  5079. _AddFilters(filter)
  5080. return True
  5081. def ProcessFile(filename, vlevel, extra_check_functions=[]):
  5082. """Does google-lint on a single file.
  5083. Args:
  5084. filename: The name of the file to parse.
  5085. vlevel: The level of errors to report. Every error of confidence
  5086. >= verbose_level will be reported. 0 is a good default.
  5087. extra_check_functions: An array of additional check functions that will be
  5088. run on each source line. Each function takes 4
  5089. arguments: filename, clean_lines, line, error
  5090. """
  5091. _SetVerboseLevel(vlevel)
  5092. _BackupFilters()
  5093. if not ProcessConfigOverrides(filename):
  5094. _RestoreFilters()
  5095. return
  5096. lf_lines = []
  5097. crlf_lines = []
  5098. try:
  5099. # Support the UNIX convention of using "-" for stdin. Note that
  5100. # we are not opening the file with universal newline support
  5101. # (which codecs doesn't support anyway), so the resulting lines do
  5102. # contain trailing '\r' characters if we are reading a file that
  5103. # has CRLF endings.
  5104. # If after the split a trailing '\r' is present, it is removed
  5105. # below.
  5106. if filename == '-':
  5107. lines = codecs.StreamReaderWriter(sys.stdin,
  5108. codecs.getreader('utf8'),
  5109. codecs.getwriter('utf8'),
  5110. 'replace').read().split('\n')
  5111. else:
  5112. lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
  5113. # Remove trailing '\r'.
  5114. # The -1 accounts for the extra trailing blank line we get from split()
  5115. for linenum in range(len(lines) - 1):
  5116. if lines[linenum].endswith('\r'):
  5117. lines[linenum] = lines[linenum].rstrip('\r')
  5118. crlf_lines.append(linenum + 1)
  5119. else:
  5120. lf_lines.append(linenum + 1)
  5121. except IOError:
  5122. sys.stderr.write(
  5123. "Skipping input '%s': Can't open for reading\n" % filename)
  5124. _RestoreFilters()
  5125. return
  5126. # Note, if no dot is found, this will give the entire filename as the ext.
  5127. file_extension = filename[filename.rfind('.') + 1:]
  5128. # When reading from stdin, the extension is unknown, so no cpplint tests
  5129. # should rely on the extension.
  5130. if filename != '-' and file_extension not in _valid_extensions:
  5131. sys.stderr.write('Ignoring %s; not a valid file name '
  5132. '(%s)\n' % (filename, ', '.join(_valid_extensions)))
  5133. else:
  5134. ProcessFileData(filename, file_extension, lines, Error,
  5135. extra_check_functions)
  5136. # If end-of-line sequences are a mix of LF and CR-LF, issue
  5137. # warnings on the lines with CR.
  5138. #
  5139. # Don't issue any warnings if all lines are uniformly LF or CR-LF,
  5140. # since critique can handle these just fine, and the style guide
  5141. # doesn't dictate a particular end of line sequence.
  5142. #
  5143. # We can't depend on os.linesep to determine what the desired
  5144. # end-of-line sequence should be, since that will return the
  5145. # server-side end-of-line sequence.
  5146. if lf_lines and crlf_lines:
  5147. # Warn on every line with CR. An alternative approach might be to
  5148. # check whether the file is mostly CRLF or just LF, and warn on the
  5149. # minority, we bias toward LF here since most tools prefer LF.
  5150. for linenum in crlf_lines:
  5151. Error(filename, linenum, 'whitespace/newline', 1,
  5152. 'Unexpected \\r (^M) found; better to use only \\n')
  5153. sys.stdout.write('Done processing %s\n' % filename)
  5154. _RestoreFilters()
  5155. def PrintUsage(message):
  5156. """Prints a brief usage string and exits, optionally with an error message.
  5157. Args:
  5158. message: The optional error message.
  5159. """
  5160. sys.stderr.write(_USAGE)
  5161. if message:
  5162. sys.exit('\nFATAL ERROR: ' + message)
  5163. else:
  5164. sys.exit(1)
  5165. def PrintCategories():
  5166. """Prints a list of all the error-categories used by error messages.
  5167. These are the categories used to filter messages via --filter.
  5168. """
  5169. sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
  5170. sys.exit(0)
  5171. def ParseArguments(args):
  5172. """Parses the command line arguments.
  5173. This may set the output format and verbosity level as side-effects.
  5174. Args:
  5175. args: The command line arguments:
  5176. Returns:
  5177. The list of filenames to lint.
  5178. """
  5179. try:
  5180. (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
  5181. 'counting=',
  5182. 'filter=',
  5183. 'root=',
  5184. 'linelength=',
  5185. 'extensions=',
  5186. 'headers='])
  5187. except getopt.GetoptError:
  5188. PrintUsage('Invalid arguments.')
  5189. verbosity = _VerboseLevel()
  5190. output_format = _OutputFormat()
  5191. filters = ''
  5192. counting_style = ''
  5193. for (opt, val) in opts:
  5194. if opt == '--help':
  5195. PrintUsage(None)
  5196. elif opt == '--output':
  5197. if val not in ('emacs', 'vs7', 'eclipse'):
  5198. PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
  5199. output_format = val
  5200. elif opt == '--verbose':
  5201. verbosity = int(val)
  5202. elif opt == '--filter':
  5203. filters = val
  5204. if not filters:
  5205. PrintCategories()
  5206. elif opt == '--counting':
  5207. if val not in ('total', 'toplevel', 'detailed'):
  5208. PrintUsage('Valid counting options are total, toplevel, and detailed')
  5209. counting_style = val
  5210. elif opt == '--root':
  5211. global _root
  5212. _root = val
  5213. elif opt == '--linelength':
  5214. global _line_length
  5215. try:
  5216. _line_length = int(val)
  5217. except ValueError:
  5218. PrintUsage('Line length must be digits.')
  5219. elif opt == '--extensions':
  5220. global _valid_extensions
  5221. try:
  5222. _valid_extensions = set(val.split(','))
  5223. except ValueError:
  5224. PrintUsage('Extensions must be comma seperated list.')
  5225. elif opt == '--headers':
  5226. ProcessHppHeadersOption(val)
  5227. if not filenames:
  5228. PrintUsage('No files were specified.')
  5229. _SetOutputFormat(output_format)
  5230. _SetVerboseLevel(verbosity)
  5231. _SetFilters(filters)
  5232. _SetCountingStyle(counting_style)
  5233. return filenames
  5234. def main():
  5235. filenames = ParseArguments(sys.argv[1:])
  5236. # Change stderr to write with replacement characters so we don't die
  5237. # if we try to print something containing non-ASCII characters.
  5238. sys.stderr = codecs.StreamReaderWriter(sys.stderr,
  5239. codecs.getreader('utf8'),
  5240. codecs.getwriter('utf8'),
  5241. 'replace')
  5242. _cpplint_state.ResetErrorCounts()
  5243. for filename in filenames:
  5244. ProcessFile(filename, _cpplint_state.verbose_level)
  5245. _cpplint_state.PrintErrorCounts()
  5246. sys.exit(_cpplint_state.error_count > 0)
  5247. if __name__ == '__main__':
  5248. main()