Algorithm In Use.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cpplint.py 234KB

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