cpplint.py 260 KB

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