cpplint.py 253 KB

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