cpplint.py 230 KB

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