cpplint.py 234 KB

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