cpplint.py 247 KB

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