cpplint.py 239 KB

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