cpplint.py 249 KB

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