lintgit 234 KB

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