cpplint.py 235 KB

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