cpplint.py 249 KB

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