lintgit 234 KB

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