C++ binding for the SQLite library https://code.ireas.org/sqlitepp/
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 236KB

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