cpplint.py 257 KB

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