cpplint.py 260 KB

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