cpplint.py 179 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756
  1. #!/usr/bin/python
  2. #
  3. # Copyright (c) 2009 Google Inc. All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Does google-lint on c++ files.
  31. The goal of this script is to identify places in the code that *may*
  32. be in non-compliance with google style. It does not attempt to fix
  33. up these problems -- the point is to educate. It does also not
  34. attempt to find all problems, or to ensure that everything it does
  35. find is legitimately a problem.
  36. In particular, we can get very confused by /* and // inside strings!
  37. We do a small hack, which is to ignore //'s with "'s after them on the
  38. same line, but it is far from perfect (in either direction).
  39. """
  40. import codecs
  41. import copy
  42. import getopt
  43. import math # for log
  44. import os
  45. import re
  46. import sre_compile
  47. import string
  48. import sys
  49. import unicodedata
  50. _USAGE = """
  51. Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
  52. [--counting=total|toplevel|detailed] [--root=subdir]
  53. [--linelength=digits]
  54. <file> [file] ...
  55. The style guidelines this tries to follow are those in
  56. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
  57. Every problem is given a confidence score from 1-5, with 5 meaning we are
  58. certain of the problem, and 1 meaning it could be a legitimate construct.
  59. This will miss some errors, and is not a substitute for a code review.
  60. To suppress false-positive errors of a certain category, add a
  61. 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)
  62. suppresses errors of all categories on that line.
  63. The files passed in will be linted; at least one file must be provided.
  64. Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the
  65. extensions with the --extensions flag.
  66. Flags:
  67. output=vs7
  68. By default, the output is formatted to ease emacs parsing. Visual Studio
  69. compatible output (vs7) may also be used. Other formats are unsupported.
  70. verbose=#
  71. Specify a number 0-5 to restrict errors to certain verbosity levels.
  72. filter=-x,+y,...
  73. Specify a comma-separated list of category-filters to apply: only
  74. error messages whose category names pass the filters will be printed.
  75. (Category names are printed with the message and look like
  76. "[whitespace/indent]".) Filters are evaluated left to right.
  77. "-FOO" and "FOO" means "do not print categories that start with FOO".
  78. "+FOO" means "do print categories that start with FOO".
  79. Examples: --filter=-whitespace,+whitespace/braces
  80. --filter=whitespace,runtime/printf,+runtime/printf_format
  81. --filter=-,+build/include_what_you_use
  82. To see a list of all the categories used in cpplint, pass no arg:
  83. --filter=
  84. counting=total|toplevel|detailed
  85. The total number of errors found is always printed. If
  86. 'toplevel' is provided, then the count of errors in each of
  87. the top-level categories like 'build' and 'whitespace' will
  88. also be printed. If 'detailed' is provided, then a count
  89. is provided for each category like 'build/class'.
  90. root=subdir
  91. The root directory used for deriving header guard CPP variable.
  92. By default, the header guard CPP variable is calculated as the relative
  93. path to the directory that contains .git, .hg, or .svn. When this flag
  94. is specified, the relative path is calculated from the specified
  95. directory. If the specified directory does not exist, this flag is
  96. ignored.
  97. Examples:
  98. Assuing that src/.git exists, the header guard CPP variables for
  99. src/chrome/browser/ui/browser.h are:
  100. No flag => CHROME_BROWSER_UI_BROWSER_H_
  101. --root=chrome => BROWSER_UI_BROWSER_H_
  102. --root=chrome/browser => UI_BROWSER_H_
  103. linelength=digits
  104. This is the allowed line length for the project. The default value is
  105. 80 characters.
  106. Examples:
  107. --linelength=120
  108. extensions=extension,extension,...
  109. The allowed file extensions that cpplint will check
  110. Examples:
  111. --extensions=hpp,cpp
  112. """
  113. # We categorize each error message we print. Here are the categories.
  114. # We want an explicit list so we can list them all in cpplint --filter=.
  115. # If you add a new error message with a new category, add it to the list
  116. # here! cpplint_unittest.py should tell you if you forget to do this.
  117. _ERROR_CATEGORIES = [
  118. 'build/class',
  119. 'build/deprecated',
  120. 'build/endif_comment',
  121. 'build/explicit_make_pair',
  122. 'build/forward_decl',
  123. 'build/header_guard',
  124. 'build/include',
  125. 'build/include_alpha',
  126. 'build/include_order',
  127. 'build/include_what_you_use',
  128. 'build/namespaces',
  129. 'build/printf_format',
  130. 'build/storage_class',
  131. 'legal/copyright',
  132. 'readability/alt_tokens',
  133. 'readability/braces',
  134. 'readability/casting',
  135. 'readability/check',
  136. 'readability/constructors',
  137. 'readability/fn_size',
  138. 'readability/function',
  139. 'readability/multiline_comment',
  140. 'readability/multiline_string',
  141. 'readability/namespace',
  142. 'readability/nolint',
  143. 'readability/nul',
  144. 'readability/streams',
  145. 'readability/todo',
  146. 'readability/utf8',
  147. 'runtime/arrays',
  148. 'runtime/casting',
  149. 'runtime/explicit',
  150. 'runtime/int',
  151. 'runtime/init',
  152. 'runtime/invalid_increment',
  153. 'runtime/member_string_references',
  154. 'runtime/memset',
  155. 'runtime/operator',
  156. 'runtime/printf',
  157. 'runtime/printf_format',
  158. 'runtime/references',
  159. 'runtime/sizeof',
  160. 'runtime/string',
  161. 'runtime/threadsafe_fn',
  162. 'runtime/vlog',
  163. 'whitespace/blank_line',
  164. 'whitespace/braces',
  165. 'whitespace/comma',
  166. 'whitespace/comments',
  167. 'whitespace/empty_conditional_body',
  168. 'whitespace/empty_loop_body',
  169. 'whitespace/end_of_line',
  170. 'whitespace/ending_newline',
  171. 'whitespace/forcolon',
  172. 'whitespace/indent',
  173. 'whitespace/line_length',
  174. 'whitespace/newline',
  175. 'whitespace/operators',
  176. 'whitespace/parens',
  177. 'whitespace/semicolon',
  178. 'whitespace/tab',
  179. 'whitespace/todo'
  180. ]
  181. # The default state of the category filter. This is overrided by the --filter=
  182. # flag. By default all errors are on, so only add here categories that should be
  183. # off by default (i.e., categories that must be enabled by the --filter= flags).
  184. # All entries here should start with a '-' or '+', as in the --filter= flag.
  185. _DEFAULT_FILTERS = ['-build/include_alpha']
  186. # We used to check for high-bit characters, but after much discussion we
  187. # decided those were OK, as long as they were in UTF-8 and didn't represent
  188. # hard-coded international strings, which belong in a separate i18n file.
  189. # C++ headers
  190. _CPP_HEADERS = frozenset([
  191. # Legacy
  192. 'algobase.h',
  193. 'algo.h',
  194. 'alloc.h',
  195. 'builtinbuf.h',
  196. 'bvector.h',
  197. 'complex.h',
  198. 'defalloc.h',
  199. 'deque.h',
  200. 'editbuf.h',
  201. 'fstream.h',
  202. 'function.h',
  203. 'hash_map',
  204. 'hash_map.h',
  205. 'hash_set',
  206. 'hash_set.h',
  207. 'hashtable.h',
  208. 'heap.h',
  209. 'indstream.h',
  210. 'iomanip.h',
  211. 'iostream.h',
  212. 'istream.h',
  213. 'iterator.h',
  214. 'list.h',
  215. 'map.h',
  216. 'multimap.h',
  217. 'multiset.h',
  218. 'ostream.h',
  219. 'pair.h',
  220. 'parsestream.h',
  221. 'pfstream.h',
  222. 'procbuf.h',
  223. 'pthread_alloc',
  224. 'pthread_alloc.h',
  225. 'rope',
  226. 'rope.h',
  227. 'ropeimpl.h',
  228. 'set.h',
  229. 'slist',
  230. 'slist.h',
  231. 'stack.h',
  232. 'stdiostream.h',
  233. 'stl_alloc.h',
  234. 'stl_relops.h',
  235. 'streambuf.h',
  236. 'stream.h',
  237. 'strfile.h',
  238. 'strstream.h',
  239. 'tempbuf.h',
  240. 'tree.h',
  241. 'type_traits.h',
  242. 'vector.h',
  243. # 17.6.1.2 C++ library headers
  244. 'algorithm',
  245. 'array',
  246. 'atomic',
  247. 'bitset',
  248. 'chrono',
  249. 'codecvt',
  250. 'complex',
  251. 'condition_variable',
  252. 'deque',
  253. 'exception',
  254. 'forward_list',
  255. 'fstream',
  256. 'functional',
  257. 'future',
  258. 'initializer_list',
  259. 'iomanip',
  260. 'ios',
  261. 'iosfwd',
  262. 'iostream',
  263. 'istream',
  264. 'iterator',
  265. 'limits',
  266. 'list',
  267. 'locale',
  268. 'map',
  269. 'memory',
  270. 'mutex',
  271. 'new',
  272. 'numeric',
  273. 'ostream',
  274. 'queue',
  275. 'random',
  276. 'ratio',
  277. 'regex',
  278. 'set',
  279. 'sstream',
  280. 'stack',
  281. 'stdexcept',
  282. 'streambuf',
  283. 'string',
  284. 'strstream',
  285. 'system_error',
  286. 'thread',
  287. 'tuple',
  288. 'typeindex',
  289. 'typeinfo',
  290. 'type_traits',
  291. 'unordered_map',
  292. 'unordered_set',
  293. 'utility',
  294. 'valarray',
  295. 'vector',
  296. # 17.6.1.2 C++ headers for C library facilities
  297. 'cassert',
  298. 'ccomplex',
  299. 'cctype',
  300. 'cerrno',
  301. 'cfenv',
  302. 'cfloat',
  303. 'cinttypes',
  304. 'ciso646',
  305. 'climits',
  306. 'clocale',
  307. 'cmath',
  308. 'csetjmp',
  309. 'csignal',
  310. 'cstdalign',
  311. 'cstdarg',
  312. 'cstdbool',
  313. 'cstddef',
  314. 'cstdint',
  315. 'cstdio',
  316. 'cstdlib',
  317. 'cstring',
  318. 'ctgmath',
  319. 'ctime',
  320. 'cuchar',
  321. 'cwchar',
  322. 'cwctype',
  323. ])
  324. # Assertion macros. These are defined in base/logging.h and
  325. # testing/base/gunit.h. Note that the _M versions need to come first
  326. # for substring matching to work.
  327. _CHECK_MACROS = [
  328. 'DCHECK', 'CHECK',
  329. 'EXPECT_TRUE_M', 'EXPECT_TRUE',
  330. 'ASSERT_TRUE_M', 'ASSERT_TRUE',
  331. 'EXPECT_FALSE_M', 'EXPECT_FALSE',
  332. 'ASSERT_FALSE_M', 'ASSERT_FALSE',
  333. ]
  334. # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
  335. _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
  336. for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
  337. ('>=', 'GE'), ('>', 'GT'),
  338. ('<=', 'LE'), ('<', 'LT')]:
  339. _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
  340. _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
  341. _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
  342. _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
  343. _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement
  344. _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement
  345. for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
  346. ('>=', 'LT'), ('>', 'LE'),
  347. ('<=', 'GT'), ('<', 'GE')]:
  348. _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
  349. _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
  350. _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement
  351. _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement
  352. # Alternative tokens and their replacements. For full list, see section 2.5
  353. # Alternative tokens [lex.digraph] in the C++ standard.
  354. #
  355. # Digraphs (such as '%:') are not included here since it's a mess to
  356. # match those on a word boundary.
  357. _ALT_TOKEN_REPLACEMENT = {
  358. 'and': '&&',
  359. 'bitor': '|',
  360. 'or': '||',
  361. 'xor': '^',
  362. 'compl': '~',
  363. 'bitand': '&',
  364. 'and_eq': '&=',
  365. 'or_eq': '|=',
  366. 'xor_eq': '^=',
  367. 'not': '!',
  368. 'not_eq': '!='
  369. }
  370. # Compile regular expression that matches all the above keywords. The "[ =()]"
  371. # bit is meant to avoid matching these keywords outside of boolean expressions.
  372. #
  373. # False positives include C-style multi-line comments and multi-line strings
  374. # but those have always been troublesome for cpplint.
  375. _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
  376. r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
  377. # These constants define types of headers for use with
  378. # _IncludeState.CheckNextIncludeOrder().
  379. _C_SYS_HEADER = 1
  380. _CPP_SYS_HEADER = 2
  381. _LIKELY_MY_HEADER = 3
  382. _POSSIBLE_MY_HEADER = 4
  383. _OTHER_HEADER = 5
  384. # These constants define the current inline assembly state
  385. _NO_ASM = 0 # Outside of inline assembly block
  386. _INSIDE_ASM = 1 # Inside inline assembly block
  387. _END_ASM = 2 # Last line of inline assembly block
  388. _BLOCK_ASM = 3 # The whole block is an inline assembly block
  389. # Match start of assembly blocks
  390. _MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
  391. r'(?:\s+(volatile|__volatile__))?'
  392. r'\s*[{(]')
  393. _regexp_compile_cache = {}
  394. # Finds occurrences of NOLINT or NOLINT(...).
  395. _RE_SUPPRESSION = re.compile(r'\bNOLINT\b(\([^)]*\))?')
  396. # {str, set(int)}: a map from error categories to sets of linenumbers
  397. # on which those errors are expected and should be suppressed.
  398. _error_suppressions = {}
  399. # The root directory used for deriving header guard CPP variable.
  400. # This is set by --root flag.
  401. _root = None
  402. # The allowed line length of files.
  403. # This is set by --linelength flag.
  404. _line_length = 80
  405. # The allowed extensions for file names
  406. # This is set by --extensions flag.
  407. _valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])
  408. def ParseNolintSuppressions(filename, raw_line, linenum, error):
  409. """Updates the global list of error-suppressions.
  410. Parses any NOLINT comments on the current line, updating the global
  411. error_suppressions store. Reports an error if the NOLINT comment
  412. was malformed.
  413. Args:
  414. filename: str, the name of the input file.
  415. raw_line: str, the line of input text, with comments.
  416. linenum: int, the number of the current line.
  417. error: function, an error handler.
  418. """
  419. # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*).
  420. matched = _RE_SUPPRESSION.search(raw_line)
  421. if matched:
  422. category = matched.group(1)
  423. if category in (None, '(*)'): # => "suppress all"
  424. _error_suppressions.setdefault(None, set()).add(linenum)
  425. else:
  426. if category.startswith('(') and category.endswith(')'):
  427. category = category[1:-1]
  428. if category in _ERROR_CATEGORIES:
  429. _error_suppressions.setdefault(category, set()).add(linenum)
  430. else:
  431. error(filename, linenum, 'readability/nolint', 5,
  432. 'Unknown NOLINT error category: %s' % category)
  433. def ResetNolintSuppressions():
  434. "Resets the set of NOLINT suppressions to empty."
  435. _error_suppressions.clear()
  436. def IsErrorSuppressedByNolint(category, linenum):
  437. """Returns true if the specified error category is suppressed on this line.
  438. Consults the global error_suppressions map populated by
  439. ParseNolintSuppressions/ResetNolintSuppressions.
  440. Args:
  441. category: str, the category of the error.
  442. linenum: int, the current line number.
  443. Returns:
  444. bool, True iff the error should be suppressed due to a NOLINT comment.
  445. """
  446. return (linenum in _error_suppressions.get(category, set()) or
  447. linenum in _error_suppressions.get(None, set()))
  448. def Match(pattern, s):
  449. """Matches the string with the pattern, caching the compiled regexp."""
  450. # The regexp compilation caching is inlined in both Match and Search for
  451. # performance reasons; factoring it out into a separate function turns out
  452. # to be noticeably expensive.
  453. if pattern not in _regexp_compile_cache:
  454. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  455. return _regexp_compile_cache[pattern].match(s)
  456. def ReplaceAll(pattern, rep, s):
  457. """Replaces instances of pattern in a string with a replacement.
  458. The compiled regex is kept in a cache shared by Match and Search.
  459. Args:
  460. pattern: regex pattern
  461. rep: replacement text
  462. s: search string
  463. Returns:
  464. string with replacements made (or original string if no replacements)
  465. """
  466. if pattern not in _regexp_compile_cache:
  467. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  468. return _regexp_compile_cache[pattern].sub(rep, s)
  469. def Search(pattern, s):
  470. """Searches the string for the pattern, caching the compiled regexp."""
  471. if pattern not in _regexp_compile_cache:
  472. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  473. return _regexp_compile_cache[pattern].search(s)
  474. class _IncludeState(dict):
  475. """Tracks line numbers for includes, and the order in which includes appear.
  476. As a dict, an _IncludeState object serves as a mapping between include
  477. filename and line number on which that file was included.
  478. Call CheckNextIncludeOrder() once for each header in the file, passing
  479. in the type constants defined above. Calls in an illegal order will
  480. raise an _IncludeError with an appropriate error message.
  481. """
  482. # self._section will move monotonically through this set. If it ever
  483. # needs to move backwards, CheckNextIncludeOrder will raise an error.
  484. _INITIAL_SECTION = 0
  485. _MY_H_SECTION = 1
  486. _C_SECTION = 2
  487. _CPP_SECTION = 3
  488. _OTHER_H_SECTION = 4
  489. _TYPE_NAMES = {
  490. _C_SYS_HEADER: 'C system header',
  491. _CPP_SYS_HEADER: 'C++ system header',
  492. _LIKELY_MY_HEADER: 'header this file implements',
  493. _POSSIBLE_MY_HEADER: 'header this file may implement',
  494. _OTHER_HEADER: 'other header',
  495. }
  496. _SECTION_NAMES = {
  497. _INITIAL_SECTION: "... nothing. (This can't be an error.)",
  498. _MY_H_SECTION: 'a header this file implements',
  499. _C_SECTION: 'C system header',
  500. _CPP_SECTION: 'C++ system header',
  501. _OTHER_H_SECTION: 'other header',
  502. }
  503. def __init__(self):
  504. dict.__init__(self)
  505. self.ResetSection()
  506. def ResetSection(self):
  507. # The name of the current section.
  508. self._section = self._INITIAL_SECTION
  509. # The path of last found header.
  510. self._last_header = ''
  511. def SetLastHeader(self, header_path):
  512. self._last_header = header_path
  513. def CanonicalizeAlphabeticalOrder(self, header_path):
  514. """Returns a path canonicalized for alphabetical comparison.
  515. - replaces "-" with "_" so they both cmp the same.
  516. - removes '-inl' since we don't require them to be after the main header.
  517. - lowercase everything, just in case.
  518. Args:
  519. header_path: Path to be canonicalized.
  520. Returns:
  521. Canonicalized path.
  522. """
  523. return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
  524. def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
  525. """Check if a header is in alphabetical order with the previous header.
  526. Args:
  527. clean_lines: A CleansedLines instance containing the file.
  528. linenum: The number of the line to check.
  529. header_path: Canonicalized header to be checked.
  530. Returns:
  531. Returns true if the header is in alphabetical order.
  532. """
  533. # If previous section is different from current section, _last_header will
  534. # be reset to empty string, so it's always less than current header.
  535. #
  536. # If previous line was a blank line, assume that the headers are
  537. # intentionally sorted the way they are.
  538. if (self._last_header > header_path and
  539. not Match(r'^\s*$', clean_lines.elided[linenum - 1])):
  540. return False
  541. return True
  542. def CheckNextIncludeOrder(self, header_type):
  543. """Returns a non-empty error message if the next header is out of order.
  544. This function also updates the internal state to be ready to check
  545. the next include.
  546. Args:
  547. header_type: One of the _XXX_HEADER constants defined above.
  548. Returns:
  549. The empty string if the header is in the right order, or an
  550. error message describing what's wrong.
  551. """
  552. error_message = ('Found %s after %s' %
  553. (self._TYPE_NAMES[header_type],
  554. self._SECTION_NAMES[self._section]))
  555. last_section = self._section
  556. if header_type == _C_SYS_HEADER:
  557. if self._section <= self._C_SECTION:
  558. self._section = self._C_SECTION
  559. else:
  560. self._last_header = ''
  561. return error_message
  562. elif header_type == _CPP_SYS_HEADER:
  563. if self._section <= self._CPP_SECTION:
  564. self._section = self._CPP_SECTION
  565. else:
  566. self._last_header = ''
  567. return error_message
  568. elif header_type == _LIKELY_MY_HEADER:
  569. if self._section <= self._MY_H_SECTION:
  570. self._section = self._MY_H_SECTION
  571. else:
  572. self._section = self._OTHER_H_SECTION
  573. elif header_type == _POSSIBLE_MY_HEADER:
  574. if self._section <= self._MY_H_SECTION:
  575. self._section = self._MY_H_SECTION
  576. else:
  577. # This will always be the fallback because we're not sure
  578. # enough that the header is associated with this file.
  579. self._section = self._OTHER_H_SECTION
  580. else:
  581. assert header_type == _OTHER_HEADER
  582. self._section = self._OTHER_H_SECTION
  583. if last_section != self._section:
  584. self._last_header = ''
  585. return ''
  586. class _CppLintState(object):
  587. """Maintains module-wide state.."""
  588. def __init__(self):
  589. self.verbose_level = 1 # global setting.
  590. self.error_count = 0 # global count of reported errors
  591. # filters to apply when emitting error messages
  592. self.filters = _DEFAULT_FILTERS[:]
  593. self.counting = 'total' # In what way are we counting errors?
  594. self.errors_by_category = {} # string to int dict storing error counts
  595. # output format:
  596. # "emacs" - format that emacs can parse (default)
  597. # "vs7" - format that Microsoft Visual Studio 7 can parse
  598. self.output_format = 'emacs'
  599. def SetOutputFormat(self, output_format):
  600. """Sets the output format for errors."""
  601. self.output_format = output_format
  602. def SetVerboseLevel(self, level):
  603. """Sets the module's verbosity, and returns the previous setting."""
  604. last_verbose_level = self.verbose_level
  605. self.verbose_level = level
  606. return last_verbose_level
  607. def SetCountingStyle(self, counting_style):
  608. """Sets the module's counting options."""
  609. self.counting = counting_style
  610. def SetFilters(self, filters):
  611. """Sets the error-message filters.
  612. These filters are applied when deciding whether to emit a given
  613. error message.
  614. Args:
  615. filters: A string of comma-separated filters (eg "+whitespace/indent").
  616. Each filter should start with + or -; else we die.
  617. Raises:
  618. ValueError: The comma-separated filters did not all start with '+' or '-'.
  619. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
  620. """
  621. # Default filters always have less priority than the flag ones.
  622. self.filters = _DEFAULT_FILTERS[:]
  623. for filt in filters.split(','):
  624. clean_filt = filt.strip()
  625. if clean_filt:
  626. self.filters.append(clean_filt)
  627. for filt in self.filters:
  628. if not (filt.startswith('+') or filt.startswith('-')):
  629. raise ValueError('Every filter in --filters must start with + or -'
  630. ' (%s does not)' % filt)
  631. def ResetErrorCounts(self):
  632. """Sets the module's error statistic back to zero."""
  633. self.error_count = 0
  634. self.errors_by_category = {}
  635. def IncrementErrorCount(self, category):
  636. """Bumps the module's error statistic."""
  637. self.error_count += 1
  638. if self.counting in ('toplevel', 'detailed'):
  639. if self.counting != 'detailed':
  640. category = category.split('/')[0]
  641. if category not in self.errors_by_category:
  642. self.errors_by_category[category] = 0
  643. self.errors_by_category[category] += 1
  644. def PrintErrorCounts(self):
  645. """Print a summary of errors by category, and the total."""
  646. for category, count in self.errors_by_category.iteritems():
  647. sys.stderr.write('Category \'%s\' errors found: %d\n' %
  648. (category, count))
  649. sys.stderr.write('Total errors found: %d\n' % self.error_count)
  650. _cpplint_state = _CppLintState()
  651. def _OutputFormat():
  652. """Gets the module's output format."""
  653. return _cpplint_state.output_format
  654. def _SetOutputFormat(output_format):
  655. """Sets the module's output format."""
  656. _cpplint_state.SetOutputFormat(output_format)
  657. def _VerboseLevel():
  658. """Returns the module's verbosity setting."""
  659. return _cpplint_state.verbose_level
  660. def _SetVerboseLevel(level):
  661. """Sets the module's verbosity, and returns the previous setting."""
  662. return _cpplint_state.SetVerboseLevel(level)
  663. def _SetCountingStyle(level):
  664. """Sets the module's counting options."""
  665. _cpplint_state.SetCountingStyle(level)
  666. def _Filters():
  667. """Returns the module's list of output filters, as a list."""
  668. return _cpplint_state.filters
  669. def _SetFilters(filters):
  670. """Sets the module's error-message filters.
  671. These filters are applied when deciding whether to emit a given
  672. error message.
  673. Args:
  674. filters: A string of comma-separated filters (eg "whitespace/indent").
  675. Each filter should start with + or -; else we die.
  676. """
  677. _cpplint_state.SetFilters(filters)
  678. class _FunctionState(object):
  679. """Tracks current function name and the number of lines in its body."""
  680. _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
  681. _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
  682. def __init__(self):
  683. self.in_a_function = False
  684. self.lines_in_function = 0
  685. self.current_function = ''
  686. def Begin(self, function_name):
  687. """Start analyzing function body.
  688. Args:
  689. function_name: The name of the function being tracked.
  690. """
  691. self.in_a_function = True
  692. self.lines_in_function = 0
  693. self.current_function = function_name
  694. def Count(self):
  695. """Count line in current function body."""
  696. if self.in_a_function:
  697. self.lines_in_function += 1
  698. def Check(self, error, filename, linenum):
  699. """Report if too many lines in function body.
  700. Args:
  701. error: The function to call with any errors found.
  702. filename: The name of the current file.
  703. linenum: The number of the line to check.
  704. """
  705. if Match(r'T(EST|est)', self.current_function):
  706. base_trigger = self._TEST_TRIGGER
  707. else:
  708. base_trigger = self._NORMAL_TRIGGER
  709. trigger = base_trigger * 2**_VerboseLevel()
  710. if self.lines_in_function > trigger:
  711. error_level = int(math.log(self.lines_in_function / base_trigger, 2))
  712. # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
  713. if error_level > 5:
  714. error_level = 5
  715. error(filename, linenum, 'readability/fn_size', error_level,
  716. 'Small and focused functions are preferred:'
  717. ' %s has %d non-comment lines'
  718. ' (error triggered by exceeding %d lines).' % (
  719. self.current_function, self.lines_in_function, trigger))
  720. def End(self):
  721. """Stop analyzing function body."""
  722. self.in_a_function = False
  723. class _IncludeError(Exception):
  724. """Indicates a problem with the include order in a file."""
  725. pass
  726. class FileInfo:
  727. """Provides utility functions for filenames.
  728. FileInfo provides easy access to the components of a file's path
  729. relative to the project root.
  730. """
  731. def __init__(self, filename):
  732. self._filename = filename
  733. def FullName(self):
  734. """Make Windows paths like Unix."""
  735. return os.path.abspath(self._filename).replace('\\', '/')
  736. def RepositoryName(self):
  737. """FullName after removing the local path to the repository.
  738. If we have a real absolute path name here we can try to do something smart:
  739. detecting the root of the checkout and truncating /path/to/checkout from
  740. the name so that we get header guards that don't include things like
  741. "C:\Documents and Settings\..." or "/home/username/..." in them and thus
  742. people on different computers who have checked the source out to different
  743. locations won't see bogus errors.
  744. """
  745. fullname = self.FullName()
  746. if os.path.exists(fullname):
  747. project_dir = os.path.dirname(fullname)
  748. if os.path.exists(os.path.join(project_dir, ".svn")):
  749. # If there's a .svn file in the current directory, we recursively look
  750. # up the directory tree for the top of the SVN checkout
  751. root_dir = project_dir
  752. one_up_dir = os.path.dirname(root_dir)
  753. while os.path.exists(os.path.join(one_up_dir, ".svn")):
  754. root_dir = os.path.dirname(root_dir)
  755. one_up_dir = os.path.dirname(one_up_dir)
  756. prefix = os.path.commonprefix([root_dir, project_dir])
  757. return fullname[len(prefix) + 1:]
  758. # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
  759. # searching up from the current path.
  760. root_dir = os.path.dirname(fullname)
  761. while (root_dir != os.path.dirname(root_dir) and
  762. not os.path.exists(os.path.join(root_dir, ".git")) and
  763. not os.path.exists(os.path.join(root_dir, ".hg")) and
  764. not os.path.exists(os.path.join(root_dir, ".svn"))):
  765. root_dir = os.path.dirname(root_dir)
  766. if (os.path.exists(os.path.join(root_dir, ".git")) or
  767. os.path.exists(os.path.join(root_dir, ".hg")) or
  768. os.path.exists(os.path.join(root_dir, ".svn"))):
  769. prefix = os.path.commonprefix([root_dir, project_dir])
  770. return fullname[len(prefix) + 1:]
  771. # Don't know what to do; header guard warnings may be wrong...
  772. return fullname
  773. def Split(self):
  774. """Splits the file into the directory, basename, and extension.
  775. For 'chrome/browser/browser.cc', Split() would
  776. return ('chrome/browser', 'browser', '.cc')
  777. Returns:
  778. A tuple of (directory, basename, extension).
  779. """
  780. googlename = self.RepositoryName()
  781. project, rest = os.path.split(googlename)
  782. return (project,) + os.path.splitext(rest)
  783. def BaseName(self):
  784. """File base name - text after the final slash, before the final period."""
  785. return self.Split()[1]
  786. def Extension(self):
  787. """File extension - text following the final period."""
  788. return self.Split()[2]
  789. def NoExtension(self):
  790. """File has no source file extension."""
  791. return '/'.join(self.Split()[0:2])
  792. def IsSource(self):
  793. """File has a source file extension."""
  794. return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
  795. def _ShouldPrintError(category, confidence, linenum):
  796. """If confidence >= verbose, category passes filter and is not suppressed."""
  797. # There are three ways we might decide not to print an error message:
  798. # a "NOLINT(category)" comment appears in the source,
  799. # the verbosity level isn't high enough, or the filters filter it out.
  800. if IsErrorSuppressedByNolint(category, linenum):
  801. return False
  802. if confidence < _cpplint_state.verbose_level:
  803. return False
  804. is_filtered = False
  805. for one_filter in _Filters():
  806. if one_filter.startswith('-'):
  807. if category.startswith(one_filter[1:]):
  808. is_filtered = True
  809. elif one_filter.startswith('+'):
  810. if category.startswith(one_filter[1:]):
  811. is_filtered = False
  812. else:
  813. assert False # should have been checked for in SetFilter.
  814. if is_filtered:
  815. return False
  816. return True
  817. def Error(filename, linenum, category, confidence, message):
  818. """Logs the fact we've found a lint error.
  819. We log where the error was found, and also our confidence in the error,
  820. that is, how certain we are this is a legitimate style regression, and
  821. not a misidentification or a use that's sometimes justified.
  822. False positives can be suppressed by the use of
  823. "cpplint(category)" comments on the offending line. These are
  824. parsed into _error_suppressions.
  825. Args:
  826. filename: The name of the file containing the error.
  827. linenum: The number of the line containing the error.
  828. category: A string used to describe the "category" this bug
  829. falls under: "whitespace", say, or "runtime". Categories
  830. may have a hierarchy separated by slashes: "whitespace/indent".
  831. confidence: A number from 1-5 representing a confidence score for
  832. the error, with 5 meaning that we are certain of the problem,
  833. and 1 meaning that it could be a legitimate construct.
  834. message: The error message.
  835. """
  836. if _ShouldPrintError(category, confidence, linenum):
  837. _cpplint_state.IncrementErrorCount(category)
  838. if _cpplint_state.output_format == 'vs7':
  839. sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
  840. filename, linenum, message, category, confidence))
  841. elif _cpplint_state.output_format == 'eclipse':
  842. sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
  843. filename, linenum, message, category, confidence))
  844. else:
  845. sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
  846. filename, linenum, message, category, confidence))
  847. # Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
  848. _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
  849. r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
  850. # Matches strings. Escape codes should already be removed by ESCAPES.
  851. _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"')
  852. # Matches characters. Escape codes should already be removed by ESCAPES.
  853. _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'")
  854. # Matches multi-line C++ comments.
  855. # This RE is a little bit more complicated than one might expect, because we
  856. # have to take care of space removals tools so we can handle comments inside
  857. # statements better.
  858. # The current rule is: We only clear spaces from both sides when we're at the
  859. # end of the line. Otherwise, we try to remove spaces from the right side,
  860. # if this doesn't work we try on left side but only if there's a non-character
  861. # on the right.
  862. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
  863. r"""(\s*/\*.*\*/\s*$|
  864. /\*.*\*/\s+|
  865. \s+/\*.*\*/(?=\W)|
  866. /\*.*\*/)""", re.VERBOSE)
  867. def IsCppString(line):
  868. """Does line terminate so, that the next symbol is in string constant.
  869. This function does not consider single-line nor multi-line comments.
  870. Args:
  871. line: is a partial line of code starting from the 0..n.
  872. Returns:
  873. True, if next character appended to 'line' is inside a
  874. string constant.
  875. """
  876. line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
  877. return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
  878. def CleanseRawStrings(raw_lines):
  879. """Removes C++11 raw strings from lines.
  880. Before:
  881. static const char kData[] = R"(
  882. multi-line string
  883. )";
  884. After:
  885. static const char kData[] = ""
  886. (replaced by blank line)
  887. "";
  888. Args:
  889. raw_lines: list of raw lines.
  890. Returns:
  891. list of lines with C++11 raw strings replaced by empty strings.
  892. """
  893. delimiter = None
  894. lines_without_raw_strings = []
  895. for line in raw_lines:
  896. if delimiter:
  897. # Inside a raw string, look for the end
  898. end = line.find(delimiter)
  899. if end >= 0:
  900. # Found the end of the string, match leading space for this
  901. # line and resume copying the original lines, and also insert
  902. # a "" on the last line.
  903. leading_space = Match(r'^(\s*)\S', line)
  904. line = leading_space.group(1) + '""' + line[end + len(delimiter):]
  905. delimiter = None
  906. else:
  907. # Haven't found the end yet, append a blank line.
  908. line = ''
  909. else:
  910. # Look for beginning of a raw string.
  911. # See 2.14.15 [lex.string] for syntax.
  912. matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
  913. if matched:
  914. delimiter = ')' + matched.group(2) + '"'
  915. end = matched.group(3).find(delimiter)
  916. if end >= 0:
  917. # Raw string ended on same line
  918. line = (matched.group(1) + '""' +
  919. matched.group(3)[end + len(delimiter):])
  920. delimiter = None
  921. else:
  922. # Start of a multi-line raw string
  923. line = matched.group(1) + '""'
  924. lines_without_raw_strings.append(line)
  925. # TODO(unknown): if delimiter is not None here, we might want to
  926. # emit a warning for unterminated string.
  927. return lines_without_raw_strings
  928. def FindNextMultiLineCommentStart(lines, lineix):
  929. """Find the beginning marker for a multiline comment."""
  930. while lineix < len(lines):
  931. if lines[lineix].strip().startswith('/*'):
  932. # Only return this marker if the comment goes beyond this line
  933. if lines[lineix].strip().find('*/', 2) < 0:
  934. return lineix
  935. lineix += 1
  936. return len(lines)
  937. def FindNextMultiLineCommentEnd(lines, lineix):
  938. """We are inside a comment, find the end marker."""
  939. while lineix < len(lines):
  940. if lines[lineix].strip().endswith('*/'):
  941. return lineix
  942. lineix += 1
  943. return len(lines)
  944. def RemoveMultiLineCommentsFromRange(lines, begin, end):
  945. """Clears a range of lines for multi-line comments."""
  946. # Having // dummy comments makes the lines non-empty, so we will not get
  947. # unnecessary blank line warnings later in the code.
  948. for i in range(begin, end):
  949. lines[i] = '// dummy'
  950. def RemoveMultiLineComments(filename, lines, error):
  951. """Removes multiline (c-style) comments from lines."""
  952. lineix = 0
  953. while lineix < len(lines):
  954. lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
  955. if lineix_begin >= len(lines):
  956. return
  957. lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
  958. if lineix_end >= len(lines):
  959. error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
  960. 'Could not find end of multi-line comment')
  961. return
  962. RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
  963. lineix = lineix_end + 1
  964. def CleanseComments(line):
  965. """Removes //-comments and single-line C-style /* */ comments.
  966. Args:
  967. line: A line of C++ source.
  968. Returns:
  969. The line with single-line comments removed.
  970. """
  971. commentpos = line.find('//')
  972. if commentpos != -1 and not IsCppString(line[:commentpos]):
  973. line = line[:commentpos].rstrip()
  974. # get rid of /* ... */
  975. return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
  976. class CleansedLines(object):
  977. """Holds 3 copies of all lines with different preprocessing applied to them.
  978. 1) elided member contains lines without strings and comments,
  979. 2) lines member contains lines without comments, and
  980. 3) raw_lines member contains all the lines without processing.
  981. All these three members are of <type 'list'>, and of the same length.
  982. """
  983. def __init__(self, lines):
  984. self.elided = []
  985. self.lines = []
  986. self.raw_lines = lines
  987. self.num_lines = len(lines)
  988. self.lines_without_raw_strings = CleanseRawStrings(lines)
  989. for linenum in range(len(self.lines_without_raw_strings)):
  990. self.lines.append(CleanseComments(
  991. self.lines_without_raw_strings[linenum]))
  992. elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
  993. self.elided.append(CleanseComments(elided))
  994. def NumLines(self):
  995. """Returns the number of lines represented."""
  996. return self.num_lines
  997. @staticmethod
  998. def _CollapseStrings(elided):
  999. """Collapses strings and chars on a line to simple "" or '' blocks.
  1000. We nix strings first so we're not fooled by text like '"http://"'
  1001. Args:
  1002. elided: The line being processed.
  1003. Returns:
  1004. The line with collapsed strings.
  1005. """
  1006. if not _RE_PATTERN_INCLUDE.match(elided):
  1007. # Remove escaped characters first to make quote/single quote collapsing
  1008. # basic. Things that look like escaped characters shouldn't occur
  1009. # outside of strings and chars.
  1010. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
  1011. elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
  1012. elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
  1013. return elided
  1014. def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar):
  1015. """Find the position just after the matching endchar.
  1016. Args:
  1017. line: a CleansedLines line.
  1018. startpos: start searching at this position.
  1019. depth: nesting level at startpos.
  1020. startchar: expression opening character.
  1021. endchar: expression closing character.
  1022. Returns:
  1023. On finding matching endchar: (index just after matching endchar, 0)
  1024. Otherwise: (-1, new depth at end of this line)
  1025. """
  1026. for i in xrange(startpos, len(line)):
  1027. if line[i] == startchar:
  1028. depth += 1
  1029. elif line[i] == endchar:
  1030. depth -= 1
  1031. if depth == 0:
  1032. return (i + 1, 0)
  1033. return (-1, depth)
  1034. def CloseExpression(clean_lines, linenum, pos):
  1035. """If input points to ( or { or [ or <, finds the position that closes it.
  1036. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
  1037. linenum/pos that correspond to the closing of the expression.
  1038. Args:
  1039. clean_lines: A CleansedLines instance containing the file.
  1040. linenum: The number of the line to check.
  1041. pos: A position on the line.
  1042. Returns:
  1043. A tuple (line, linenum, pos) pointer *past* the closing brace, or
  1044. (line, len(lines), -1) if we never find a close. Note we ignore
  1045. strings and comments when matching; and the line we return is the
  1046. 'cleansed' line at linenum.
  1047. """
  1048. line = clean_lines.elided[linenum]
  1049. startchar = line[pos]
  1050. if startchar not in '({[<':
  1051. return (line, clean_lines.NumLines(), -1)
  1052. if startchar == '(': endchar = ')'
  1053. if startchar == '[': endchar = ']'
  1054. if startchar == '{': endchar = '}'
  1055. if startchar == '<': endchar = '>'
  1056. # Check first line
  1057. (end_pos, num_open) = FindEndOfExpressionInLine(
  1058. line, pos, 0, startchar, endchar)
  1059. if end_pos > -1:
  1060. return (line, linenum, end_pos)
  1061. # Continue scanning forward
  1062. while linenum < clean_lines.NumLines() - 1:
  1063. linenum += 1
  1064. line = clean_lines.elided[linenum]
  1065. (end_pos, num_open) = FindEndOfExpressionInLine(
  1066. line, 0, num_open, startchar, endchar)
  1067. if end_pos > -1:
  1068. return (line, linenum, end_pos)
  1069. # Did not find endchar before end of file, give up
  1070. return (line, clean_lines.NumLines(), -1)
  1071. def FindStartOfExpressionInLine(line, endpos, depth, startchar, endchar):
  1072. """Find position at the matching startchar.
  1073. This is almost the reverse of FindEndOfExpressionInLine, but note
  1074. that the input position and returned position differs by 1.
  1075. Args:
  1076. line: a CleansedLines line.
  1077. endpos: start searching at this position.
  1078. depth: nesting level at endpos.
  1079. startchar: expression opening character.
  1080. endchar: expression closing character.
  1081. Returns:
  1082. On finding matching startchar: (index at matching startchar, 0)
  1083. Otherwise: (-1, new depth at beginning of this line)
  1084. """
  1085. for i in xrange(endpos, -1, -1):
  1086. if line[i] == endchar:
  1087. depth += 1
  1088. elif line[i] == startchar:
  1089. depth -= 1
  1090. if depth == 0:
  1091. return (i, 0)
  1092. return (-1, depth)
  1093. def ReverseCloseExpression(clean_lines, linenum, pos):
  1094. """If input points to ) or } or ] or >, finds the position that opens it.
  1095. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
  1096. linenum/pos that correspond to the opening of the expression.
  1097. Args:
  1098. clean_lines: A CleansedLines instance containing the file.
  1099. linenum: The number of the line to check.
  1100. pos: A position on the line.
  1101. Returns:
  1102. A tuple (line, linenum, pos) pointer *at* the opening brace, or
  1103. (line, 0, -1) if we never find the matching opening brace. Note
  1104. we ignore strings and comments when matching; and the line we
  1105. return is the 'cleansed' line at linenum.
  1106. """
  1107. line = clean_lines.elided[linenum]
  1108. endchar = line[pos]
  1109. if endchar not in ')}]>':
  1110. return (line, 0, -1)
  1111. if endchar == ')': startchar = '('
  1112. if endchar == ']': startchar = '['
  1113. if endchar == '}': startchar = '{'
  1114. if endchar == '>': startchar = '<'
  1115. # Check last line
  1116. (start_pos, num_open) = FindStartOfExpressionInLine(
  1117. line, pos, 0, startchar, endchar)
  1118. if start_pos > -1:
  1119. return (line, linenum, start_pos)
  1120. # Continue scanning backward
  1121. while linenum > 0:
  1122. linenum -= 1
  1123. line = clean_lines.elided[linenum]
  1124. (start_pos, num_open) = FindStartOfExpressionInLine(
  1125. line, len(line) - 1, num_open, startchar, endchar)
  1126. if start_pos > -1:
  1127. return (line, linenum, start_pos)
  1128. # Did not find startchar before beginning of file, give up
  1129. return (line, 0, -1)
  1130. def CheckForCopyright(filename, lines, error):
  1131. """Logs an error if no Copyright message appears at the top of the file."""
  1132. # We'll say it should occur by line 10. Don't forget there's a
  1133. # dummy line at the front.
  1134. for line in xrange(1, min(len(lines), 11)):
  1135. if re.search(r'Copyright', lines[line], re.I): break
  1136. else: # means no copyright line was found
  1137. error(filename, 0, 'legal/copyright', 5,
  1138. 'No copyright message found. '
  1139. 'You should have a line: "Copyright [year] <Copyright Owner>"')
  1140. def GetHeaderGuardCPPVariable(filename):
  1141. """Returns the CPP variable that should be used as a header guard.
  1142. Args:
  1143. filename: The name of a C++ header file.
  1144. Returns:
  1145. The CPP variable that should be used as a header guard in the
  1146. named file.
  1147. """
  1148. # Restores original filename in case that cpplint is invoked from Emacs's
  1149. # flymake.
  1150. filename = re.sub(r'_flymake\.h$', '.h', filename)
  1151. filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
  1152. fileinfo = FileInfo(filename)
  1153. file_path_from_root = fileinfo.RepositoryName()
  1154. if _root:
  1155. file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
  1156. return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
  1157. def CheckForHeaderGuard(filename, lines, error):
  1158. """Checks that the file contains a header guard.
  1159. Logs an error if no #ifndef header guard is present. For other
  1160. headers, checks that the full pathname is used.
  1161. Args:
  1162. filename: The name of the C++ header file.
  1163. lines: An array of strings, each representing a line of the file.
  1164. error: The function to call with any errors found.
  1165. """
  1166. cppvar = GetHeaderGuardCPPVariable(filename)
  1167. ifndef = None
  1168. ifndef_linenum = 0
  1169. define = None
  1170. endif = None
  1171. endif_linenum = 0
  1172. for linenum, line in enumerate(lines):
  1173. linesplit = line.split()
  1174. if len(linesplit) >= 2:
  1175. # find the first occurrence of #ifndef and #define, save arg
  1176. if not ifndef and linesplit[0] == '#ifndef':
  1177. # set ifndef to the header guard presented on the #ifndef line.
  1178. ifndef = linesplit[1]
  1179. ifndef_linenum = linenum
  1180. if not define and linesplit[0] == '#define':
  1181. define = linesplit[1]
  1182. # find the last occurrence of #endif, save entire line
  1183. if line.startswith('#endif'):
  1184. endif = line
  1185. endif_linenum = linenum
  1186. if not ifndef:
  1187. error(filename, 0, 'build/header_guard', 5,
  1188. 'No #ifndef header guard found, suggested CPP variable is: %s' %
  1189. cppvar)
  1190. return
  1191. if not define:
  1192. error(filename, 0, 'build/header_guard', 5,
  1193. 'No #define header guard found, suggested CPP variable is: %s' %
  1194. cppvar)
  1195. return
  1196. # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
  1197. # for backward compatibility.
  1198. if ifndef != cppvar:
  1199. error_level = 0
  1200. if ifndef != cppvar + '_':
  1201. error_level = 5
  1202. ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum,
  1203. error)
  1204. error(filename, ifndef_linenum, 'build/header_guard', error_level,
  1205. '#ifndef header guard has wrong style, please use: %s' % cppvar)
  1206. if define != ifndef:
  1207. error(filename, 0, 'build/header_guard', 5,
  1208. '#ifndef and #define don\'t match, suggested CPP variable is: %s' %
  1209. cppvar)
  1210. return
  1211. if endif != ('#endif // %s' % cppvar):
  1212. error_level = 0
  1213. if endif != ('#endif // %s' % (cppvar + '_')):
  1214. error_level = 5
  1215. ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum,
  1216. error)
  1217. error(filename, endif_linenum, 'build/header_guard', error_level,
  1218. '#endif line should be "#endif // %s"' % cppvar)
  1219. def CheckForBadCharacters(filename, lines, error):
  1220. """Logs an error for each line containing bad characters.
  1221. Two kinds of bad characters:
  1222. 1. Unicode replacement characters: These indicate that either the file
  1223. contained invalid UTF-8 (likely) or Unicode replacement characters (which
  1224. it shouldn't). Note that it's possible for this to throw off line
  1225. numbering if the invalid UTF-8 occurred adjacent to a newline.
  1226. 2. NUL bytes. These are problematic for some tools.
  1227. Args:
  1228. filename: The name of the current file.
  1229. lines: An array of strings, each representing a line of the file.
  1230. error: The function to call with any errors found.
  1231. """
  1232. for linenum, line in enumerate(lines):
  1233. if u'\ufffd' in line:
  1234. error(filename, linenum, 'readability/utf8', 5,
  1235. 'Line contains invalid UTF-8 (or Unicode replacement character).')
  1236. if '\0' in line:
  1237. error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
  1238. def CheckForNewlineAtEOF(filename, lines, error):
  1239. """Logs an error if there is no newline char at the end of the file.
  1240. Args:
  1241. filename: The name of the current file.
  1242. lines: An array of strings, each representing a line of the file.
  1243. error: The function to call with any errors found.
  1244. """
  1245. # The array lines() was created by adding two newlines to the
  1246. # original file (go figure), then splitting on \n.
  1247. # To verify that the file ends in \n, we just have to make sure the
  1248. # last-but-two element of lines() exists and is empty.
  1249. if len(lines) < 3 or lines[-2]:
  1250. error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
  1251. 'Could not find a newline character at the end of the file.')
  1252. def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
  1253. """Logs an error if we see /* ... */ or "..." that extend past one line.
  1254. /* ... */ comments are legit inside macros, for one line.
  1255. Otherwise, we prefer // comments, so it's ok to warn about the
  1256. other. Likewise, it's ok for strings to extend across multiple
  1257. lines, as long as a line continuation character (backslash)
  1258. terminates each line. Although not currently prohibited by the C++
  1259. style guide, it's ugly and unnecessary. We don't do well with either
  1260. in this lint program, so we warn about both.
  1261. Args:
  1262. filename: The name of the current file.
  1263. clean_lines: A CleansedLines instance containing the file.
  1264. linenum: The number of the line to check.
  1265. error: The function to call with any errors found.
  1266. """
  1267. line = clean_lines.elided[linenum]
  1268. # Remove all \\ (escaped backslashes) from the line. They are OK, and the
  1269. # second (escaped) slash may trigger later \" detection erroneously.
  1270. line = line.replace('\\\\', '')
  1271. if line.count('/*') > line.count('*/'):
  1272. error(filename, linenum, 'readability/multiline_comment', 5,
  1273. 'Complex multi-line /*...*/-style comment found. '
  1274. 'Lint may give bogus warnings. '
  1275. 'Consider replacing these with //-style comments, '
  1276. 'with #if 0...#endif, '
  1277. 'or with more clearly structured multi-line comments.')
  1278. if (line.count('"') - line.count('\\"')) % 2:
  1279. error(filename, linenum, 'readability/multiline_string', 5,
  1280. 'Multi-line string ("...") found. This lint script doesn\'t '
  1281. 'do well with such strings, and may give bogus warnings. '
  1282. 'Use C++11 raw strings or concatenation instead.')
  1283. threading_list = (
  1284. ('asctime(', 'asctime_r('),
  1285. ('ctime(', 'ctime_r('),
  1286. ('getgrgid(', 'getgrgid_r('),
  1287. ('getgrnam(', 'getgrnam_r('),
  1288. ('getlogin(', 'getlogin_r('),
  1289. ('getpwnam(', 'getpwnam_r('),
  1290. ('getpwuid(', 'getpwuid_r('),
  1291. ('gmtime(', 'gmtime_r('),
  1292. ('localtime(', 'localtime_r('),
  1293. ('rand(', 'rand_r('),
  1294. ('strtok(', 'strtok_r('),
  1295. ('ttyname(', 'ttyname_r('),
  1296. )
  1297. def CheckPosixThreading(filename, clean_lines, linenum, error):
  1298. """Checks for calls to thread-unsafe functions.
  1299. Much code has been originally written without consideration of
  1300. multi-threading. Also, engineers are relying on their old experience;
  1301. they have learned posix before threading extensions were added. These
  1302. tests guide the engineers to use thread-safe functions (when using
  1303. posix directly).
  1304. Args:
  1305. filename: The name of the current file.
  1306. clean_lines: A CleansedLines instance containing the file.
  1307. linenum: The number of the line to check.
  1308. error: The function to call with any errors found.
  1309. """
  1310. line = clean_lines.elided[linenum]
  1311. for single_thread_function, multithread_safe_function in threading_list:
  1312. ix = line.find(single_thread_function)
  1313. # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
  1314. if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
  1315. line[ix - 1] not in ('_', '.', '>'))):
  1316. error(filename, linenum, 'runtime/threadsafe_fn', 2,
  1317. 'Consider using ' + multithread_safe_function +
  1318. '...) instead of ' + single_thread_function +
  1319. '...) for improved thread safety.')
  1320. def CheckVlogArguments(filename, clean_lines, linenum, error):
  1321. """Checks that VLOG() is only used for defining a logging level.
  1322. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
  1323. VLOG(FATAL) are not.
  1324. Args:
  1325. filename: The name of the current file.
  1326. clean_lines: A CleansedLines instance containing the file.
  1327. linenum: The number of the line to check.
  1328. error: The function to call with any errors found.
  1329. """
  1330. line = clean_lines.elided[linenum]
  1331. if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
  1332. error(filename, linenum, 'runtime/vlog', 5,
  1333. 'VLOG() should be used with numeric verbosity level. '
  1334. 'Use LOG() if you want symbolic severity levels.')
  1335. # Matches invalid increment: *count++, which moves pointer instead of
  1336. # incrementing a value.
  1337. _RE_PATTERN_INVALID_INCREMENT = re.compile(
  1338. r'^\s*\*\w+(\+\+|--);')
  1339. def CheckInvalidIncrement(filename, clean_lines, linenum, error):
  1340. """Checks for invalid increment *count++.
  1341. For example following function:
  1342. void increment_counter(int* count) {
  1343. *count++;
  1344. }
  1345. is invalid, because it effectively does count++, moving pointer, and should
  1346. be replaced with ++*count, (*count)++ or *count += 1.
  1347. Args:
  1348. filename: The name of the current file.
  1349. clean_lines: A CleansedLines instance containing the file.
  1350. linenum: The number of the line to check.
  1351. error: The function to call with any errors found.
  1352. """
  1353. line = clean_lines.elided[linenum]
  1354. if _RE_PATTERN_INVALID_INCREMENT.match(line):
  1355. error(filename, linenum, 'runtime/invalid_increment', 5,
  1356. 'Changing pointer instead of value (or unused value of operator*).')
  1357. class _BlockInfo(object):
  1358. """Stores information about a generic block of code."""
  1359. def __init__(self, seen_open_brace):
  1360. self.seen_open_brace = seen_open_brace
  1361. self.open_parentheses = 0
  1362. self.inline_asm = _NO_ASM
  1363. def CheckBegin(self, filename, clean_lines, linenum, error):
  1364. """Run checks that applies to text up to the opening brace.
  1365. This is mostly for checking the text after the class identifier
  1366. and the "{", usually where the base class is specified. For other
  1367. blocks, there isn't much to check, so we always pass.
  1368. Args:
  1369. filename: The name of the current file.
  1370. clean_lines: A CleansedLines instance containing the file.
  1371. linenum: The number of the line to check.
  1372. error: The function to call with any errors found.
  1373. """
  1374. pass
  1375. def CheckEnd(self, filename, clean_lines, linenum, error):
  1376. """Run checks that applies to text after the closing brace.
  1377. This is mostly used for checking end of namespace comments.
  1378. Args:
  1379. filename: The name of the current file.
  1380. clean_lines: A CleansedLines instance containing the file.
  1381. linenum: The number of the line to check.
  1382. error: The function to call with any errors found.
  1383. """
  1384. pass
  1385. class _ClassInfo(_BlockInfo):
  1386. """Stores information about a class."""
  1387. def __init__(self, name, class_or_struct, clean_lines, linenum):
  1388. _BlockInfo.__init__(self, False)
  1389. self.name = name
  1390. self.starting_linenum = linenum
  1391. self.is_derived = False
  1392. if class_or_struct == 'struct':
  1393. self.access = 'public'
  1394. self.is_struct = True
  1395. else:
  1396. self.access = 'private'
  1397. self.is_struct = False
  1398. # Remember initial indentation level for this class. Using raw_lines here
  1399. # instead of elided to account for leading comments.
  1400. initial_indent = Match(r'^( *)\S', clean_lines.raw_lines[linenum])
  1401. if initial_indent:
  1402. self.class_indent = len(initial_indent.group(1))
  1403. else:
  1404. self.class_indent = 0
  1405. # Try to find the end of the class. This will be confused by things like:
  1406. # class A {
  1407. # } *x = { ...
  1408. #
  1409. # But it's still good enough for CheckSectionSpacing.
  1410. self.last_line = 0
  1411. depth = 0
  1412. for i in range(linenum, clean_lines.NumLines()):
  1413. line = clean_lines.elided[i]
  1414. depth += line.count('{') - line.count('}')
  1415. if not depth:
  1416. self.last_line = i
  1417. break
  1418. def CheckBegin(self, filename, clean_lines, linenum, error):
  1419. # Look for a bare ':'
  1420. if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
  1421. self.is_derived = True
  1422. def CheckEnd(self, filename, clean_lines, linenum, error):
  1423. # Check that closing brace is aligned with beginning of the class.
  1424. # Only do this if the closing brace is indented by only whitespaces.
  1425. # This means we will not check single-line class definitions.
  1426. indent = Match(r'^( *)\}', clean_lines.elided[linenum])
  1427. if indent and len(indent.group(1)) != self.class_indent:
  1428. if self.is_struct:
  1429. parent = 'struct ' + self.name
  1430. else:
  1431. parent = 'class ' + self.name
  1432. error(filename, linenum, 'whitespace/indent', 3,
  1433. 'Closing brace should be aligned with beginning of %s' % parent)
  1434. class _NamespaceInfo(_BlockInfo):
  1435. """Stores information about a namespace."""
  1436. def __init__(self, name, linenum):
  1437. _BlockInfo.__init__(self, False)
  1438. self.name = name or ''
  1439. self.starting_linenum = linenum
  1440. def CheckEnd(self, filename, clean_lines, linenum, error):
  1441. """Check end of namespace comments."""
  1442. line = clean_lines.raw_lines[linenum]
  1443. # Check how many lines is enclosed in this namespace. Don't issue
  1444. # warning for missing namespace comments if there aren't enough
  1445. # lines. However, do apply checks if there is already an end of
  1446. # namespace comment and it's incorrect.
  1447. #
  1448. # TODO(unknown): We always want to check end of namespace comments
  1449. # if a namespace is large, but sometimes we also want to apply the
  1450. # check if a short namespace contained nontrivial things (something
  1451. # other than forward declarations). There is currently no logic on
  1452. # deciding what these nontrivial things are, so this check is
  1453. # triggered by namespace size only, which works most of the time.
  1454. if (linenum - self.starting_linenum < 10
  1455. and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)):
  1456. return
  1457. # Look for matching comment at end of namespace.
  1458. #
  1459. # Note that we accept C style "/* */" comments for terminating
  1460. # namespaces, so that code that terminate namespaces inside
  1461. # preprocessor macros can be cpplint clean.
  1462. #
  1463. # We also accept stuff like "// end of namespace <name>." with the
  1464. # period at the end.
  1465. #
  1466. # Besides these, we don't accept anything else, otherwise we might
  1467. # get false negatives when existing comment is a substring of the
  1468. # expected namespace.
  1469. if self.name:
  1470. # Named namespace
  1471. if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) +
  1472. r'[\*/\.\\\s]*$'),
  1473. line):
  1474. error(filename, linenum, 'readability/namespace', 5,
  1475. 'Namespace should be terminated with "// namespace %s"' %
  1476. self.name)
  1477. else:
  1478. # Anonymous namespace
  1479. if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
  1480. error(filename, linenum, 'readability/namespace', 5,
  1481. 'Namespace should be terminated with "// namespace"')
  1482. class _PreprocessorInfo(object):
  1483. """Stores checkpoints of nesting stacks when #if/#else is seen."""
  1484. def __init__(self, stack_before_if):
  1485. # The entire nesting stack before #if
  1486. self.stack_before_if = stack_before_if
  1487. # The entire nesting stack up to #else
  1488. self.stack_before_else = []
  1489. # Whether we have already seen #else or #elif
  1490. self.seen_else = False
  1491. class _NestingState(object):
  1492. """Holds states related to parsing braces."""
  1493. def __init__(self):
  1494. # Stack for tracking all braces. An object is pushed whenever we
  1495. # see a "{", and popped when we see a "}". Only 3 types of
  1496. # objects are possible:
  1497. # - _ClassInfo: a class or struct.
  1498. # - _NamespaceInfo: a namespace.
  1499. # - _BlockInfo: some other type of block.
  1500. self.stack = []
  1501. # Stack of _PreprocessorInfo objects.
  1502. self.pp_stack = []
  1503. def SeenOpenBrace(self):
  1504. """Check if we have seen the opening brace for the innermost block.
  1505. Returns:
  1506. True if we have seen the opening brace, False if the innermost
  1507. block is still expecting an opening brace.
  1508. """
  1509. return (not self.stack) or self.stack[-1].seen_open_brace
  1510. def InNamespaceBody(self):
  1511. """Check if we are currently one level inside a namespace body.
  1512. Returns:
  1513. True if top of the stack is a namespace block, False otherwise.
  1514. """
  1515. return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
  1516. def UpdatePreprocessor(self, line):
  1517. """Update preprocessor stack.
  1518. We need to handle preprocessors due to classes like this:
  1519. #ifdef SWIG
  1520. struct ResultDetailsPageElementExtensionPoint {
  1521. #else
  1522. struct ResultDetailsPageElementExtensionPoint : public Extension {
  1523. #endif
  1524. We make the following assumptions (good enough for most files):
  1525. - Preprocessor condition evaluates to true from #if up to first
  1526. #else/#elif/#endif.
  1527. - Preprocessor condition evaluates to false from #else/#elif up
  1528. to #endif. We still perform lint checks on these lines, but
  1529. these do not affect nesting stack.
  1530. Args:
  1531. line: current line to check.
  1532. """
  1533. if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
  1534. # Beginning of #if block, save the nesting stack here. The saved
  1535. # stack will allow us to restore the parsing state in the #else case.
  1536. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
  1537. elif Match(r'^\s*#\s*(else|elif)\b', line):
  1538. # Beginning of #else block
  1539. if self.pp_stack:
  1540. if not self.pp_stack[-1].seen_else:
  1541. # This is the first #else or #elif block. Remember the
  1542. # whole nesting stack up to this point. This is what we
  1543. # keep after the #endif.
  1544. self.pp_stack[-1].seen_else = True
  1545. self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
  1546. # Restore the stack to how it was before the #if
  1547. self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
  1548. else:
  1549. # TODO(unknown): unexpected #else, issue warning?
  1550. pass
  1551. elif Match(r'^\s*#\s*endif\b', line):
  1552. # End of #if or #else blocks.
  1553. if self.pp_stack:
  1554. # If we saw an #else, we will need to restore the nesting
  1555. # stack to its former state before the #else, otherwise we
  1556. # will just continue from where we left off.
  1557. if self.pp_stack[-1].seen_else:
  1558. # Here we can just use a shallow copy since we are the last
  1559. # reference to it.
  1560. self.stack = self.pp_stack[-1].stack_before_else
  1561. # Drop the corresponding #if
  1562. self.pp_stack.pop()
  1563. else:
  1564. # TODO(unknown): unexpected #endif, issue warning?
  1565. pass
  1566. def Update(self, filename, clean_lines, linenum, error):
  1567. """Update nesting state with current line.
  1568. Args:
  1569. filename: The name of the current file.
  1570. clean_lines: A CleansedLines instance containing the file.
  1571. linenum: The number of the line to check.
  1572. error: The function to call with any errors found.
  1573. """
  1574. line = clean_lines.elided[linenum]
  1575. # Update pp_stack first
  1576. self.UpdatePreprocessor(line)
  1577. # Count parentheses. This is to avoid adding struct arguments to
  1578. # the nesting stack.
  1579. if self.stack:
  1580. inner_block = self.stack[-1]
  1581. depth_change = line.count('(') - line.count(')')
  1582. inner_block.open_parentheses += depth_change
  1583. # Also check if we are starting or ending an inline assembly block.
  1584. if inner_block.inline_asm in (_NO_ASM, _END_ASM):
  1585. if (depth_change != 0 and
  1586. inner_block.open_parentheses == 1 and
  1587. _MATCH_ASM.match(line)):
  1588. # Enter assembly block
  1589. inner_block.inline_asm = _INSIDE_ASM
  1590. else:
  1591. # Not entering assembly block. If previous line was _END_ASM,
  1592. # we will now shift to _NO_ASM state.
  1593. inner_block.inline_asm = _NO_ASM
  1594. elif (inner_block.inline_asm == _INSIDE_ASM and
  1595. inner_block.open_parentheses == 0):
  1596. # Exit assembly block
  1597. inner_block.inline_asm = _END_ASM
  1598. # Consume namespace declaration at the beginning of the line. Do
  1599. # this in a loop so that we catch same line declarations like this:
  1600. # namespace proto2 { namespace bridge { class MessageSet; } }
  1601. while True:
  1602. # Match start of namespace. The "\b\s*" below catches namespace
  1603. # declarations even if it weren't followed by a whitespace, this
  1604. # is so that we don't confuse our namespace checker. The
  1605. # missing spaces will be flagged by CheckSpacing.
  1606. namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
  1607. if not namespace_decl_match:
  1608. break
  1609. new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
  1610. self.stack.append(new_namespace)
  1611. line = namespace_decl_match.group(2)
  1612. if line.find('{') != -1:
  1613. new_namespace.seen_open_brace = True
  1614. line = line[line.find('{') + 1:]
  1615. # Look for a class declaration in whatever is left of the line
  1616. # after parsing namespaces. The regexp accounts for decorated classes
  1617. # such as in:
  1618. # class LOCKABLE API Object {
  1619. # };
  1620. #
  1621. # Templates with class arguments may confuse the parser, for example:
  1622. # template <class T
  1623. # class Comparator = less<T>,
  1624. # class Vector = vector<T> >
  1625. # class HeapQueue {
  1626. #
  1627. # Because this parser has no nesting state about templates, by the
  1628. # time it saw "class Comparator", it may think that it's a new class.
  1629. # Nested templates have a similar problem:
  1630. # template <
  1631. # typename ExportedType,
  1632. # typename TupleType,
  1633. # template <typename, typename> class ImplTemplate>
  1634. #
  1635. # To avoid these cases, we ignore classes that are followed by '=' or '>'
  1636. class_decl_match = Match(
  1637. r'\s*(template\s*<[\w\s<>,:]*>\s*)?'
  1638. r'(class|struct)\s+([A-Z_]+\s+)*(\w+(?:::\w+)*)'
  1639. r'(([^=>]|<[^<>]*>|<[^<>]*<[^<>]*>\s*>)*)$', line)
  1640. if (class_decl_match and
  1641. (not self.stack or self.stack[-1].open_parentheses == 0)):
  1642. self.stack.append(_ClassInfo(
  1643. class_decl_match.group(4), class_decl_match.group(2),
  1644. clean_lines, linenum))
  1645. line = class_decl_match.group(5)
  1646. # If we have not yet seen the opening brace for the innermost block,
  1647. # run checks here.
  1648. if not self.SeenOpenBrace():
  1649. self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
  1650. # Update access control if we are inside a class/struct
  1651. if self.stack and isinstance(self.stack[-1], _ClassInfo):
  1652. classinfo = self.stack[-1]
  1653. access_match = Match(
  1654. r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
  1655. r':(?:[^:]|$)',
  1656. line)
  1657. if access_match:
  1658. classinfo.access = access_match.group(2)
  1659. # Check that access keywords are indented +1 space. Skip this
  1660. # check if the keywords are not preceded by whitespaces.
  1661. indent = access_match.group(1)
  1662. if (len(indent) != classinfo.class_indent + 1 and
  1663. Match(r'^\s*$', indent)):
  1664. if classinfo.is_struct:
  1665. parent = 'struct ' + classinfo.name
  1666. else:
  1667. parent = 'class ' + classinfo.name
  1668. slots = ''
  1669. if access_match.group(3):
  1670. slots = access_match.group(3)
  1671. error(filename, linenum, 'whitespace/indent', 3,
  1672. '%s%s: should be indented +1 space inside %s' % (
  1673. access_match.group(2), slots, parent))
  1674. # Consume braces or semicolons from what's left of the line
  1675. while True:
  1676. # Match first brace, semicolon, or closed parenthesis.
  1677. matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
  1678. if not matched:
  1679. break
  1680. token = matched.group(1)
  1681. if token == '{':
  1682. # If namespace or class hasn't seen a opening brace yet, mark
  1683. # namespace/class head as complete. Push a new block onto the
  1684. # stack otherwise.
  1685. if not self.SeenOpenBrace():
  1686. self.stack[-1].seen_open_brace = True
  1687. else:
  1688. self.stack.append(_BlockInfo(True))
  1689. if _MATCH_ASM.match(line):
  1690. self.stack[-1].inline_asm = _BLOCK_ASM
  1691. elif token == ';' or token == ')':
  1692. # If we haven't seen an opening brace yet, but we already saw
  1693. # a semicolon, this is probably a forward declaration. Pop
  1694. # the stack for these.
  1695. #
  1696. # Similarly, if we haven't seen an opening brace yet, but we
  1697. # already saw a closing parenthesis, then these are probably
  1698. # function arguments with extra "class" or "struct" keywords.
  1699. # Also pop these stack for these.
  1700. if not self.SeenOpenBrace():
  1701. self.stack.pop()
  1702. else: # token == '}'
  1703. # Perform end of block checks and pop the stack.
  1704. if self.stack:
  1705. self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
  1706. self.stack.pop()
  1707. line = matched.group(2)
  1708. def InnermostClass(self):
  1709. """Get class info on the top of the stack.
  1710. Returns:
  1711. A _ClassInfo object if we are inside a class, or None otherwise.
  1712. """
  1713. for i in range(len(self.stack), 0, -1):
  1714. classinfo = self.stack[i - 1]
  1715. if isinstance(classinfo, _ClassInfo):
  1716. return classinfo
  1717. return None
  1718. def CheckCompletedBlocks(self, filename, error):
  1719. """Checks that all classes and namespaces have been completely parsed.
  1720. Call this when all lines in a file have been processed.
  1721. Args:
  1722. filename: The name of the current file.
  1723. error: The function to call with any errors found.
  1724. """
  1725. # Note: This test can result in false positives if #ifdef constructs
  1726. # get in the way of brace matching. See the testBuildClass test in
  1727. # cpplint_unittest.py for an example of this.
  1728. for obj in self.stack:
  1729. if isinstance(obj, _ClassInfo):
  1730. error(filename, obj.starting_linenum, 'build/class', 5,
  1731. 'Failed to find complete declaration of class %s' %
  1732. obj.name)
  1733. elif isinstance(obj, _NamespaceInfo):
  1734. error(filename, obj.starting_linenum, 'build/namespaces', 5,
  1735. 'Failed to find complete declaration of namespace %s' %
  1736. obj.name)
  1737. def CheckForNonStandardConstructs(filename, clean_lines, linenum,
  1738. nesting_state, error):
  1739. r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
  1740. Complain about several constructs which gcc-2 accepts, but which are
  1741. not standard C++. Warning about these in lint is one way to ease the
  1742. transition to new compilers.
  1743. - put storage class first (e.g. "static const" instead of "const static").
  1744. - "%lld" instead of %qd" in printf-type functions.
  1745. - "%1$d" is non-standard in printf-type functions.
  1746. - "\%" is an undefined character escape sequence.
  1747. - text after #endif is not allowed.
  1748. - invalid inner-style forward declaration.
  1749. - >? and <? operators, and their >?= and <?= cousins.
  1750. Additionally, check for constructor/destructor style violations and reference
  1751. members, as it is very convenient to do so while checking for
  1752. gcc-2 compliance.
  1753. Args:
  1754. filename: The name of the current file.
  1755. clean_lines: A CleansedLines instance containing the file.
  1756. linenum: The number of the line to check.
  1757. nesting_state: A _NestingState instance which maintains information about
  1758. the current stack of nested blocks being parsed.
  1759. error: A callable to which errors are reported, which takes 4 arguments:
  1760. filename, line number, error level, and message
  1761. """
  1762. # Remove comments from the line, but leave in strings for now.
  1763. line = clean_lines.lines[linenum]
  1764. if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
  1765. error(filename, linenum, 'runtime/printf_format', 3,
  1766. '%q in format strings is deprecated. Use %ll instead.')
  1767. if Search(r'printf\s*\(.*".*%\d+\$', line):
  1768. error(filename, linenum, 'runtime/printf_format', 2,
  1769. '%N$ formats are unconventional. Try rewriting to avoid them.')
  1770. # Remove escaped backslashes before looking for undefined escapes.
  1771. line = line.replace('\\\\', '')
  1772. if Search(r'("|\').*\\(%|\[|\(|{)', line):
  1773. error(filename, linenum, 'build/printf_format', 3,
  1774. '%, [, (, and { are undefined character escapes. Unescape them.')
  1775. # For the rest, work with both comments and strings removed.
  1776. line = clean_lines.elided[linenum]
  1777. if Search(r'\b(const|volatile|void|char|short|int|long'
  1778. r'|float|double|signed|unsigned'
  1779. r'|schar|u?int8|u?int16|u?int32|u?int64)'
  1780. r'\s+(register|static|extern|typedef)\b',
  1781. line):
  1782. error(filename, linenum, 'build/storage_class', 5,
  1783. 'Storage class (static, extern, typedef, etc) should be first.')
  1784. if Match(r'\s*#\s*endif\s*[^/\s]+', line):
  1785. error(filename, linenum, 'build/endif_comment', 5,
  1786. 'Uncommented text after #endif is non-standard. Use a comment.')
  1787. if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
  1788. error(filename, linenum, 'build/forward_decl', 5,
  1789. 'Inner-style forward declarations are invalid. Remove this line.')
  1790. if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
  1791. line):
  1792. error(filename, linenum, 'build/deprecated', 3,
  1793. '>? and <? (max and min) operators are non-standard and deprecated.')
  1794. if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
  1795. # TODO(unknown): Could it be expanded safely to arbitrary references,
  1796. # without triggering too many false positives? The first
  1797. # attempt triggered 5 warnings for mostly benign code in the regtest, hence
  1798. # the restriction.
  1799. # Here's the original regexp, for the reference:
  1800. # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
  1801. # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
  1802. error(filename, linenum, 'runtime/member_string_references', 2,
  1803. 'const string& members are dangerous. It is much better to use '
  1804. 'alternatives, such as pointers or simple constants.')
  1805. # Everything else in this function operates on class declarations.
  1806. # Return early if the top of the nesting stack is not a class, or if
  1807. # the class head is not completed yet.
  1808. classinfo = nesting_state.InnermostClass()
  1809. if not classinfo or not classinfo.seen_open_brace:
  1810. return
  1811. # The class may have been declared with namespace or classname qualifiers.
  1812. # The constructor and destructor will not have those qualifiers.
  1813. base_classname = classinfo.name.split('::')[-1]
  1814. # Look for single-argument constructors that aren't marked explicit.
  1815. # Technically a valid construct, but against style.
  1816. args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
  1817. % re.escape(base_classname),
  1818. line)
  1819. if (args and
  1820. args.group(1) != 'void' and
  1821. not Match(r'(const\s+)?%s(\s+const)?\s*(?:<\w+>\s*)?&'
  1822. % re.escape(base_classname), args.group(1).strip())):
  1823. error(filename, linenum, 'runtime/explicit', 5,
  1824. 'Single-argument constructors should be marked explicit.')
  1825. def CheckSpacingForFunctionCall(filename, line, linenum, error):
  1826. """Checks for the correctness of various spacing around function calls.
  1827. Args:
  1828. filename: The name of the current file.
  1829. line: The text of the line to check.
  1830. linenum: The number of the line to check.
  1831. error: The function to call with any errors found.
  1832. """
  1833. # Since function calls often occur inside if/for/while/switch
  1834. # expressions - which have their own, more liberal conventions - we
  1835. # first see if we should be looking inside such an expression for a
  1836. # function call, to which we can apply more strict standards.
  1837. fncall = line # if there's no control flow construct, look at whole line
  1838. for pattern in (r'\bif\s*\((.*)\)\s*{',
  1839. r'\bfor\s*\((.*)\)\s*{',
  1840. r'\bwhile\s*\((.*)\)\s*[{;]',
  1841. r'\bswitch\s*\((.*)\)\s*{'):
  1842. match = Search(pattern, line)
  1843. if match:
  1844. fncall = match.group(1) # look inside the parens for function calls
  1845. break
  1846. # Except in if/for/while/switch, there should never be space
  1847. # immediately inside parens (eg "f( 3, 4 )"). We make an exception
  1848. # for nested parens ( (a+b) + c ). Likewise, there should never be
  1849. # a space before a ( when it's a function argument. I assume it's a
  1850. # function argument when the char before the whitespace is legal in
  1851. # a function name (alnum + _) and we're not starting a macro. Also ignore
  1852. # pointers and references to arrays and functions coz they're too tricky:
  1853. # we use a very simple way to recognize these:
  1854. # " (something)(maybe-something)" or
  1855. # " (something)(maybe-something," or
  1856. # " (something)[something]"
  1857. # Note that we assume the contents of [] to be short enough that
  1858. # they'll never need to wrap.
  1859. if ( # Ignore control structures.
  1860. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
  1861. fncall) and
  1862. # Ignore pointers/references to functions.
  1863. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
  1864. # Ignore pointers/references to arrays.
  1865. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
  1866. if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
  1867. error(filename, linenum, 'whitespace/parens', 4,
  1868. 'Extra space after ( in function call')
  1869. elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
  1870. error(filename, linenum, 'whitespace/parens', 2,
  1871. 'Extra space after (')
  1872. if (Search(r'\w\s+\(', fncall) and
  1873. not Search(r'#\s*define|typedef', fncall) and
  1874. not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)):
  1875. error(filename, linenum, 'whitespace/parens', 4,
  1876. 'Extra space before ( in function call')
  1877. # If the ) is followed only by a newline or a { + newline, assume it's
  1878. # part of a control statement (if/while/etc), and don't complain
  1879. if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
  1880. # If the closing parenthesis is preceded by only whitespaces,
  1881. # try to give a more descriptive error message.
  1882. if Search(r'^\s+\)', fncall):
  1883. error(filename, linenum, 'whitespace/parens', 2,
  1884. 'Closing ) should be moved to the previous line')
  1885. else:
  1886. error(filename, linenum, 'whitespace/parens', 2,
  1887. 'Extra space before )')
  1888. def IsBlankLine(line):
  1889. """Returns true if the given line is blank.
  1890. We consider a line to be blank if the line is empty or consists of
  1891. only white spaces.
  1892. Args:
  1893. line: A line of a string.
  1894. Returns:
  1895. True, if the given line is blank.
  1896. """
  1897. return not line or line.isspace()
  1898. def CheckForFunctionLengths(filename, clean_lines, linenum,
  1899. function_state, error):
  1900. """Reports for long function bodies.
  1901. For an overview why this is done, see:
  1902. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
  1903. Uses a simplistic algorithm assuming other style guidelines
  1904. (especially spacing) are followed.
  1905. Only checks unindented functions, so class members are unchecked.
  1906. Trivial bodies are unchecked, so constructors with huge initializer lists
  1907. may be missed.
  1908. Blank/comment lines are not counted so as to avoid encouraging the removal
  1909. of vertical space and comments just to get through a lint check.
  1910. NOLINT *on the last line of a function* disables this check.
  1911. Args:
  1912. filename: The name of the current file.
  1913. clean_lines: A CleansedLines instance containing the file.
  1914. linenum: The number of the line to check.
  1915. function_state: Current function name and lines in body so far.
  1916. error: The function to call with any errors found.
  1917. """
  1918. lines = clean_lines.lines
  1919. line = lines[linenum]
  1920. raw = clean_lines.raw_lines
  1921. raw_line = raw[linenum]
  1922. joined_line = ''
  1923. starting_func = False
  1924. regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
  1925. match_result = Match(regexp, line)
  1926. if match_result:
  1927. # If the name is all caps and underscores, figure it's a macro and
  1928. # ignore it, unless it's TEST or TEST_F.
  1929. function_name = match_result.group(1).split()[-1]
  1930. if function_name == 'TEST' or function_name == 'TEST_F' or (
  1931. not Match(r'[A-Z_]+$', function_name)):
  1932. starting_func = True
  1933. if starting_func:
  1934. body_found = False
  1935. for start_linenum in xrange(linenum, clean_lines.NumLines()):
  1936. start_line = lines[start_linenum]
  1937. joined_line += ' ' + start_line.lstrip()
  1938. if Search(r'(;|})', start_line): # Declarations and trivial functions
  1939. body_found = True
  1940. break # ... ignore
  1941. elif Search(r'{', start_line):
  1942. body_found = True
  1943. function = Search(r'((\w|:)*)\(', line).group(1)
  1944. if Match(r'TEST', function): # Handle TEST... macros
  1945. parameter_regexp = Search(r'(\(.*\))', joined_line)
  1946. if parameter_regexp: # Ignore bad syntax
  1947. function += parameter_regexp.group(1)
  1948. else:
  1949. function += '()'
  1950. function_state.Begin(function)
  1951. break
  1952. if not body_found:
  1953. # No body for the function (or evidence of a non-function) was found.
  1954. error(filename, linenum, 'readability/fn_size', 5,
  1955. 'Lint failed to find start of function body.')
  1956. elif Match(r'^\}\s*$', line): # function end
  1957. function_state.Check(error, filename, linenum)
  1958. function_state.End()
  1959. elif not Match(r'^\s*$', line):
  1960. function_state.Count() # Count non-blank/non-comment lines.
  1961. _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
  1962. def CheckComment(comment, filename, linenum, error):
  1963. """Checks for common mistakes in TODO comments.
  1964. Args:
  1965. comment: The text of the comment from the line in question.
  1966. filename: The name of the current file.
  1967. linenum: The number of the line to check.
  1968. error: The function to call with any errors found.
  1969. """
  1970. match = _RE_PATTERN_TODO.match(comment)
  1971. if match:
  1972. # One whitespace is correct; zero whitespace is handled elsewhere.
  1973. leading_whitespace = match.group(1)
  1974. if len(leading_whitespace) > 1:
  1975. error(filename, linenum, 'whitespace/todo', 2,
  1976. 'Too many spaces before TODO')
  1977. username = match.group(2)
  1978. if not username:
  1979. error(filename, linenum, 'readability/todo', 2,
  1980. 'Missing username in TODO; it should look like '
  1981. '"// TODO(my_username): Stuff."')
  1982. middle_whitespace = match.group(3)
  1983. # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
  1984. if middle_whitespace != ' ' and middle_whitespace != '':
  1985. error(filename, linenum, 'whitespace/todo', 2,
  1986. 'TODO(my_username) should be followed by a space')
  1987. def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
  1988. """Checks for improper use of DISALLOW* macros.
  1989. Args:
  1990. filename: The name of the current file.
  1991. clean_lines: A CleansedLines instance containing the file.
  1992. linenum: The number of the line to check.
  1993. nesting_state: A _NestingState instance which maintains information about
  1994. the current stack of nested blocks being parsed.
  1995. error: The function to call with any errors found.
  1996. """
  1997. line = clean_lines.elided[linenum] # get rid of comments and strings
  1998. matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|'
  1999. r'DISALLOW_EVIL_CONSTRUCTORS|'
  2000. r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line)
  2001. if not matched:
  2002. return
  2003. if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo):
  2004. if nesting_state.stack[-1].access != 'private':
  2005. error(filename, linenum, 'readability/constructors', 3,
  2006. '%s must be in the private: section' % matched.group(1))
  2007. else:
  2008. # Found DISALLOW* macro outside a class declaration, or perhaps it
  2009. # was used inside a function when it should have been part of the
  2010. # class declaration. We could issue a warning here, but it
  2011. # probably resulted in a compiler error already.
  2012. pass
  2013. def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix):
  2014. """Find the corresponding > to close a template.
  2015. Args:
  2016. clean_lines: A CleansedLines instance containing the file.
  2017. linenum: Current line number.
  2018. init_suffix: Remainder of the current line after the initial <.
  2019. Returns:
  2020. True if a matching bracket exists.
  2021. """
  2022. line = init_suffix
  2023. nesting_stack = ['<']
  2024. while True:
  2025. # Find the next operator that can tell us whether < is used as an
  2026. # opening bracket or as a less-than operator. We only want to
  2027. # warn on the latter case.
  2028. #
  2029. # We could also check all other operators and terminate the search
  2030. # early, e.g. if we got something like this "a<b+c", the "<" is
  2031. # most likely a less-than operator, but then we will get false
  2032. # positives for default arguments and other template expressions.
  2033. match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line)
  2034. if match:
  2035. # Found an operator, update nesting stack
  2036. operator = match.group(1)
  2037. line = match.group(2)
  2038. if nesting_stack[-1] == '<':
  2039. # Expecting closing angle bracket
  2040. if operator in ('<', '(', '['):
  2041. nesting_stack.append(operator)
  2042. elif operator == '>':
  2043. nesting_stack.pop()
  2044. if not nesting_stack:
  2045. # Found matching angle bracket
  2046. return True
  2047. elif operator == ',':
  2048. # Got a comma after a bracket, this is most likely a template
  2049. # argument. We have not seen a closing angle bracket yet, but
  2050. # it's probably a few lines later if we look for it, so just
  2051. # return early here.
  2052. return True
  2053. else:
  2054. # Got some other operator.
  2055. return False
  2056. else:
  2057. # Expecting closing parenthesis or closing bracket
  2058. if operator in ('<', '(', '['):
  2059. nesting_stack.append(operator)
  2060. elif operator in (')', ']'):
  2061. # We don't bother checking for matching () or []. If we got
  2062. # something like (] or [), it would have been a syntax error.
  2063. nesting_stack.pop()
  2064. else:
  2065. # Scan the next line
  2066. linenum += 1
  2067. if linenum >= len(clean_lines.elided):
  2068. break
  2069. line = clean_lines.elided[linenum]
  2070. # Exhausted all remaining lines and still no matching angle bracket.
  2071. # Most likely the input was incomplete, otherwise we should have
  2072. # seen a semicolon and returned early.
  2073. return True
  2074. def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix):
  2075. """Find the corresponding < that started a template.
  2076. Args:
  2077. clean_lines: A CleansedLines instance containing the file.
  2078. linenum: Current line number.
  2079. init_prefix: Part of the current line before the initial >.
  2080. Returns:
  2081. True if a matching bracket exists.
  2082. """
  2083. line = init_prefix
  2084. nesting_stack = ['>']
  2085. while True:
  2086. # Find the previous operator
  2087. match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line)
  2088. if match:
  2089. # Found an operator, update nesting stack
  2090. operator = match.group(2)
  2091. line = match.group(1)
  2092. if nesting_stack[-1] == '>':
  2093. # Expecting opening angle bracket
  2094. if operator in ('>', ')', ']'):
  2095. nesting_stack.append(operator)
  2096. elif operator == '<':
  2097. nesting_stack.pop()
  2098. if not nesting_stack:
  2099. # Found matching angle bracket
  2100. return True
  2101. elif operator == ',':
  2102. # Got a comma before a bracket, this is most likely a
  2103. # template argument. The opening angle bracket is probably
  2104. # there if we look for it, so just return early here.
  2105. return True
  2106. else:
  2107. # Got some other operator.
  2108. return False
  2109. else:
  2110. # Expecting opening parenthesis or opening bracket
  2111. if operator in ('>', ')', ']'):
  2112. nesting_stack.append(operator)
  2113. elif operator in ('(', '['):
  2114. nesting_stack.pop()
  2115. else:
  2116. # Scan the previous line
  2117. linenum -= 1
  2118. if linenum < 0:
  2119. break
  2120. line = clean_lines.elided[linenum]
  2121. # Exhausted all earlier lines and still no matching angle bracket.
  2122. return False
  2123. def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
  2124. """Checks for the correctness of various spacing issues in the code.
  2125. Things we check for: spaces around operators, spaces after
  2126. if/for/while/switch, no spaces around parens in function calls, two
  2127. spaces between code and comment, don't start a block with a blank
  2128. line, don't end a function with a blank line, don't add a blank line
  2129. after public/protected/private, don't have too many blank lines in a row.
  2130. Args:
  2131. filename: The name of the current file.
  2132. clean_lines: A CleansedLines instance containing the file.
  2133. linenum: The number of the line to check.
  2134. nesting_state: A _NestingState instance which maintains information about
  2135. the current stack of nested blocks being parsed.
  2136. error: The function to call with any errors found.
  2137. """
  2138. # Don't use "elided" lines here, otherwise we can't check commented lines.
  2139. # Don't want to use "raw" either, because we don't want to check inside C++11
  2140. # raw strings,
  2141. raw = clean_lines.lines_without_raw_strings
  2142. line = raw[linenum]
  2143. # Before nixing comments, check if the line is blank for no good
  2144. # reason. This includes the first line after a block is opened, and
  2145. # blank lines at the end of a function (ie, right before a line like '}'
  2146. #
  2147. # Skip all the blank line checks if we are immediately inside a
  2148. # namespace body. In other words, don't issue blank line warnings
  2149. # for this block:
  2150. # namespace {
  2151. #
  2152. # }
  2153. #
  2154. # A warning about missing end of namespace comments will be issued instead.
  2155. if IsBlankLine(line) and not nesting_state.InNamespaceBody():
  2156. elided = clean_lines.elided
  2157. prev_line = elided[linenum - 1]
  2158. prevbrace = prev_line.rfind('{')
  2159. # TODO(unknown): Don't complain if line before blank line, and line after,
  2160. # both start with alnums and are indented the same amount.
  2161. # This ignores whitespace at the start of a namespace block
  2162. # because those are not usually indented.
  2163. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
  2164. # OK, we have a blank line at the start of a code block. Before we
  2165. # complain, we check if it is an exception to the rule: The previous
  2166. # non-empty line has the parameters of a function header that are indented
  2167. # 4 spaces (because they did not fit in a 80 column line when placed on
  2168. # the same line as the function name). We also check for the case where
  2169. # the previous line is indented 6 spaces, which may happen when the
  2170. # initializers of a constructor do not fit into a 80 column line.
  2171. exception = False
  2172. if Match(r' {6}\w', prev_line): # Initializer list?
  2173. # We are looking for the opening column of initializer list, which
  2174. # should be indented 4 spaces to cause 6 space indentation afterwards.
  2175. search_position = linenum-2
  2176. while (search_position >= 0
  2177. and Match(r' {6}\w', elided[search_position])):
  2178. search_position -= 1
  2179. exception = (search_position >= 0
  2180. and elided[search_position][:5] == ' :')
  2181. else:
  2182. # Search for the function arguments or an initializer list. We use a
  2183. # simple heuristic here: If the line is indented 4 spaces; and we have a
  2184. # closing paren, without the opening paren, followed by an opening brace
  2185. # or colon (for initializer lists) we assume that it is the last line of
  2186. # a function header. If we have a colon indented 4 spaces, it is an
  2187. # initializer list.
  2188. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
  2189. prev_line)
  2190. or Match(r' {4}:', prev_line))
  2191. if not exception:
  2192. error(filename, linenum, 'whitespace/blank_line', 2,
  2193. 'Redundant blank line at the start of a code block '
  2194. 'should be deleted.')
  2195. # Ignore blank lines at the end of a block in a long if-else
  2196. # chain, like this:
  2197. # if (condition1) {
  2198. # // Something followed by a blank line
  2199. #
  2200. # } else if (condition2) {
  2201. # // Something else
  2202. # }
  2203. if linenum + 1 < clean_lines.NumLines():
  2204. next_line = raw[linenum + 1]
  2205. if (next_line
  2206. and Match(r'\s*}', next_line)
  2207. and next_line.find('} else ') == -1):
  2208. error(filename, linenum, 'whitespace/blank_line', 3,
  2209. 'Redundant blank line at the end of a code block '
  2210. 'should be deleted.')
  2211. matched = Match(r'\s*(public|protected|private):', prev_line)
  2212. if matched:
  2213. error(filename, linenum, 'whitespace/blank_line', 3,
  2214. 'Do not leave a blank line after "%s:"' % matched.group(1))
  2215. # Next, we complain if there's a comment too near the text
  2216. commentpos = line.find('//')
  2217. if commentpos != -1:
  2218. # Check if the // may be in quotes. If so, ignore it
  2219. # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
  2220. if (line.count('"', 0, commentpos) -
  2221. line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
  2222. # Allow one space for new scopes, two spaces otherwise:
  2223. if (not Match(r'^\s*{ //', line) and
  2224. ((commentpos >= 1 and
  2225. line[commentpos-1] not in string.whitespace) or
  2226. (commentpos >= 2 and
  2227. line[commentpos-2] not in string.whitespace))):
  2228. error(filename, linenum, 'whitespace/comments', 2,
  2229. 'At least two spaces is best between code and comments')
  2230. # There should always be a space between the // and the comment
  2231. commentend = commentpos + 2
  2232. if commentend < len(line) and not line[commentend] == ' ':
  2233. # but some lines are exceptions -- e.g. if they're big
  2234. # comment delimiters like:
  2235. # //----------------------------------------------------------
  2236. # or are an empty C++ style Doxygen comment, like:
  2237. # ///
  2238. # or C++ style Doxygen comments placed after the variable:
  2239. # ///< Header comment
  2240. # //!< Header comment
  2241. # or they begin with multiple slashes followed by a space:
  2242. # //////// Header comment
  2243. match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
  2244. Search(r'^/$', line[commentend:]) or
  2245. Search(r'^!< ', line[commentend:]) or
  2246. Search(r'^/< ', line[commentend:]) or
  2247. Search(r'^/+ ', line[commentend:]))
  2248. if not match:
  2249. error(filename, linenum, 'whitespace/comments', 4,
  2250. 'Should have a space between // and comment')
  2251. CheckComment(line[commentpos:], filename, linenum, error)
  2252. line = clean_lines.elided[linenum] # get rid of comments and strings
  2253. # Don't try to do spacing checks for operator methods
  2254. line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
  2255. # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
  2256. # Otherwise not. Note we only check for non-spaces on *both* sides;
  2257. # sometimes people put non-spaces on one side when aligning ='s among
  2258. # many lines (not that this is behavior that I approve of...)
  2259. if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line):
  2260. error(filename, linenum, 'whitespace/operators', 4,
  2261. 'Missing spaces around =')
  2262. # It's ok not to have spaces around binary operators like + - * /, but if
  2263. # there's too little whitespace, we get concerned. It's hard to tell,
  2264. # though, so we punt on this one for now. TODO.
  2265. # You should always have whitespace around binary operators.
  2266. #
  2267. # Check <= and >= first to avoid false positives with < and >, then
  2268. # check non-include lines for spacing around < and >.
  2269. match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
  2270. if match:
  2271. error(filename, linenum, 'whitespace/operators', 3,
  2272. 'Missing spaces around %s' % match.group(1))
  2273. # We allow no-spaces around << when used like this: 10<<20, but
  2274. # not otherwise (particularly, not when used as streams)
  2275. # Also ignore using ns::operator<<;
  2276. match = Search(r'(operator|\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line)
  2277. if (match and
  2278. not (match.group(1).isdigit() and match.group(2).isdigit()) and
  2279. not (match.group(1) == 'operator' and match.group(2) == ';')):
  2280. error(filename, linenum, 'whitespace/operators', 3,
  2281. 'Missing spaces around <<')
  2282. elif not Match(r'#.*include', line):
  2283. # Avoid false positives on ->
  2284. reduced_line = line.replace('->', '')
  2285. # Look for < that is not surrounded by spaces. This is only
  2286. # triggered if both sides are missing spaces, even though
  2287. # technically should should flag if at least one side is missing a
  2288. # space. This is done to avoid some false positives with shifts.
  2289. match = Search(r'[^\s<]<([^\s=<].*)', reduced_line)
  2290. if (match and
  2291. not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))):
  2292. error(filename, linenum, 'whitespace/operators', 3,
  2293. 'Missing spaces around <')
  2294. # Look for > that is not surrounded by spaces. Similar to the
  2295. # above, we only trigger if both sides are missing spaces to avoid
  2296. # false positives with shifts.
  2297. match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line)
  2298. if (match and
  2299. not FindPreviousMatchingAngleBracket(clean_lines, linenum,
  2300. match.group(1))):
  2301. error(filename, linenum, 'whitespace/operators', 3,
  2302. 'Missing spaces around >')
  2303. # We allow no-spaces around >> for almost anything. This is because
  2304. # C++11 allows ">>" to close nested templates, which accounts for
  2305. # most cases when ">>" is not followed by a space.
  2306. #
  2307. # We still warn on ">>" followed by alpha character, because that is
  2308. # likely due to ">>" being used for right shifts, e.g.:
  2309. # value >> alpha
  2310. #
  2311. # When ">>" is used to close templates, the alphanumeric letter that
  2312. # follows would be part of an identifier, and there should still be
  2313. # a space separating the template type and the identifier.
  2314. # type<type<type>> alpha
  2315. match = Search(r'>>[a-zA-Z_]', line)
  2316. if match:
  2317. error(filename, linenum, 'whitespace/operators', 3,
  2318. 'Missing spaces around >>')
  2319. # There shouldn't be space around unary operators
  2320. match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
  2321. if match:
  2322. error(filename, linenum, 'whitespace/operators', 4,
  2323. 'Extra space for operator %s' % match.group(1))
  2324. # A pet peeve of mine: no spaces after an if, while, switch, or for
  2325. match = Search(r' (if\(|for\(|while\(|switch\()', line)
  2326. if match:
  2327. error(filename, linenum, 'whitespace/parens', 5,
  2328. 'Missing space before ( in %s' % match.group(1))
  2329. # For if/for/while/switch, the left and right parens should be
  2330. # consistent about how many spaces are inside the parens, and
  2331. # there should either be zero or one spaces inside the parens.
  2332. # We don't want: "if ( foo)" or "if ( foo )".
  2333. # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
  2334. match = Search(r'\b(if|for|while|switch)\s*'
  2335. r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
  2336. line)
  2337. if match:
  2338. if len(match.group(2)) != len(match.group(4)):
  2339. if not (match.group(3) == ';' and
  2340. len(match.group(2)) == 1 + len(match.group(4)) or
  2341. not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
  2342. error(filename, linenum, 'whitespace/parens', 5,
  2343. 'Mismatching spaces inside () in %s' % match.group(1))
  2344. if len(match.group(2)) not in [0, 1]:
  2345. error(filename, linenum, 'whitespace/parens', 5,
  2346. 'Should have zero or one spaces inside ( and ) in %s' %
  2347. match.group(1))
  2348. # You should always have a space after a comma (either as fn arg or operator)
  2349. #
  2350. # This does not apply when the non-space character following the
  2351. # comma is another comma, since the only time when that happens is
  2352. # for empty macro arguments.
  2353. #
  2354. # We run this check in two passes: first pass on elided lines to
  2355. # verify that lines contain missing whitespaces, second pass on raw
  2356. # lines to confirm that those missing whitespaces are not due to
  2357. # elided comments.
  2358. if Search(r',[^,\s]', line) and Search(r',[^,\s]', raw[linenum]):
  2359. error(filename, linenum, 'whitespace/comma', 3,
  2360. 'Missing space after ,')
  2361. # You should always have a space after a semicolon
  2362. # except for few corner cases
  2363. # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
  2364. # space after ;
  2365. if Search(r';[^\s};\\)/]', line):
  2366. error(filename, linenum, 'whitespace/semicolon', 3,
  2367. 'Missing space after ;')
  2368. # Next we will look for issues with function calls.
  2369. CheckSpacingForFunctionCall(filename, line, linenum, error)
  2370. # Except after an opening paren, or after another opening brace (in case of
  2371. # an initializer list, for instance), you should have spaces before your
  2372. # braces. And since you should never have braces at the beginning of a line,
  2373. # this is an easy test.
  2374. match = Match(r'^(.*[^ ({]){', line)
  2375. if match:
  2376. # Try a bit harder to check for brace initialization. This
  2377. # happens in one of the following forms:
  2378. # Constructor() : initializer_list_{} { ... }
  2379. # Constructor{}.MemberFunction()
  2380. # Type variable{};
  2381. # FunctionCall(type{}, ...);
  2382. # LastArgument(..., type{});
  2383. # LOG(INFO) << type{} << " ...";
  2384. # map_of_type[{...}] = ...;
  2385. #
  2386. # We check for the character following the closing brace, and
  2387. # silence the warning if it's one of those listed above, i.e.
  2388. # "{.;,)<]".
  2389. #
  2390. # To account for nested initializer list, we allow any number of
  2391. # closing braces up to "{;,)<". We can't simply silence the
  2392. # warning on first sight of closing brace, because that would
  2393. # cause false negatives for things that are not initializer lists.
  2394. # Silence this: But not this:
  2395. # Outer{ if (...) {
  2396. # Inner{...} if (...){ // Missing space before {
  2397. # }; }
  2398. #
  2399. # There is a false negative with this approach if people inserted
  2400. # spurious semicolons, e.g. "if (cond){};", but we will catch the
  2401. # spurious semicolon with a separate check.
  2402. (endline, endlinenum, endpos) = CloseExpression(
  2403. clean_lines, linenum, len(match.group(1)))
  2404. trailing_text = ''
  2405. if endpos > -1:
  2406. trailing_text = endline[endpos:]
  2407. for offset in xrange(endlinenum + 1,
  2408. min(endlinenum + 3, clean_lines.NumLines() - 1)):
  2409. trailing_text += clean_lines.elided[offset]
  2410. if not Match(r'^[\s}]*[{.;,)<\]]', trailing_text):
  2411. error(filename, linenum, 'whitespace/braces', 5,
  2412. 'Missing space before {')
  2413. # Make sure '} else {' has spaces.
  2414. if Search(r'}else', line):
  2415. error(filename, linenum, 'whitespace/braces', 5,
  2416. 'Missing space before else')
  2417. # You shouldn't have spaces before your brackets, except maybe after
  2418. # 'delete []' or 'new char * []'.
  2419. if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
  2420. error(filename, linenum, 'whitespace/braces', 5,
  2421. 'Extra space before [')
  2422. # You shouldn't have a space before a semicolon at the end of the line.
  2423. # There's a special case for "for" since the style guide allows space before
  2424. # the semicolon there.
  2425. if Search(r':\s*;\s*$', line):
  2426. error(filename, linenum, 'whitespace/semicolon', 5,
  2427. 'Semicolon defining empty statement. Use {} instead.')
  2428. elif Search(r'^\s*;\s*$', line):
  2429. error(filename, linenum, 'whitespace/semicolon', 5,
  2430. 'Line contains only semicolon. If this should be an empty statement, '
  2431. 'use {} instead.')
  2432. elif (Search(r'\s+;\s*$', line) and
  2433. not Search(r'\bfor\b', line)):
  2434. error(filename, linenum, 'whitespace/semicolon', 5,
  2435. 'Extra space before last semicolon. If this should be an empty '
  2436. 'statement, use {} instead.')
  2437. # In range-based for, we wanted spaces before and after the colon, but
  2438. # not around "::" tokens that might appear.
  2439. if (Search('for *\(.*[^:]:[^: ]', line) or
  2440. Search('for *\(.*[^: ]:[^:]', line)):
  2441. error(filename, linenum, 'whitespace/forcolon', 2,
  2442. 'Missing space around colon in range-based for loop')
  2443. def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
  2444. """Checks for additional blank line issues related to sections.
  2445. Currently the only thing checked here is blank line before protected/private.
  2446. Args:
  2447. filename: The name of the current file.
  2448. clean_lines: A CleansedLines instance containing the file.
  2449. class_info: A _ClassInfo objects.
  2450. linenum: The number of the line to check.
  2451. error: The function to call with any errors found.
  2452. """
  2453. # Skip checks if the class is small, where small means 25 lines or less.
  2454. # 25 lines seems like a good cutoff since that's the usual height of
  2455. # terminals, and any class that can't fit in one screen can't really
  2456. # be considered "small".
  2457. #
  2458. # Also skip checks if we are on the first line. This accounts for
  2459. # classes that look like
  2460. # class Foo { public: ... };
  2461. #
  2462. # If we didn't find the end of the class, last_line would be zero,
  2463. # and the check will be skipped by the first condition.
  2464. if (class_info.last_line - class_info.starting_linenum <= 24 or
  2465. linenum <= class_info.starting_linenum):
  2466. return
  2467. matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
  2468. if matched:
  2469. # Issue warning if the line before public/protected/private was
  2470. # not a blank line, but don't do this if the previous line contains
  2471. # "class" or "struct". This can happen two ways:
  2472. # - We are at the beginning of the class.
  2473. # - We are forward-declaring an inner class that is semantically
  2474. # private, but needed to be public for implementation reasons.
  2475. # Also ignores cases where the previous line ends with a backslash as can be
  2476. # common when defining classes in C macros.
  2477. prev_line = clean_lines.lines[linenum - 1]
  2478. if (not IsBlankLine(prev_line) and
  2479. not Search(r'\b(class|struct)\b', prev_line) and
  2480. not Search(r'\\$', prev_line)):
  2481. # Try a bit harder to find the beginning of the class. This is to
  2482. # account for multi-line base-specifier lists, e.g.:
  2483. # class Derived
  2484. # : public Base {
  2485. end_class_head = class_info.starting_linenum
  2486. for i in range(class_info.starting_linenum, linenum):
  2487. if Search(r'\{\s*$', clean_lines.lines[i]):
  2488. end_class_head = i
  2489. break
  2490. if end_class_head < linenum - 1:
  2491. error(filename, linenum, 'whitespace/blank_line', 3,
  2492. '"%s:" should be preceded by a blank line' % matched.group(1))
  2493. def GetPreviousNonBlankLine(clean_lines, linenum):
  2494. """Return the most recent non-blank line and its line number.
  2495. Args:
  2496. clean_lines: A CleansedLines instance containing the file contents.
  2497. linenum: The number of the line to check.
  2498. Returns:
  2499. A tuple with two elements. The first element is the contents of the last
  2500. non-blank line before the current line, or the empty string if this is the
  2501. first non-blank line. The second is the line number of that line, or -1
  2502. if this is the first non-blank line.
  2503. """
  2504. prevlinenum = linenum - 1
  2505. while prevlinenum >= 0:
  2506. prevline = clean_lines.elided[prevlinenum]
  2507. if not IsBlankLine(prevline): # if not a blank line...
  2508. return (prevline, prevlinenum)
  2509. prevlinenum -= 1
  2510. return ('', -1)
  2511. def CheckBraces(filename, clean_lines, linenum, error):
  2512. """Looks for misplaced braces (e.g. at the end of line).
  2513. Args:
  2514. filename: The name of the current file.
  2515. clean_lines: A CleansedLines instance containing the file.
  2516. linenum: The number of the line to check.
  2517. error: The function to call with any errors found.
  2518. """
  2519. line = clean_lines.elided[linenum] # get rid of comments and strings
  2520. if Match(r'\s*{\s*$', line):
  2521. # We allow an open brace to start a line in the case where someone is using
  2522. # braces in a block to explicitly create a new scope, which is commonly used
  2523. # to control the lifetime of stack-allocated variables. Braces are also
  2524. # used for brace initializers inside function calls. We don't detect this
  2525. # perfectly: we just don't complain if the last non-whitespace character on
  2526. # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
  2527. # previous line starts a preprocessor block.
  2528. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  2529. if (not Search(r'[,;:}{(]\s*$', prevline) and
  2530. not Match(r'\s*#', prevline)):
  2531. error(filename, linenum, 'whitespace/braces', 4,
  2532. '{ should almost always be at the end of the previous line')
  2533. # An else clause should be on the same line as the preceding closing brace.
  2534. if Match(r'\s*else\s*', line):
  2535. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  2536. if Match(r'\s*}\s*$', prevline):
  2537. error(filename, linenum, 'whitespace/newline', 4,
  2538. 'An else should appear on the same line as the preceding }')
  2539. # If braces come on one side of an else, they should be on both.
  2540. # However, we have to worry about "else if" that spans multiple lines!
  2541. if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
  2542. if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if
  2543. # find the ( after the if
  2544. pos = line.find('else if')
  2545. pos = line.find('(', pos)
  2546. if pos > 0:
  2547. (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
  2548. if endline[endpos:].find('{') == -1: # must be brace after if
  2549. error(filename, linenum, 'readability/braces', 5,
  2550. 'If an else has a brace on one side, it should have it on both')
  2551. else: # common case: else not followed by a multi-line if
  2552. error(filename, linenum, 'readability/braces', 5,
  2553. 'If an else has a brace on one side, it should have it on both')
  2554. # Likewise, an else should never have the else clause on the same line
  2555. if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
  2556. error(filename, linenum, 'whitespace/newline', 4,
  2557. 'Else clause should never be on same line as else (use 2 lines)')
  2558. # In the same way, a do/while should never be on one line
  2559. if Match(r'\s*do [^\s{]', line):
  2560. error(filename, linenum, 'whitespace/newline', 4,
  2561. 'do/while clauses should not be on a single line')
  2562. # Block bodies should not be followed by a semicolon. Due to C++11
  2563. # brace initialization, there are more places where semicolons are
  2564. # required than not, so we use a whitelist approach to check these
  2565. # rather than a blacklist. These are the places where "};" should
  2566. # be replaced by just "}":
  2567. # 1. Some flavor of block following closing parenthesis:
  2568. # for (;;) {};
  2569. # while (...) {};
  2570. # switch (...) {};
  2571. # Function(...) {};
  2572. # if (...) {};
  2573. # if (...) else if (...) {};
  2574. #
  2575. # 2. else block:
  2576. # if (...) else {};
  2577. #
  2578. # 3. const member function:
  2579. # Function(...) const {};
  2580. #
  2581. # 4. Block following some statement:
  2582. # x = 42;
  2583. # {};
  2584. #
  2585. # 5. Block at the beginning of a function:
  2586. # Function(...) {
  2587. # {};
  2588. # }
  2589. #
  2590. # Note that naively checking for the preceding "{" will also match
  2591. # braces inside multi-dimensional arrays, but this is fine since
  2592. # that expression will not contain semicolons.
  2593. #
  2594. # 6. Block following another block:
  2595. # while (true) {}
  2596. # {};
  2597. #
  2598. # 7. End of namespaces:
  2599. # namespace {};
  2600. #
  2601. # These semicolons seems far more common than other kinds of
  2602. # redundant semicolons, possibly due to people converting classes
  2603. # to namespaces. For now we do not warn for this case.
  2604. #
  2605. # Try matching case 1 first.
  2606. match = Match(r'^(.*\)\s*)\{', line)
  2607. if match:
  2608. # Matched closing parenthesis (case 1). Check the token before the
  2609. # matching opening parenthesis, and don't warn if it looks like a
  2610. # macro. This avoids these false positives:
  2611. # - macro that defines a base class
  2612. # - multi-line macro that defines a base class
  2613. # - macro that defines the whole class-head
  2614. #
  2615. # But we still issue warnings for macros that we know are safe to
  2616. # warn, specifically:
  2617. # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
  2618. # - TYPED_TEST
  2619. # - INTERFACE_DEF
  2620. # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
  2621. #
  2622. # We implement a whitelist of safe macros instead of a blacklist of
  2623. # unsafe macros, even though the latter appears less frequently in
  2624. # google code and would have been easier to implement. This is because
  2625. # the downside for getting the whitelist wrong means some extra
  2626. # semicolons, while the downside for getting the blacklist wrong
  2627. # would result in compile errors.
  2628. #
  2629. # In addition to macros, we also don't want to warn on compound
  2630. # literals.
  2631. closing_brace_pos = match.group(1).rfind(')')
  2632. opening_parenthesis = ReverseCloseExpression(
  2633. clean_lines, linenum, closing_brace_pos)
  2634. if opening_parenthesis[2] > -1:
  2635. line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
  2636. macro = Search(r'\b([A-Z_]+)\s*$', line_prefix)
  2637. if ((macro and
  2638. macro.group(1) not in (
  2639. 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
  2640. 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
  2641. 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
  2642. Search(r'\s+=\s*$', line_prefix)):
  2643. match = None
  2644. else:
  2645. # Try matching cases 2-3.
  2646. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
  2647. if not match:
  2648. # Try matching cases 4-6. These are always matched on separate lines.
  2649. #
  2650. # Note that we can't simply concatenate the previous line to the
  2651. # current line and do a single match, otherwise we may output
  2652. # duplicate warnings for the blank line case:
  2653. # if (cond) {
  2654. # // blank line
  2655. # }
  2656. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  2657. if prevline and Search(r'[;{}]\s*$', prevline):
  2658. match = Match(r'^(\s*)\{', line)
  2659. # Check matching closing brace
  2660. if match:
  2661. (endline, endlinenum, endpos) = CloseExpression(
  2662. clean_lines, linenum, len(match.group(1)))
  2663. if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
  2664. # Current {} pair is eligible for semicolon check, and we have found
  2665. # the redundant semicolon, output warning here.
  2666. #
  2667. # Note: because we are scanning forward for opening braces, and
  2668. # outputting warnings for the matching closing brace, if there are
  2669. # nested blocks with trailing semicolons, we will get the error
  2670. # messages in reversed order.
  2671. error(filename, endlinenum, 'readability/braces', 4,
  2672. "You don't need a ; after a }")
  2673. def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
  2674. """Look for empty loop/conditional body with only a single semicolon.
  2675. Args:
  2676. filename: The name of the current file.
  2677. clean_lines: A CleansedLines instance containing the file.
  2678. linenum: The number of the line to check.
  2679. error: The function to call with any errors found.
  2680. """
  2681. # Search for loop keywords at the beginning of the line. Because only
  2682. # whitespaces are allowed before the keywords, this will also ignore most
  2683. # do-while-loops, since those lines should start with closing brace.
  2684. #
  2685. # We also check "if" blocks here, since an empty conditional block
  2686. # is likely an error.
  2687. line = clean_lines.elided[linenum]
  2688. matched = Match(r'\s*(for|while|if)\s*\(', line)
  2689. if matched:
  2690. # Find the end of the conditional expression
  2691. (end_line, end_linenum, end_pos) = CloseExpression(
  2692. clean_lines, linenum, line.find('('))
  2693. # Output warning if what follows the condition expression is a semicolon.
  2694. # No warning for all other cases, including whitespace or newline, since we
  2695. # have a separate check for semicolons preceded by whitespace.
  2696. if end_pos >= 0 and Match(r';', end_line[end_pos:]):
  2697. if matched.group(1) == 'if':
  2698. error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
  2699. 'Empty conditional bodies should use {}')
  2700. else:
  2701. error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
  2702. 'Empty loop bodies should use {} or continue')
  2703. def CheckCheck(filename, clean_lines, linenum, error):
  2704. """Checks the use of CHECK and EXPECT macros.
  2705. Args:
  2706. filename: The name of the current file.
  2707. clean_lines: A CleansedLines instance containing the file.
  2708. linenum: The number of the line to check.
  2709. error: The function to call with any errors found.
  2710. """
  2711. # Decide the set of replacement macros that should be suggested
  2712. lines = clean_lines.elided
  2713. check_macro = None
  2714. start_pos = -1
  2715. for macro in _CHECK_MACROS:
  2716. i = lines[linenum].find(macro)
  2717. if i >= 0:
  2718. check_macro = macro
  2719. # Find opening parenthesis. Do a regular expression match here
  2720. # to make sure that we are matching the expected CHECK macro, as
  2721. # opposed to some other macro that happens to contain the CHECK
  2722. # substring.
  2723. matched = Match(r'^(.*\b' + check_macro + r'\s*)\(', lines[linenum])
  2724. if not matched:
  2725. continue
  2726. start_pos = len(matched.group(1))
  2727. break
  2728. if not check_macro or start_pos < 0:
  2729. # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'
  2730. return
  2731. # Find end of the boolean expression by matching parentheses
  2732. (last_line, end_line, end_pos) = CloseExpression(
  2733. clean_lines, linenum, start_pos)
  2734. if end_pos < 0:
  2735. return
  2736. if linenum == end_line:
  2737. expression = lines[linenum][start_pos + 1:end_pos - 1]
  2738. else:
  2739. expression = lines[linenum][start_pos + 1:]
  2740. for i in xrange(linenum + 1, end_line):
  2741. expression += lines[i]
  2742. expression += last_line[0:end_pos - 1]
  2743. # Parse expression so that we can take parentheses into account.
  2744. # This avoids false positives for inputs like "CHECK((a < 4) == b)",
  2745. # which is not replaceable by CHECK_LE.
  2746. lhs = ''
  2747. rhs = ''
  2748. operator = None
  2749. while expression:
  2750. matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
  2751. r'==|!=|>=|>|<=|<|\()(.*)$', expression)
  2752. if matched:
  2753. token = matched.group(1)
  2754. if token == '(':
  2755. # Parenthesized operand
  2756. expression = matched.group(2)
  2757. (end, _) = FindEndOfExpressionInLine(expression, 0, 1, '(', ')')
  2758. if end < 0:
  2759. return # Unmatched parenthesis
  2760. lhs += '(' + expression[0:end]
  2761. expression = expression[end:]
  2762. elif token in ('&&', '||'):
  2763. # Logical and/or operators. This means the expression
  2764. # contains more than one term, for example:
  2765. # CHECK(42 < a && a < b);
  2766. #
  2767. # These are not replaceable with CHECK_LE, so bail out early.
  2768. return
  2769. elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
  2770. # Non-relational operator
  2771. lhs += token
  2772. expression = matched.group(2)
  2773. else:
  2774. # Relational operator
  2775. operator = token
  2776. rhs = matched.group(2)
  2777. break
  2778. else:
  2779. # Unparenthesized operand. Instead of appending to lhs one character
  2780. # at a time, we do another regular expression match to consume several
  2781. # characters at once if possible. Trivial benchmark shows that this
  2782. # is more efficient when the operands are longer than a single
  2783. # character, which is generally the case.
  2784. matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
  2785. if not matched:
  2786. matched = Match(r'^(\s*\S)(.*)$', expression)
  2787. if not matched:
  2788. break
  2789. lhs += matched.group(1)
  2790. expression = matched.group(2)
  2791. # Only apply checks if we got all parts of the boolean expression
  2792. if not (lhs and operator and rhs):
  2793. return
  2794. # Check that rhs do not contain logical operators. We already know
  2795. # that lhs is fine since the loop above parses out && and ||.
  2796. if rhs.find('&&') > -1 or rhs.find('||') > -1:
  2797. return
  2798. # At least one of the operands must be a constant literal. This is
  2799. # to avoid suggesting replacements for unprintable things like
  2800. # CHECK(variable != iterator)
  2801. #
  2802. # The following pattern matches decimal, hex integers, strings, and
  2803. # characters (in that order).
  2804. lhs = lhs.strip()
  2805. rhs = rhs.strip()
  2806. match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
  2807. if Match(match_constant, lhs) or Match(match_constant, rhs):
  2808. # Note: since we know both lhs and rhs, we can provide a more
  2809. # descriptive error message like:
  2810. # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
  2811. # Instead of:
  2812. # Consider using CHECK_EQ instead of CHECK(a == b)
  2813. #
  2814. # We are still keeping the less descriptive message because if lhs
  2815. # or rhs gets long, the error message might become unreadable.
  2816. error(filename, linenum, 'readability/check', 2,
  2817. 'Consider using %s instead of %s(a %s b)' % (
  2818. _CHECK_REPLACEMENT[check_macro][operator],
  2819. check_macro, operator))
  2820. def CheckAltTokens(filename, clean_lines, linenum, error):
  2821. """Check alternative keywords being used in boolean expressions.
  2822. Args:
  2823. filename: The name of the current file.
  2824. clean_lines: A CleansedLines instance containing the file.
  2825. linenum: The number of the line to check.
  2826. error: The function to call with any errors found.
  2827. """
  2828. line = clean_lines.elided[linenum]
  2829. # Avoid preprocessor lines
  2830. if Match(r'^\s*#', line):
  2831. return
  2832. # Last ditch effort to avoid multi-line comments. This will not help
  2833. # if the comment started before the current line or ended after the
  2834. # current line, but it catches most of the false positives. At least,
  2835. # it provides a way to workaround this warning for people who use
  2836. # multi-line comments in preprocessor macros.
  2837. #
  2838. # TODO(unknown): remove this once cpplint has better support for
  2839. # multi-line comments.
  2840. if line.find('/*') >= 0 or line.find('*/') >= 0:
  2841. return
  2842. for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
  2843. error(filename, linenum, 'readability/alt_tokens', 2,
  2844. 'Use operator %s instead of %s' % (
  2845. _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
  2846. def GetLineWidth(line):
  2847. """Determines the width of the line in column positions.
  2848. Args:
  2849. line: A string, which may be a Unicode string.
  2850. Returns:
  2851. The width of the line in column positions, accounting for Unicode
  2852. combining characters and wide characters.
  2853. """
  2854. if isinstance(line, unicode):
  2855. width = 0
  2856. for uc in unicodedata.normalize('NFC', line):
  2857. if unicodedata.east_asian_width(uc) in ('W', 'F'):
  2858. width += 2
  2859. elif not unicodedata.combining(uc):
  2860. width += 1
  2861. return width
  2862. else:
  2863. return len(line)
  2864. def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
  2865. error):
  2866. """Checks rules from the 'C++ style rules' section of cppguide.html.
  2867. Most of these rules are hard to test (naming, comment style), but we
  2868. do what we can. In particular we check for 2-space indents, line lengths,
  2869. tab usage, spaces inside code, etc.
  2870. Args:
  2871. filename: The name of the current file.
  2872. clean_lines: A CleansedLines instance containing the file.
  2873. linenum: The number of the line to check.
  2874. file_extension: The extension (without the dot) of the filename.
  2875. nesting_state: A _NestingState instance which maintains information about
  2876. the current stack of nested blocks being parsed.
  2877. error: The function to call with any errors found.
  2878. """
  2879. # Don't use "elided" lines here, otherwise we can't check commented lines.
  2880. # Don't want to use "raw" either, because we don't want to check inside C++11
  2881. # raw strings,
  2882. raw_lines = clean_lines.lines_without_raw_strings
  2883. line = raw_lines[linenum]
  2884. if line.find('\t') != -1:
  2885. error(filename, linenum, 'whitespace/tab', 1,
  2886. 'Tab found; better to use spaces')
  2887. # One or three blank spaces at the beginning of the line is weird; it's
  2888. # hard to reconcile that with 2-space indents.
  2889. # NOTE: here are the conditions rob pike used for his tests. Mine aren't
  2890. # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
  2891. # if(RLENGTH > 20) complain = 0;
  2892. # if(match($0, " +(error|private|public|protected):")) complain = 0;
  2893. # if(match(prev, "&& *$")) complain = 0;
  2894. # if(match(prev, "\\|\\| *$")) complain = 0;
  2895. # if(match(prev, "[\",=><] *$")) complain = 0;
  2896. # if(match($0, " <<")) complain = 0;
  2897. # if(match(prev, " +for \\(")) complain = 0;
  2898. # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
  2899. initial_spaces = 0
  2900. cleansed_line = clean_lines.elided[linenum]
  2901. while initial_spaces < len(line) and line[initial_spaces] == ' ':
  2902. initial_spaces += 1
  2903. if line and line[-1].isspace():
  2904. error(filename, linenum, 'whitespace/end_of_line', 4,
  2905. 'Line ends in whitespace. Consider deleting these extra spaces.')
  2906. # There are certain situations we allow one space, notably for section labels
  2907. elif ((initial_spaces == 1 or initial_spaces == 3) and
  2908. not Match(r'\s*\w+\s*:\s*$', cleansed_line)):
  2909. error(filename, linenum, 'whitespace/indent', 3,
  2910. 'Weird number of spaces at line-start. '
  2911. 'Are you using a 2-space indent?')
  2912. # Check if the line is a header guard.
  2913. is_header_guard = False
  2914. if file_extension == 'h':
  2915. cppvar = GetHeaderGuardCPPVariable(filename)
  2916. if (line.startswith('#ifndef %s' % cppvar) or
  2917. line.startswith('#define %s' % cppvar) or
  2918. line.startswith('#endif // %s' % cppvar)):
  2919. is_header_guard = True
  2920. # #include lines and header guards can be long, since there's no clean way to
  2921. # split them.
  2922. #
  2923. # URLs can be long too. It's possible to split these, but it makes them
  2924. # harder to cut&paste.
  2925. #
  2926. # The "$Id:...$" comment may also get very long without it being the
  2927. # developers fault.
  2928. if (not line.startswith('#include') and not is_header_guard and
  2929. not Match(r'^\s*//.*http(s?)://\S*$', line) and
  2930. not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
  2931. line_width = GetLineWidth(line)
  2932. extended_length = int((_line_length * 1.25))
  2933. if line_width > extended_length:
  2934. error(filename, linenum, 'whitespace/line_length', 4,
  2935. 'Lines should very rarely be longer than %i characters' %
  2936. extended_length)
  2937. elif line_width > _line_length:
  2938. error(filename, linenum, 'whitespace/line_length', 2,
  2939. 'Lines should be <= %i characters long' % _line_length)
  2940. if (cleansed_line.count(';') > 1 and
  2941. # for loops are allowed two ;'s (and may run over two lines).
  2942. cleansed_line.find('for') == -1 and
  2943. (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
  2944. GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
  2945. # It's ok to have many commands in a switch case that fits in 1 line
  2946. not ((cleansed_line.find('case ') != -1 or
  2947. cleansed_line.find('default:') != -1) and
  2948. cleansed_line.find('break;') != -1)):
  2949. error(filename, linenum, 'whitespace/newline', 0,
  2950. 'More than one command on the same line')
  2951. # Some more style checks
  2952. CheckBraces(filename, clean_lines, linenum, error)
  2953. CheckEmptyBlockBody(filename, clean_lines, linenum, error)
  2954. CheckAccess(filename, clean_lines, linenum, nesting_state, error)
  2955. CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
  2956. CheckCheck(filename, clean_lines, linenum, error)
  2957. CheckAltTokens(filename, clean_lines, linenum, error)
  2958. classinfo = nesting_state.InnermostClass()
  2959. if classinfo:
  2960. CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
  2961. _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"')
  2962. _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
  2963. # Matches the first component of a filename delimited by -s and _s. That is:
  2964. # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
  2965. # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
  2966. # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
  2967. # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
  2968. _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
  2969. def _DropCommonSuffixes(filename):
  2970. """Drops common suffixes like _test.cc or -inl.h from filename.
  2971. For example:
  2972. >>> _DropCommonSuffixes('foo/foo-inl.h')
  2973. 'foo/foo'
  2974. >>> _DropCommonSuffixes('foo/bar/foo.cc')
  2975. 'foo/bar/foo'
  2976. >>> _DropCommonSuffixes('foo/foo_internal.h')
  2977. 'foo/foo'
  2978. >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
  2979. 'foo/foo_unusualinternal'
  2980. Args:
  2981. filename: The input filename.
  2982. Returns:
  2983. The filename with the common suffix removed.
  2984. """
  2985. for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
  2986. 'inl.h', 'impl.h', 'internal.h'):
  2987. if (filename.endswith(suffix) and len(filename) > len(suffix) and
  2988. filename[-len(suffix) - 1] in ('-', '_')):
  2989. return filename[:-len(suffix) - 1]
  2990. return os.path.splitext(filename)[0]
  2991. def _IsTestFilename(filename):
  2992. """Determines if the given filename has a suffix that identifies it as a test.
  2993. Args:
  2994. filename: The input filename.
  2995. Returns:
  2996. True if 'filename' looks like a test, False otherwise.
  2997. """
  2998. if (filename.endswith('_test.cc') or
  2999. filename.endswith('_unittest.cc') or
  3000. filename.endswith('_regtest.cc')):
  3001. return True
  3002. else:
  3003. return False
  3004. def _ClassifyInclude(fileinfo, include, is_system):
  3005. """Figures out what kind of header 'include' is.
  3006. Args:
  3007. fileinfo: The current file cpplint is running over. A FileInfo instance.
  3008. include: The path to a #included file.
  3009. is_system: True if the #include used <> rather than "".
  3010. Returns:
  3011. One of the _XXX_HEADER constants.
  3012. For example:
  3013. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
  3014. _C_SYS_HEADER
  3015. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
  3016. _CPP_SYS_HEADER
  3017. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
  3018. _LIKELY_MY_HEADER
  3019. >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
  3020. ... 'bar/foo_other_ext.h', False)
  3021. _POSSIBLE_MY_HEADER
  3022. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
  3023. _OTHER_HEADER
  3024. """
  3025. # This is a list of all standard c++ header files, except
  3026. # those already checked for above.
  3027. is_cpp_h = include in _CPP_HEADERS
  3028. if is_system:
  3029. if is_cpp_h:
  3030. return _CPP_SYS_HEADER
  3031. else:
  3032. return _C_SYS_HEADER
  3033. # If the target file and the include we're checking share a
  3034. # basename when we drop common extensions, and the include
  3035. # lives in . , then it's likely to be owned by the target file.
  3036. target_dir, target_base = (
  3037. os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
  3038. include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
  3039. if target_base == include_base and (
  3040. include_dir == target_dir or
  3041. include_dir == os.path.normpath(target_dir + '/../public')):
  3042. return _LIKELY_MY_HEADER
  3043. # If the target and include share some initial basename
  3044. # component, it's possible the target is implementing the
  3045. # include, so it's allowed to be first, but we'll never
  3046. # complain if it's not there.
  3047. target_first_component = _RE_FIRST_COMPONENT.match(target_base)
  3048. include_first_component = _RE_FIRST_COMPONENT.match(include_base)
  3049. if (target_first_component and include_first_component and
  3050. target_first_component.group(0) ==
  3051. include_first_component.group(0)):
  3052. return _POSSIBLE_MY_HEADER
  3053. return _OTHER_HEADER
  3054. def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
  3055. """Check rules that are applicable to #include lines.
  3056. Strings on #include lines are NOT removed from elided line, to make
  3057. certain tasks easier. However, to prevent false positives, checks
  3058. applicable to #include lines in CheckLanguage must be put here.
  3059. Args:
  3060. filename: The name of the current file.
  3061. clean_lines: A CleansedLines instance containing the file.
  3062. linenum: The number of the line to check.
  3063. include_state: An _IncludeState instance in which the headers are inserted.
  3064. error: The function to call with any errors found.
  3065. """
  3066. fileinfo = FileInfo(filename)
  3067. line = clean_lines.lines[linenum]
  3068. # "include" should use the new style "foo/bar.h" instead of just "bar.h"
  3069. if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line):
  3070. error(filename, linenum, 'build/include', 4,
  3071. 'Include the directory when naming .h files')
  3072. # we shouldn't include a file more than once. actually, there are a
  3073. # handful of instances where doing so is okay, but in general it's
  3074. # not.
  3075. match = _RE_PATTERN_INCLUDE.search(line)
  3076. if match:
  3077. include = match.group(2)
  3078. is_system = (match.group(1) == '<')
  3079. if include in include_state:
  3080. error(filename, linenum, 'build/include', 4,
  3081. '"%s" already included at %s:%s' %
  3082. (include, filename, include_state[include]))
  3083. else:
  3084. include_state[include] = linenum
  3085. # We want to ensure that headers appear in the right order:
  3086. # 1) for foo.cc, foo.h (preferred location)
  3087. # 2) c system files
  3088. # 3) cpp system files
  3089. # 4) for foo.cc, foo.h (deprecated location)
  3090. # 5) other google headers
  3091. #
  3092. # We classify each include statement as one of those 5 types
  3093. # using a number of techniques. The include_state object keeps
  3094. # track of the highest type seen, and complains if we see a
  3095. # lower type after that.
  3096. error_message = include_state.CheckNextIncludeOrder(
  3097. _ClassifyInclude(fileinfo, include, is_system))
  3098. if error_message:
  3099. error(filename, linenum, 'build/include_order', 4,
  3100. '%s. Should be: %s.h, c system, c++ system, other.' %
  3101. (error_message, fileinfo.BaseName()))
  3102. canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
  3103. if not include_state.IsInAlphabeticalOrder(
  3104. clean_lines, linenum, canonical_include):
  3105. error(filename, linenum, 'build/include_alpha', 4,
  3106. 'Include "%s" not in alphabetical order' % include)
  3107. include_state.SetLastHeader(canonical_include)
  3108. # Look for any of the stream classes that are part of standard C++.
  3109. match = _RE_PATTERN_INCLUDE.match(line)
  3110. if match:
  3111. include = match.group(2)
  3112. if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
  3113. # Many unit tests use cout, so we exempt them.
  3114. if not _IsTestFilename(filename):
  3115. error(filename, linenum, 'readability/streams', 3,
  3116. 'Streams are highly discouraged.')
  3117. def _GetTextInside(text, start_pattern):
  3118. r"""Retrieves all the text between matching open and close parentheses.
  3119. Given a string of lines and a regular expression string, retrieve all the text
  3120. following the expression and between opening punctuation symbols like
  3121. (, [, or {, and the matching close-punctuation symbol. This properly nested
  3122. occurrences of the punctuations, so for the text like
  3123. printf(a(), b(c()));
  3124. a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
  3125. start_pattern must match string having an open punctuation symbol at the end.
  3126. Args:
  3127. text: The lines to extract text. Its comments and strings must be elided.
  3128. It can be single line and can span multiple lines.
  3129. start_pattern: The regexp string indicating where to start extracting
  3130. the text.
  3131. Returns:
  3132. The extracted text.
  3133. None if either the opening string or ending punctuation could not be found.
  3134. """
  3135. # TODO(sugawarayu): Audit cpplint.py to see what places could be profitably
  3136. # rewritten to use _GetTextInside (and use inferior regexp matching today).
  3137. # Give opening punctuations to get the matching close-punctuations.
  3138. matching_punctuation = {'(': ')', '{': '}', '[': ']'}
  3139. closing_punctuation = set(matching_punctuation.itervalues())
  3140. # Find the position to start extracting text.
  3141. match = re.search(start_pattern, text, re.M)
  3142. if not match: # start_pattern not found in text.
  3143. return None
  3144. start_position = match.end(0)
  3145. assert start_position > 0, (
  3146. 'start_pattern must ends with an opening punctuation.')
  3147. assert text[start_position - 1] in matching_punctuation, (
  3148. 'start_pattern must ends with an opening punctuation.')
  3149. # Stack of closing punctuations we expect to have in text after position.
  3150. punctuation_stack = [matching_punctuation[text[start_position - 1]]]
  3151. position = start_position
  3152. while punctuation_stack and position < len(text):
  3153. if text[position] == punctuation_stack[-1]:
  3154. punctuation_stack.pop()
  3155. elif text[position] in closing_punctuation:
  3156. # A closing punctuation without matching opening punctuations.
  3157. return None
  3158. elif text[position] in matching_punctuation:
  3159. punctuation_stack.append(matching_punctuation[text[position]])
  3160. position += 1
  3161. if punctuation_stack:
  3162. # Opening punctuations left without matching close-punctuations.
  3163. return None
  3164. # punctuations match.
  3165. return text[start_position:position - 1]
  3166. # Patterns for matching call-by-reference parameters.
  3167. #
  3168. # Supports nested templates up to 2 levels deep using this messy pattern:
  3169. # < (?: < (?: < [^<>]*
  3170. # >
  3171. # | [^<>] )*
  3172. # >
  3173. # | [^<>] )*
  3174. # >
  3175. _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
  3176. _RE_PATTERN_TYPE = (
  3177. r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
  3178. r'(?:\w|'
  3179. r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
  3180. r'::)+')
  3181. # A call-by-reference parameter ends with '& identifier'.
  3182. _RE_PATTERN_REF_PARAM = re.compile(
  3183. r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
  3184. r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
  3185. # A call-by-const-reference parameter either ends with 'const& identifier'
  3186. # or looks like 'const type& identifier' when 'type' is atomic.
  3187. _RE_PATTERN_CONST_REF_PARAM = (
  3188. r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
  3189. r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
  3190. def CheckLanguage(filename, clean_lines, linenum, file_extension,
  3191. include_state, nesting_state, error):
  3192. """Checks rules from the 'C++ language rules' section of cppguide.html.
  3193. Some of these rules are hard to test (function overloading, using
  3194. uint32 inappropriately), but we do the best we can.
  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. file_extension: The extension (without the dot) of the filename.
  3200. include_state: An _IncludeState instance in which the headers are inserted.
  3201. nesting_state: A _NestingState instance which maintains information about
  3202. the current stack of nested blocks being parsed.
  3203. error: The function to call with any errors found.
  3204. """
  3205. # If the line is empty or consists of entirely a comment, no need to
  3206. # check it.
  3207. line = clean_lines.elided[linenum]
  3208. if not line:
  3209. return
  3210. match = _RE_PATTERN_INCLUDE.search(line)
  3211. if match:
  3212. CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
  3213. return
  3214. # Reset include state across preprocessor directives. This is meant
  3215. # to silence warnings for conditional includes.
  3216. if Match(r'^\s*#\s*(?:ifdef|elif|else|endif)\b', line):
  3217. include_state.ResetSection()
  3218. # Make Windows paths like Unix.
  3219. fullname = os.path.abspath(filename).replace('\\', '/')
  3220. # TODO(unknown): figure out if they're using default arguments in fn proto.
  3221. # Check to see if they're using an conversion function cast.
  3222. # I just try to capture the most common basic types, though there are more.
  3223. # Parameterless conversion functions, such as bool(), are allowed as they are
  3224. # probably a member operator declaration or default constructor.
  3225. match = Search(
  3226. r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there
  3227. r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
  3228. r'(\([^)].*)', line)
  3229. if match:
  3230. matched_new = match.group(1)
  3231. matched_type = match.group(2)
  3232. matched_funcptr = match.group(3)
  3233. # gMock methods are defined using some variant of MOCK_METHODx(name, type)
  3234. # where type may be float(), int(string), etc. Without context they are
  3235. # virtually indistinguishable from int(x) casts. Likewise, gMock's
  3236. # MockCallback takes a template parameter of the form return_type(arg_type),
  3237. # which looks much like the cast we're trying to detect.
  3238. #
  3239. # std::function<> wrapper has a similar problem.
  3240. #
  3241. # Return types for function pointers also look like casts if they
  3242. # don't have an extra space.
  3243. if (matched_new is None and # If new operator, then this isn't a cast
  3244. not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
  3245. Search(r'\bMockCallback<.*>', line) or
  3246. Search(r'\bstd::function<.*>', line)) and
  3247. not (matched_funcptr and
  3248. Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
  3249. matched_funcptr))):
  3250. # Try a bit harder to catch gmock lines: the only place where
  3251. # something looks like an old-style cast is where we declare the
  3252. # return type of the mocked method, and the only time when we
  3253. # are missing context is if MOCK_METHOD was split across
  3254. # multiple lines. The missing MOCK_METHOD is usually one or two
  3255. # lines back, so scan back one or two lines.
  3256. #
  3257. # It's not possible for gmock macros to appear in the first 2
  3258. # lines, since the class head + section name takes up 2 lines.
  3259. if (linenum < 2 or
  3260. not (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
  3261. clean_lines.elided[linenum - 1]) or
  3262. Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
  3263. clean_lines.elided[linenum - 2]))):
  3264. error(filename, linenum, 'readability/casting', 4,
  3265. 'Using deprecated casting style. '
  3266. 'Use static_cast<%s>(...) instead' %
  3267. matched_type)
  3268. CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  3269. 'static_cast',
  3270. r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
  3271. # This doesn't catch all cases. Consider (const char * const)"hello".
  3272. #
  3273. # (char *) "foo" should always be a const_cast (reinterpret_cast won't
  3274. # compile).
  3275. if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  3276. 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error):
  3277. pass
  3278. else:
  3279. # Check pointer casts for other than string constants
  3280. CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  3281. 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
  3282. # In addition, we look for people taking the address of a cast. This
  3283. # is dangerous -- casts can assign to temporaries, so the pointer doesn't
  3284. # point where you think.
  3285. match = Search(
  3286. r'(?:&\(([^)]+)\)[\w(])|'
  3287. r'(?:&(static|dynamic|down|reinterpret)_cast\b)', line)
  3288. if match and match.group(1) != '*':
  3289. error(filename, linenum, 'runtime/casting', 4,
  3290. ('Are you taking an address of a cast? '
  3291. 'This is dangerous: could be a temp var. '
  3292. 'Take the address before doing the cast, rather than after'))
  3293. # Create an extended_line, which is the concatenation of the current and
  3294. # next lines, for more effective checking of code that may span more than one
  3295. # line.
  3296. if linenum + 1 < clean_lines.NumLines():
  3297. extended_line = line + clean_lines.elided[linenum + 1]
  3298. else:
  3299. extended_line = line
  3300. # Check for people declaring static/global STL strings at the top level.
  3301. # This is dangerous because the C++ language does not guarantee that
  3302. # globals with constructors are initialized before the first access.
  3303. match = Match(
  3304. r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
  3305. line)
  3306. # Make sure it's not a function.
  3307. # Function template specialization looks like: "string foo<Type>(...".
  3308. # Class template definitions look like: "string Foo<Type>::Method(...".
  3309. #
  3310. # Also ignore things that look like operators. These are matched separately
  3311. # because operator names cross non-word boundaries. If we change the pattern
  3312. # above, we would decrease the accuracy of matching identifiers.
  3313. if (match and
  3314. not Search(r'\boperator\W', line) and
  3315. not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)', match.group(3))):
  3316. error(filename, linenum, 'runtime/string', 4,
  3317. 'For a static/global string constant, use a C style string instead: '
  3318. '"%schar %s[]".' %
  3319. (match.group(1), match.group(2)))
  3320. if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
  3321. error(filename, linenum, 'runtime/init', 4,
  3322. 'You seem to be initializing a member variable with itself.')
  3323. if file_extension == 'h':
  3324. # TODO(unknown): check that 1-arg constructors are explicit.
  3325. # How to tell it's a constructor?
  3326. # (handled in CheckForNonStandardConstructs for now)
  3327. # TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS
  3328. # (level 1 error)
  3329. pass
  3330. # Check if people are using the verboten C basic types. The only exception
  3331. # we regularly allow is "unsigned short port" for port.
  3332. if Search(r'\bshort port\b', line):
  3333. if not Search(r'\bunsigned short port\b', line):
  3334. error(filename, linenum, 'runtime/int', 4,
  3335. 'Use "unsigned short" for ports, not "short"')
  3336. else:
  3337. match = Search(r'\b(short|long(?! +double)|long long)\b', line)
  3338. if match:
  3339. error(filename, linenum, 'runtime/int', 4,
  3340. 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
  3341. # When snprintf is used, the second argument shouldn't be a literal.
  3342. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
  3343. if match and match.group(2) != '0':
  3344. # If 2nd arg is zero, snprintf is used to calculate size.
  3345. error(filename, linenum, 'runtime/printf', 3,
  3346. 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
  3347. 'to snprintf.' % (match.group(1), match.group(2)))
  3348. # Check if some verboten C functions are being used.
  3349. if Search(r'\bsprintf\b', line):
  3350. error(filename, linenum, 'runtime/printf', 5,
  3351. 'Never use sprintf. Use snprintf instead.')
  3352. match = Search(r'\b(strcpy|strcat)\b', line)
  3353. if match:
  3354. error(filename, linenum, 'runtime/printf', 4,
  3355. 'Almost always, snprintf is better than %s' % match.group(1))
  3356. # Check if some verboten operator overloading is going on
  3357. # TODO(unknown): catch out-of-line unary operator&:
  3358. # class X {};
  3359. # int operator&(const X& x) { return 42; } // unary operator&
  3360. # The trick is it's hard to tell apart from binary operator&:
  3361. # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
  3362. if Search(r'\boperator\s*&\s*\(\s*\)', line):
  3363. error(filename, linenum, 'runtime/operator', 4,
  3364. 'Unary operator& is dangerous. Do not use it.')
  3365. # Check for suspicious usage of "if" like
  3366. # } if (a == b) {
  3367. if Search(r'\}\s*if\s*\(', line):
  3368. error(filename, linenum, 'readability/braces', 4,
  3369. 'Did you mean "else if"? If not, start a new line for "if".')
  3370. # Check for potential format string bugs like printf(foo).
  3371. # We constrain the pattern not to pick things like DocidForPrintf(foo).
  3372. # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
  3373. # TODO(sugawarayu): Catch the following case. Need to change the calling
  3374. # convention of the whole function to process multiple line to handle it.
  3375. # printf(
  3376. # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
  3377. printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
  3378. if printf_args:
  3379. match = Match(r'([\w.\->()]+)$', printf_args)
  3380. if match and match.group(1) != '__VA_ARGS__':
  3381. function_name = re.search(r'\b((?:string)?printf)\s*\(',
  3382. line, re.I).group(1)
  3383. error(filename, linenum, 'runtime/printf', 4,
  3384. 'Potential format string bug. Do %s("%%s", %s) instead.'
  3385. % (function_name, match.group(1)))
  3386. # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
  3387. match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
  3388. if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
  3389. error(filename, linenum, 'runtime/memset', 4,
  3390. 'Did you mean "memset(%s, 0, %s)"?'
  3391. % (match.group(1), match.group(2)))
  3392. if Search(r'\busing namespace\b', line):
  3393. error(filename, linenum, 'build/namespaces', 5,
  3394. 'Do not use namespace using-directives. '
  3395. 'Use using-declarations instead.')
  3396. # Detect variable-length arrays.
  3397. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
  3398. if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
  3399. match.group(3).find(']') == -1):
  3400. # Split the size using space and arithmetic operators as delimiters.
  3401. # If any of the resulting tokens are not compile time constants then
  3402. # report the error.
  3403. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
  3404. is_const = True
  3405. skip_next = False
  3406. for tok in tokens:
  3407. if skip_next:
  3408. skip_next = False
  3409. continue
  3410. if Search(r'sizeof\(.+\)', tok): continue
  3411. if Search(r'arraysize\(\w+\)', tok): continue
  3412. tok = tok.lstrip('(')
  3413. tok = tok.rstrip(')')
  3414. if not tok: continue
  3415. if Match(r'\d+', tok): continue
  3416. if Match(r'0[xX][0-9a-fA-F]+', tok): continue
  3417. if Match(r'k[A-Z0-9]\w*', tok): continue
  3418. if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
  3419. if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
  3420. # A catch all for tricky sizeof cases, including 'sizeof expression',
  3421. # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
  3422. # requires skipping the next token because we split on ' ' and '*'.
  3423. if tok.startswith('sizeof'):
  3424. skip_next = True
  3425. continue
  3426. is_const = False
  3427. break
  3428. if not is_const:
  3429. error(filename, linenum, 'runtime/arrays', 1,
  3430. 'Do not use variable-length arrays. Use an appropriately named '
  3431. "('k' followed by CamelCase) compile-time constant for the size.")
  3432. # If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or
  3433. # DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing
  3434. # in the class declaration.
  3435. match = Match(
  3436. (r'\s*'
  3437. r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'
  3438. r'\(.*\);$'),
  3439. line)
  3440. if match and linenum + 1 < clean_lines.NumLines():
  3441. next_line = clean_lines.elided[linenum + 1]
  3442. # We allow some, but not all, declarations of variables to be present
  3443. # in the statement that defines the class. The [\w\*,\s]* fragment of
  3444. # the regular expression below allows users to declare instances of
  3445. # the class or pointers to instances, but not less common types such
  3446. # as function pointers or arrays. It's a tradeoff between allowing
  3447. # reasonable code and avoiding trying to parse more C++ using regexps.
  3448. if not Search(r'^\s*}[\w\*,\s]*;', next_line):
  3449. error(filename, linenum, 'readability/constructors', 3,
  3450. match.group(1) + ' should be the last thing in the class')
  3451. # Check for use of unnamed namespaces in header files. Registration
  3452. # macros are typically OK, so we allow use of "namespace {" on lines
  3453. # that end with backslashes.
  3454. if (file_extension == 'h'
  3455. and Search(r'\bnamespace\s*{', line)
  3456. and line[-1] != '\\'):
  3457. error(filename, linenum, 'build/namespaces', 4,
  3458. 'Do not use unnamed namespaces in header files. See '
  3459. 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
  3460. ' for more information.')
  3461. def CheckForNonConstReference(filename, clean_lines, linenum,
  3462. nesting_state, error):
  3463. """Check for non-const references.
  3464. Separate from CheckLanguage since it scans backwards from current
  3465. line, instead of scanning forward.
  3466. Args:
  3467. filename: The name of the current file.
  3468. clean_lines: A CleansedLines instance containing the file.
  3469. linenum: The number of the line to check.
  3470. nesting_state: A _NestingState instance which maintains information about
  3471. the current stack of nested blocks being parsed.
  3472. error: The function to call with any errors found.
  3473. """
  3474. # Do nothing if there is no '&' on current line.
  3475. line = clean_lines.elided[linenum]
  3476. if '&' not in line:
  3477. return
  3478. # Long type names may be broken across multiple lines, usually in one
  3479. # of these forms:
  3480. # LongType
  3481. # ::LongTypeContinued &identifier
  3482. # LongType::
  3483. # LongTypeContinued &identifier
  3484. # LongType<
  3485. # ...>::LongTypeContinued &identifier
  3486. #
  3487. # If we detected a type split across two lines, join the previous
  3488. # line to current line so that we can match const references
  3489. # accordingly.
  3490. #
  3491. # Note that this only scans back one line, since scanning back
  3492. # arbitrary number of lines would be expensive. If you have a type
  3493. # that spans more than 2 lines, please use a typedef.
  3494. if linenum > 1:
  3495. previous = None
  3496. if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
  3497. # previous_line\n + ::current_line
  3498. previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
  3499. clean_lines.elided[linenum - 1])
  3500. elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
  3501. # previous_line::\n + current_line
  3502. previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
  3503. clean_lines.elided[linenum - 1])
  3504. if previous:
  3505. line = previous.group(1) + line.lstrip()
  3506. else:
  3507. # Check for templated parameter that is split across multiple lines
  3508. endpos = line.rfind('>')
  3509. if endpos > -1:
  3510. (_, startline, startpos) = ReverseCloseExpression(
  3511. clean_lines, linenum, endpos)
  3512. if startpos > -1 and startline < linenum:
  3513. # Found the matching < on an earlier line, collect all
  3514. # pieces up to current line.
  3515. line = ''
  3516. for i in xrange(startline, linenum + 1):
  3517. line += clean_lines.elided[i].strip()
  3518. # Check for non-const references in function parameters. A single '&' may
  3519. # found in the following places:
  3520. # inside expression: binary & for bitwise AND
  3521. # inside expression: unary & for taking the address of something
  3522. # inside declarators: reference parameter
  3523. # We will exclude the first two cases by checking that we are not inside a
  3524. # function body, including one that was just introduced by a trailing '{'.
  3525. # TODO(unknwon): Doesn't account for preprocessor directives.
  3526. # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
  3527. check_params = False
  3528. if not nesting_state.stack:
  3529. check_params = True # top level
  3530. elif (isinstance(nesting_state.stack[-1], _ClassInfo) or
  3531. isinstance(nesting_state.stack[-1], _NamespaceInfo)):
  3532. check_params = True # within class or namespace
  3533. elif Match(r'.*{\s*$', line):
  3534. if (len(nesting_state.stack) == 1 or
  3535. isinstance(nesting_state.stack[-2], _ClassInfo) or
  3536. isinstance(nesting_state.stack[-2], _NamespaceInfo)):
  3537. check_params = True # just opened global/class/namespace block
  3538. # We allow non-const references in a few standard places, like functions
  3539. # called "swap()" or iostream operators like "<<" or ">>". Do not check
  3540. # those function parameters.
  3541. #
  3542. # We also accept & in static_assert, which looks like a function but
  3543. # it's actually a declaration expression.
  3544. whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
  3545. r'operator\s*[<>][<>]|'
  3546. r'static_assert|COMPILE_ASSERT'
  3547. r')\s*\(')
  3548. if Search(whitelisted_functions, line):
  3549. check_params = False
  3550. elif not Search(r'\S+\([^)]*$', line):
  3551. # Don't see a whitelisted function on this line. Actually we
  3552. # didn't see any function name on this line, so this is likely a
  3553. # multi-line parameter list. Try a bit harder to catch this case.
  3554. for i in xrange(2):
  3555. if (linenum > i and
  3556. Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
  3557. check_params = False
  3558. break
  3559. if check_params:
  3560. decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
  3561. for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
  3562. if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter):
  3563. error(filename, linenum, 'runtime/references', 2,
  3564. 'Is this a non-const reference? '
  3565. 'If so, make const or use a pointer: ' +
  3566. ReplaceAll(' *<', '<', parameter))
  3567. def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
  3568. error):
  3569. """Checks for a C-style cast by looking for the pattern.
  3570. Args:
  3571. filename: The name of the current file.
  3572. linenum: The number of the line to check.
  3573. line: The line of code to check.
  3574. raw_line: The raw line of code to check, with comments.
  3575. cast_type: The string for the C++ cast to recommend. This is either
  3576. reinterpret_cast, static_cast, or const_cast, depending.
  3577. pattern: The regular expression used to find C-style casts.
  3578. error: The function to call with any errors found.
  3579. Returns:
  3580. True if an error was emitted.
  3581. False otherwise.
  3582. """
  3583. match = Search(pattern, line)
  3584. if not match:
  3585. return False
  3586. # e.g., sizeof(int)
  3587. sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
  3588. if sizeof_match:
  3589. error(filename, linenum, 'runtime/sizeof', 1,
  3590. 'Using sizeof(type). Use sizeof(varname) instead if possible')
  3591. return True
  3592. # operator++(int) and operator--(int)
  3593. if (line[0:match.start(1) - 1].endswith(' operator++') or
  3594. line[0:match.start(1) - 1].endswith(' operator--')):
  3595. return False
  3596. # A single unnamed argument for a function tends to look like old
  3597. # style cast. If we see those, don't issue warnings for deprecated
  3598. # casts, instead issue warnings for unnamed arguments where
  3599. # appropriate.
  3600. #
  3601. # These are things that we want warnings for, since the style guide
  3602. # explicitly require all parameters to be named:
  3603. # Function(int);
  3604. # Function(int) {
  3605. # ConstMember(int) const;
  3606. # ConstMember(int) const {
  3607. # ExceptionMember(int) throw (...);
  3608. # ExceptionMember(int) throw (...) {
  3609. # PureVirtual(int) = 0;
  3610. #
  3611. # These are functions of some sort, where the compiler would be fine
  3612. # if they had named parameters, but people often omit those
  3613. # identifiers to reduce clutter:
  3614. # (FunctionPointer)(int);
  3615. # (FunctionPointer)(int) = value;
  3616. # Function((function_pointer_arg)(int))
  3617. # <TemplateArgument(int)>;
  3618. # <(FunctionPointerTemplateArgument)(int)>;
  3619. remainder = line[match.end(0):]
  3620. if Match(r'^\s*(?:;|const\b|throw\b|=|>|\{|\))', remainder):
  3621. # Looks like an unnamed parameter.
  3622. # Don't warn on any kind of template arguments.
  3623. if Match(r'^\s*>', remainder):
  3624. return False
  3625. # Don't warn on assignments to function pointers, but keep warnings for
  3626. # unnamed parameters to pure virtual functions. Note that this pattern
  3627. # will also pass on assignments of "0" to function pointers, but the
  3628. # preferred values for those would be "nullptr" or "NULL".
  3629. matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder)
  3630. if matched_zero and matched_zero.group(1) != '0':
  3631. return False
  3632. # Don't warn on function pointer declarations. For this we need
  3633. # to check what came before the "(type)" string.
  3634. if Match(r'.*\)\s*$', line[0:match.start(0)]):
  3635. return False
  3636. # Don't warn if the parameter is named with block comments, e.g.:
  3637. # Function(int /*unused_param*/);
  3638. if '/*' in raw_line:
  3639. return False
  3640. # Passed all filters, issue warning here.
  3641. error(filename, linenum, 'readability/function', 3,
  3642. 'All parameters should be named in a function')
  3643. return True
  3644. # At this point, all that should be left is actual casts.
  3645. error(filename, linenum, 'readability/casting', 4,
  3646. 'Using C-style cast. Use %s<%s>(...) instead' %
  3647. (cast_type, match.group(1)))
  3648. return True
  3649. _HEADERS_CONTAINING_TEMPLATES = (
  3650. ('<deque>', ('deque',)),
  3651. ('<functional>', ('unary_function', 'binary_function',
  3652. 'plus', 'minus', 'multiplies', 'divides', 'modulus',
  3653. 'negate',
  3654. 'equal_to', 'not_equal_to', 'greater', 'less',
  3655. 'greater_equal', 'less_equal',
  3656. 'logical_and', 'logical_or', 'logical_not',
  3657. 'unary_negate', 'not1', 'binary_negate', 'not2',
  3658. 'bind1st', 'bind2nd',
  3659. 'pointer_to_unary_function',
  3660. 'pointer_to_binary_function',
  3661. 'ptr_fun',
  3662. 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
  3663. 'mem_fun_ref_t',
  3664. 'const_mem_fun_t', 'const_mem_fun1_t',
  3665. 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
  3666. 'mem_fun_ref',
  3667. )),
  3668. ('<limits>', ('numeric_limits',)),
  3669. ('<list>', ('list',)),
  3670. ('<map>', ('map', 'multimap',)),
  3671. ('<memory>', ('allocator',)),
  3672. ('<queue>', ('queue', 'priority_queue',)),
  3673. ('<set>', ('set', 'multiset',)),
  3674. ('<stack>', ('stack',)),
  3675. ('<string>', ('char_traits', 'basic_string',)),
  3676. ('<utility>', ('pair',)),
  3677. ('<vector>', ('vector',)),
  3678. # gcc extensions.
  3679. # Note: std::hash is their hash, ::hash is our hash
  3680. ('<hash_map>', ('hash_map', 'hash_multimap',)),
  3681. ('<hash_set>', ('hash_set', 'hash_multiset',)),
  3682. ('<slist>', ('slist',)),
  3683. )
  3684. _RE_PATTERN_STRING = re.compile(r'\bstring\b')
  3685. _re_pattern_algorithm_header = []
  3686. for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap',
  3687. 'transform'):
  3688. # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
  3689. # type::max().
  3690. _re_pattern_algorithm_header.append(
  3691. (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
  3692. _template,
  3693. '<algorithm>'))
  3694. _re_pattern_templates = []
  3695. for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
  3696. for _template in _templates:
  3697. _re_pattern_templates.append(
  3698. (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
  3699. _template + '<>',
  3700. _header))
  3701. def FilesBelongToSameModule(filename_cc, filename_h):
  3702. """Check if these two filenames belong to the same module.
  3703. The concept of a 'module' here is a as follows:
  3704. foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
  3705. same 'module' if they are in the same directory.
  3706. some/path/public/xyzzy and some/path/internal/xyzzy are also considered
  3707. to belong to the same module here.
  3708. If the filename_cc contains a longer path than the filename_h, for example,
  3709. '/absolute/path/to/base/sysinfo.cc', and this file would include
  3710. 'base/sysinfo.h', this function also produces the prefix needed to open the
  3711. header. This is used by the caller of this function to more robustly open the
  3712. header file. We don't have access to the real include paths in this context,
  3713. so we need this guesswork here.
  3714. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
  3715. according to this implementation. Because of this, this function gives
  3716. some false positives. This should be sufficiently rare in practice.
  3717. Args:
  3718. filename_cc: is the path for the .cc file
  3719. filename_h: is the path for the header path
  3720. Returns:
  3721. Tuple with a bool and a string:
  3722. bool: True if filename_cc and filename_h belong to the same module.
  3723. string: the additional prefix needed to open the header file.
  3724. """
  3725. if not filename_cc.endswith('.cc'):
  3726. return (False, '')
  3727. filename_cc = filename_cc[:-len('.cc')]
  3728. if filename_cc.endswith('_unittest'):
  3729. filename_cc = filename_cc[:-len('_unittest')]
  3730. elif filename_cc.endswith('_test'):
  3731. filename_cc = filename_cc[:-len('_test')]
  3732. filename_cc = filename_cc.replace('/public/', '/')
  3733. filename_cc = filename_cc.replace('/internal/', '/')
  3734. if not filename_h.endswith('.h'):
  3735. return (False, '')
  3736. filename_h = filename_h[:-len('.h')]
  3737. if filename_h.endswith('-inl'):
  3738. filename_h = filename_h[:-len('-inl')]
  3739. filename_h = filename_h.replace('/public/', '/')
  3740. filename_h = filename_h.replace('/internal/', '/')
  3741. files_belong_to_same_module = filename_cc.endswith(filename_h)
  3742. common_path = ''
  3743. if files_belong_to_same_module:
  3744. common_path = filename_cc[:-len(filename_h)]
  3745. return files_belong_to_same_module, common_path
  3746. def UpdateIncludeState(filename, include_state, io=codecs):
  3747. """Fill up the include_state with new includes found from the file.
  3748. Args:
  3749. filename: the name of the header to read.
  3750. include_state: an _IncludeState instance in which the headers are inserted.
  3751. io: The io factory to use to read the file. Provided for testability.
  3752. Returns:
  3753. True if a header was succesfully added. False otherwise.
  3754. """
  3755. headerfile = None
  3756. try:
  3757. headerfile = io.open(filename, 'r', 'utf8', 'replace')
  3758. except IOError:
  3759. return False
  3760. linenum = 0
  3761. for line in headerfile:
  3762. linenum += 1
  3763. clean_line = CleanseComments(line)
  3764. match = _RE_PATTERN_INCLUDE.search(clean_line)
  3765. if match:
  3766. include = match.group(2)
  3767. # The value formatting is cute, but not really used right now.
  3768. # What matters here is that the key is in include_state.
  3769. include_state.setdefault(include, '%s:%d' % (filename, linenum))
  3770. return True
  3771. def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
  3772. io=codecs):
  3773. """Reports for missing stl includes.
  3774. This function will output warnings to make sure you are including the headers
  3775. necessary for the stl containers and functions that you use. We only give one
  3776. reason to include a header. For example, if you use both equal_to<> and
  3777. less<> in a .h file, only one (the latter in the file) of these will be
  3778. reported as a reason to include the <functional>.
  3779. Args:
  3780. filename: The name of the current file.
  3781. clean_lines: A CleansedLines instance containing the file.
  3782. include_state: An _IncludeState instance.
  3783. error: The function to call with any errors found.
  3784. io: The IO factory to use to read the header file. Provided for unittest
  3785. injection.
  3786. """
  3787. required = {} # A map of header name to linenumber and the template entity.
  3788. # Example of required: { '<functional>': (1219, 'less<>') }
  3789. for linenum in xrange(clean_lines.NumLines()):
  3790. line = clean_lines.elided[linenum]
  3791. if not line or line[0] == '#':
  3792. continue
  3793. # String is special -- it is a non-templatized type in STL.
  3794. matched = _RE_PATTERN_STRING.search(line)
  3795. if matched:
  3796. # Don't warn about strings in non-STL namespaces:
  3797. # (We check only the first match per line; good enough.)
  3798. prefix = line[:matched.start()]
  3799. if prefix.endswith('std::') or not prefix.endswith('::'):
  3800. required['<string>'] = (linenum, 'string')
  3801. for pattern, template, header in _re_pattern_algorithm_header:
  3802. if pattern.search(line):
  3803. required[header] = (linenum, template)
  3804. # The following function is just a speed up, no semantics are changed.
  3805. if not '<' in line: # Reduces the cpu time usage by skipping lines.
  3806. continue
  3807. for pattern, template, header in _re_pattern_templates:
  3808. if pattern.search(line):
  3809. required[header] = (linenum, template)
  3810. # The policy is that if you #include something in foo.h you don't need to
  3811. # include it again in foo.cc. Here, we will look at possible includes.
  3812. # Let's copy the include_state so it is only messed up within this function.
  3813. include_state = include_state.copy()
  3814. # Did we find the header for this file (if any) and succesfully load it?
  3815. header_found = False
  3816. # Use the absolute path so that matching works properly.
  3817. abs_filename = FileInfo(filename).FullName()
  3818. # For Emacs's flymake.
  3819. # If cpplint is invoked from Emacs's flymake, a temporary file is generated
  3820. # by flymake and that file name might end with '_flymake.cc'. In that case,
  3821. # restore original file name here so that the corresponding header file can be
  3822. # found.
  3823. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
  3824. # instead of 'foo_flymake.h'
  3825. abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
  3826. # include_state is modified during iteration, so we iterate over a copy of
  3827. # the keys.
  3828. header_keys = include_state.keys()
  3829. for header in header_keys:
  3830. (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
  3831. fullpath = common_path + header
  3832. if same_module and UpdateIncludeState(fullpath, include_state, io):
  3833. header_found = True
  3834. # If we can't find the header file for a .cc, assume it's because we don't
  3835. # know where to look. In that case we'll give up as we're not sure they
  3836. # didn't include it in the .h file.
  3837. # TODO(unknown): Do a better job of finding .h files so we are confident that
  3838. # not having the .h file means there isn't one.
  3839. if filename.endswith('.cc') and not header_found:
  3840. return
  3841. # All the lines have been processed, report the errors found.
  3842. for required_header_unstripped in required:
  3843. template = required[required_header_unstripped][1]
  3844. if required_header_unstripped.strip('<>"') not in include_state:
  3845. error(filename, required[required_header_unstripped][0],
  3846. 'build/include_what_you_use', 4,
  3847. 'Add #include ' + required_header_unstripped + ' for ' + template)
  3848. _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
  3849. def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
  3850. """Check that make_pair's template arguments are deduced.
  3851. G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
  3852. specified explicitly, and such use isn't intended in any case.
  3853. Args:
  3854. filename: The name of the current file.
  3855. clean_lines: A CleansedLines instance containing the file.
  3856. linenum: The number of the line to check.
  3857. error: The function to call with any errors found.
  3858. """
  3859. line = clean_lines.elided[linenum]
  3860. match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
  3861. if match:
  3862. error(filename, linenum, 'build/explicit_make_pair',
  3863. 4, # 4 = high confidence
  3864. 'For C++11-compatibility, omit template arguments from make_pair'
  3865. ' OR use pair directly OR if appropriate, construct a pair directly')
  3866. def ProcessLine(filename, file_extension, clean_lines, line,
  3867. include_state, function_state, nesting_state, error,
  3868. extra_check_functions=[]):
  3869. """Processes a single line in the file.
  3870. Args:
  3871. filename: Filename of the file that is being processed.
  3872. file_extension: The extension (dot not included) of the file.
  3873. clean_lines: An array of strings, each representing a line of the file,
  3874. with comments stripped.
  3875. line: Number of line being processed.
  3876. include_state: An _IncludeState instance in which the headers are inserted.
  3877. function_state: A _FunctionState instance which counts function lines, etc.
  3878. nesting_state: A _NestingState instance which maintains information about
  3879. the current stack of nested blocks being parsed.
  3880. error: A callable to which errors are reported, which takes 4 arguments:
  3881. filename, line number, error level, and message
  3882. extra_check_functions: An array of additional check functions that will be
  3883. run on each source line. Each function takes 4
  3884. arguments: filename, clean_lines, line, error
  3885. """
  3886. raw_lines = clean_lines.raw_lines
  3887. ParseNolintSuppressions(filename, raw_lines[line], line, error)
  3888. nesting_state.Update(filename, clean_lines, line, error)
  3889. if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM:
  3890. return
  3891. CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
  3892. CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
  3893. CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
  3894. CheckLanguage(filename, clean_lines, line, file_extension, include_state,
  3895. nesting_state, error)
  3896. CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
  3897. CheckForNonStandardConstructs(filename, clean_lines, line,
  3898. nesting_state, error)
  3899. CheckVlogArguments(filename, clean_lines, line, error)
  3900. CheckPosixThreading(filename, clean_lines, line, error)
  3901. CheckInvalidIncrement(filename, clean_lines, line, error)
  3902. CheckMakePairUsesDeduction(filename, clean_lines, line, error)
  3903. for check_fn in extra_check_functions:
  3904. check_fn(filename, clean_lines, line, error)
  3905. def ProcessFileData(filename, file_extension, lines, error,
  3906. extra_check_functions=[]):
  3907. """Performs lint checks and reports any errors to the given error function.
  3908. Args:
  3909. filename: Filename of the file that is being processed.
  3910. file_extension: The extension (dot not included) of the file.
  3911. lines: An array of strings, each representing a line of the file, with the
  3912. last element being empty if the file is terminated with a newline.
  3913. error: A callable to which errors are reported, which takes 4 arguments:
  3914. filename, line number, error level, and message
  3915. extra_check_functions: An array of additional check functions that will be
  3916. run on each source line. Each function takes 4
  3917. arguments: filename, clean_lines, line, error
  3918. """
  3919. lines = (['// marker so line numbers and indices both start at 1'] + lines +
  3920. ['// marker so line numbers end in a known way'])
  3921. include_state = _IncludeState()
  3922. function_state = _FunctionState()
  3923. nesting_state = _NestingState()
  3924. ResetNolintSuppressions()
  3925. CheckForCopyright(filename, lines, error)
  3926. if file_extension == 'h':
  3927. CheckForHeaderGuard(filename, lines, error)
  3928. RemoveMultiLineComments(filename, lines, error)
  3929. clean_lines = CleansedLines(lines)
  3930. for line in xrange(clean_lines.NumLines()):
  3931. ProcessLine(filename, file_extension, clean_lines, line,
  3932. include_state, function_state, nesting_state, error,
  3933. extra_check_functions)
  3934. nesting_state.CheckCompletedBlocks(filename, error)
  3935. CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
  3936. # We check here rather than inside ProcessLine so that we see raw
  3937. # lines rather than "cleaned" lines.
  3938. CheckForBadCharacters(filename, lines, error)
  3939. CheckForNewlineAtEOF(filename, lines, error)
  3940. def ProcessFile(filename, vlevel, extra_check_functions=[]):
  3941. """Does google-lint on a single file.
  3942. Args:
  3943. filename: The name of the file to parse.
  3944. vlevel: The level of errors to report. Every error of confidence
  3945. >= verbose_level will be reported. 0 is a good default.
  3946. extra_check_functions: An array of additional check functions that will be
  3947. run on each source line. Each function takes 4
  3948. arguments: filename, clean_lines, line, error
  3949. """
  3950. _SetVerboseLevel(vlevel)
  3951. try:
  3952. # Support the UNIX convention of using "-" for stdin. Note that
  3953. # we are not opening the file with universal newline support
  3954. # (which codecs doesn't support anyway), so the resulting lines do
  3955. # contain trailing '\r' characters if we are reading a file that
  3956. # has CRLF endings.
  3957. # If after the split a trailing '\r' is present, it is removed
  3958. # below. If it is not expected to be present (i.e. os.linesep !=
  3959. # '\r\n' as in Windows), a warning is issued below if this file
  3960. # is processed.
  3961. if filename == '-':
  3962. lines = codecs.StreamReaderWriter(sys.stdin,
  3963. codecs.getreader('utf8'),
  3964. codecs.getwriter('utf8'),
  3965. 'replace').read().split('\n')
  3966. else:
  3967. lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
  3968. carriage_return_found = False
  3969. # Remove trailing '\r'.
  3970. for linenum in range(len(lines)):
  3971. if lines[linenum].endswith('\r'):
  3972. lines[linenum] = lines[linenum].rstrip('\r')
  3973. carriage_return_found = True
  3974. except IOError:
  3975. sys.stderr.write(
  3976. "Skipping input '%s': Can't open for reading\n" % filename)
  3977. return
  3978. # Note, if no dot is found, this will give the entire filename as the ext.
  3979. file_extension = filename[filename.rfind('.') + 1:]
  3980. # When reading from stdin, the extension is unknown, so no cpplint tests
  3981. # should rely on the extension.
  3982. if filename != '-' and file_extension not in _valid_extensions:
  3983. sys.stderr.write('Ignoring %s; not a valid file name '
  3984. '(%s)\n' % (filename, ', '.join(_valid_extensions)))
  3985. else:
  3986. ProcessFileData(filename, file_extension, lines, Error,
  3987. extra_check_functions)
  3988. if carriage_return_found and os.linesep != '\r\n':
  3989. # Use 0 for linenum since outputting only one error for potentially
  3990. # several lines.
  3991. Error(filename, 0, 'whitespace/newline', 1,
  3992. 'One or more unexpected \\r (^M) found;'
  3993. 'better to use only a \\n')
  3994. sys.stderr.write('Done processing %s\n' % filename)
  3995. def PrintUsage(message):
  3996. """Prints a brief usage string and exits, optionally with an error message.
  3997. Args:
  3998. message: The optional error message.
  3999. """
  4000. sys.stderr.write(_USAGE)
  4001. if message:
  4002. sys.exit('\nFATAL ERROR: ' + message)
  4003. else:
  4004. sys.exit(1)
  4005. def PrintCategories():
  4006. """Prints a list of all the error-categories used by error messages.
  4007. These are the categories used to filter messages via --filter.
  4008. """
  4009. sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
  4010. sys.exit(0)
  4011. def ParseArguments(args):
  4012. """Parses the command line arguments.
  4013. This may set the output format and verbosity level as side-effects.
  4014. Args:
  4015. args: The command line arguments:
  4016. Returns:
  4017. The list of filenames to lint.
  4018. """
  4019. try:
  4020. (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
  4021. 'counting=',
  4022. 'filter=',
  4023. 'root=',
  4024. 'linelength=',
  4025. 'extensions='])
  4026. except getopt.GetoptError:
  4027. PrintUsage('Invalid arguments.')
  4028. verbosity = _VerboseLevel()
  4029. output_format = _OutputFormat()
  4030. filters = ''
  4031. counting_style = ''
  4032. for (opt, val) in opts:
  4033. if opt == '--help':
  4034. PrintUsage(None)
  4035. elif opt == '--output':
  4036. if val not in ('emacs', 'vs7', 'eclipse'):
  4037. PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
  4038. output_format = val
  4039. elif opt == '--verbose':
  4040. verbosity = int(val)
  4041. elif opt == '--filter':
  4042. filters = val
  4043. if not filters:
  4044. PrintCategories()
  4045. elif opt == '--counting':
  4046. if val not in ('total', 'toplevel', 'detailed'):
  4047. PrintUsage('Valid counting options are total, toplevel, and detailed')
  4048. counting_style = val
  4049. elif opt == '--root':
  4050. global _root
  4051. _root = val
  4052. elif opt == '--linelength':
  4053. global _line_length
  4054. try:
  4055. _line_length = int(val)
  4056. except ValueError:
  4057. PrintUsage('Line length must be digits.')
  4058. elif opt == '--extensions':
  4059. global _valid_extensions
  4060. try:
  4061. _valid_extensions = set(val.split(','))
  4062. except ValueError:
  4063. PrintUsage('Extensions must be comma seperated list.')
  4064. if not filenames:
  4065. PrintUsage('No files were specified.')
  4066. _SetOutputFormat(output_format)
  4067. _SetVerboseLevel(verbosity)
  4068. _SetFilters(filters)
  4069. _SetCountingStyle(counting_style)
  4070. return filenames
  4071. def main():
  4072. filenames = ParseArguments(sys.argv[1:])
  4073. # Change stderr to write with replacement characters so we don't die
  4074. # if we try to print something containing non-ASCII characters.
  4075. sys.stderr = codecs.StreamReaderWriter(sys.stderr,
  4076. codecs.getreader('utf8'),
  4077. codecs.getwriter('utf8'),
  4078. 'replace')
  4079. _cpplint_state.ResetErrorCounts()
  4080. for filename in filenames:
  4081. ProcessFile(filename, _cpplint_state.verbose_level)
  4082. _cpplint_state.PrintErrorCounts()
  4083. sys.exit(_cpplint_state.error_count > 0)
  4084. if __name__ == '__main__':
  4085. main()