cpplint.py 250 KB

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