cpplint.py 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (c) 2009 Google Inc. All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. # Here are some issues that I've had people identify in my code during reviews,
  31. # that I think are possible to flag automatically in a lint tool. If these were
  32. # caught by lint, it would save time both for myself and that of my reviewers.
  33. # Most likely, some of these are beyond the scope of the current lint framework,
  34. # but I think it is valuable to retain these wish-list items even if they cannot
  35. # be immediately implemented.
  36. #
  37. # Suggestions
  38. # -----------
  39. # - Check for no 'explicit' for multi-arg ctor
  40. # - Check for boolean assign RHS in parens
  41. # - Check for ctor initializer-list colon position and spacing
  42. # - Check that if there's a ctor, there should be a dtor
  43. # - Check accessors that return non-pointer member variables are
  44. # declared const
  45. # - Check accessors that return non-const pointer member vars are
  46. # *not* declared const
  47. # - Check for using public includes for testing
  48. # - Check for spaces between brackets in one-line inline method
  49. # - Check for no assert()
  50. # - Check for spaces surrounding operators
  51. # - Check for 0 in pointer context (should be NULL)
  52. # - Check for 0 in char context (should be '\0')
  53. # - Check for camel-case method name conventions for methods
  54. # that are not simple inline getters and setters
  55. # - Check that base classes have virtual destructors
  56. # put " // namespace" after } that closes a namespace, with
  57. # namespace's name after 'namespace' if it is named.
  58. # - Do not indent namespace contents
  59. # - Avoid inlining non-trivial constructors in header files
  60. # include base/basictypes.h if DISALLOW_EVIL_CONSTRUCTORS is used
  61. # - Check for old-school (void) cast for call-sites of functions
  62. # ignored return value
  63. # - Check gUnit usage of anonymous namespace
  64. # - Check for class declaration order (typedefs, consts, enums,
  65. # ctor(s?), dtor, friend declarations, methods, member vars)
  66. #
  67. """Does google-lint on c++ files.
  68. The goal of this script is to identify places in the code that *may*
  69. be in non-compliance with google style. It does not attempt to fix
  70. up these problems -- the point is to educate. It does also not
  71. attempt to find all problems, or to ensure that everything it does
  72. find is legitimately a problem.
  73. In particular, we can get very confused by /* and // inside strings!
  74. We do a small hack, which is to ignore //'s with "'s after them on the
  75. same line, but it is far from perfect (in either direction).
  76. """
  77. import codecs
  78. import getopt
  79. import math # for log
  80. import os
  81. import re
  82. import sre_compile
  83. import string
  84. import sys
  85. import unicodedata
  86. EXTENSIONS = ['c', 'cc', 'cpp', 'cxx', 'c++',
  87. 'h', 'hpp', 'hxx', 'h++']
  88. _USAGE = """
  89. Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
  90. [--counting=total|toplevel|detailed]
  91. <file> [file] ...
  92. The style guidelines this tries to follow are those in
  93. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
  94. Every problem is given a confidence score from 1-5, with 5 meaning we are
  95. certain of the problem, and 1 meaning it could be a legitimate construct.
  96. This will miss some errors, and is not a substitute for a code review.
  97. To suppress false-positive errors of a certain category, add a
  98. 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)
  99. suppresses errors of all categories on that line.
  100. The files passed in will be linted; at least one file must be provided.
  101. Linted extensions are %s. Other file types will be ignored.
  102. Flags:
  103. output=vs7
  104. By default, the output is formatted to ease emacs parsing. Visual Studio
  105. compatible output (vs7) may also be used. Other formats are unsupported.
  106. verbose=#
  107. Specify a number 0-5 to restrict errors to certain verbosity levels.
  108. filter=-x,+y,...
  109. Specify a comma-separated list of category-filters to apply: only
  110. error messages whose category names pass the filters will be printed.
  111. (Category names are printed with the message and look like
  112. "[whitespace/indent]".) Filters are evaluated left to right.
  113. "-FOO" and "FOO" means "do not print categories that start with FOO".
  114. "+FOO" means "do print categories that start with FOO".
  115. Examples: --filter=-whitespace,+whitespace/braces
  116. --filter=whitespace,runtime/printf,+runtime/printf_format
  117. --filter=-,+build/include_what_you_use
  118. To see a list of all the categories used in cpplint, pass no arg:
  119. --filter=
  120. counting=total|toplevel|detailed
  121. The total number of errors found is always printed. If
  122. 'toplevel' is provided, then the count of errors in each of
  123. the top-level categories like 'build' and 'whitespace' will
  124. also be printed. If 'detailed' is provided, then a count
  125. is provided for each category like 'build/class'.
  126. """ % (EXTENSIONS)
  127. # We categorize each error message we print. Here are the categories.
  128. # We want an explicit list so we can list them all in cpplint --filter=.
  129. # If you add a new error message with a new category, add it to the list
  130. # here! cpplint_unittest.py should tell you if you forget to do this.
  131. # \ used for clearer layout -- pylint: disable-msg=C6013
  132. _ERROR_CATEGORIES = [
  133. 'build/class',
  134. 'build/deprecated',
  135. 'build/endif_comment',
  136. 'build/explicit_make_pair',
  137. 'build/forward_decl',
  138. 'build/header_guard',
  139. 'build/include',
  140. 'build/include_alpha',
  141. 'build/include_order',
  142. 'build/include_what_you_use',
  143. 'build/namespaces',
  144. 'build/printf_format',
  145. 'build/storage_class',
  146. 'legal/copyright',
  147. 'readability/braces',
  148. 'readability/casting',
  149. 'readability/check',
  150. 'readability/constructors',
  151. 'readability/fn_size',
  152. 'readability/function',
  153. 'readability/multiline_comment',
  154. 'readability/multiline_string',
  155. 'readability/nolint',
  156. 'readability/streams',
  157. 'readability/todo',
  158. 'readability/utf8',
  159. 'runtime/arrays',
  160. 'runtime/casting',
  161. 'runtime/explicit',
  162. 'runtime/int',
  163. 'runtime/init',
  164. 'runtime/invalid_increment',
  165. 'runtime/member_string_references',
  166. 'runtime/memset',
  167. 'runtime/operator',
  168. 'runtime/printf',
  169. 'runtime/printf_format',
  170. 'runtime/references',
  171. 'runtime/rtti',
  172. 'runtime/sizeof',
  173. 'runtime/string',
  174. 'runtime/threadsafe_fn',
  175. 'runtime/virtual',
  176. 'whitespace/blank_line',
  177. 'whitespace/braces',
  178. 'whitespace/comma',
  179. 'whitespace/comments',
  180. 'whitespace/end_of_line',
  181. 'whitespace/ending_newline',
  182. 'whitespace/indent',
  183. 'whitespace/labels',
  184. 'whitespace/line_length',
  185. 'whitespace/newline',
  186. 'whitespace/operators',
  187. 'whitespace/parens',
  188. 'whitespace/semicolon',
  189. 'whitespace/tab',
  190. 'whitespace/todo'
  191. ]
  192. # The default state of the category filter. This is overrided by the --filter=
  193. # flag. By default all errors are on, so only add here categories that should be
  194. # off by default (i.e., categories that must be enabled by the --filter= flags).
  195. # All entries here should start with a '-' or '+', as in the --filter= flag.
  196. _DEFAULT_FILTERS = ['-build/include_alpha']
  197. # We used to check for high-bit characters, but after much discussion we
  198. # decided those were OK, as long as they were in UTF-8 and didn't represent
  199. # hard-coded international strings, which belong in a separate i18n file.
  200. # Headers that we consider STL headers.
  201. _STL_HEADERS = frozenset([
  202. 'algobase.h', 'algorithm', 'alloc.h', 'bitset', 'deque', 'exception',
  203. 'function.h', 'functional', 'hash_map', 'hash_map.h', 'hash_set',
  204. 'hash_set.h', 'iterator', 'list', 'list.h', 'map', 'memory', 'new',
  205. 'pair.h', 'pthread_alloc', 'queue', 'set', 'set.h', 'sstream', 'stack',
  206. 'stl_alloc.h', 'stl_relops.h', 'type_traits.h',
  207. 'utility', 'vector', 'vector.h',
  208. ])
  209. # Non-STL C++ system headers.
  210. _CPP_HEADERS = frozenset([
  211. 'algo.h', 'builtinbuf.h', 'bvector.h', 'cassert', 'cctype',
  212. 'cerrno', 'cfloat', 'ciso646', 'climits', 'clocale', 'cmath',
  213. 'complex', 'complex.h', 'csetjmp', 'csignal', 'cstdarg', 'cstddef',
  214. 'cstdio', 'cstdlib', 'cstring', 'ctime', 'cwchar', 'cwctype',
  215. 'defalloc.h', 'deque.h', 'editbuf.h', 'exception', 'fstream',
  216. 'fstream.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip',
  217. 'iomanip.h', 'ios', 'iosfwd', 'iostream', 'iostream.h', 'istream',
  218. 'istream.h', 'iterator.h', 'limits', 'map.h', 'multimap.h', 'multiset.h',
  219. 'numeric', 'ostream', 'ostream.h', 'parsestream.h', 'pfstream.h',
  220. 'PlotFile.h', 'procbuf.h', 'pthread_alloc.h', 'rope', 'rope.h',
  221. 'ropeimpl.h', 'SFile.h', 'slist', 'slist.h', 'stack.h', 'stdexcept',
  222. 'stdiostream.h', 'streambuf.h', 'stream.h', 'strfile.h', 'string',
  223. 'strstream', 'strstream.h', 'tempbuf.h', 'tree.h', 'typeinfo', 'valarray',
  224. ])
  225. # Assertion macros. These are defined in base/logging.h and
  226. # testing/base/gunit.h. Note that the _M versions need to come first
  227. # for substring matching to work.
  228. _CHECK_MACROS = [
  229. 'DCHECK', 'CHECK',
  230. 'EXPECT_TRUE_M', 'EXPECT_TRUE',
  231. 'ASSERT_TRUE_M', 'ASSERT_TRUE',
  232. 'EXPECT_FALSE_M', 'EXPECT_FALSE',
  233. 'ASSERT_FALSE_M', 'ASSERT_FALSE',
  234. ]
  235. # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
  236. _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
  237. for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
  238. ('>=', 'GE'), ('>', 'GT'),
  239. ('<=', 'LE'), ('<', 'LT')]:
  240. _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
  241. _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
  242. _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
  243. _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
  244. _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement
  245. _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement
  246. for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
  247. ('>=', 'LT'), ('>', 'LE'),
  248. ('<=', 'GT'), ('<', 'GE')]:
  249. _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
  250. _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
  251. _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement
  252. _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement
  253. # These constants define types of headers for use with
  254. # _IncludeState.CheckNextIncludeOrder().
  255. _C_SYS_HEADER = 1
  256. _CPP_SYS_HEADER = 2
  257. _LIKELY_MY_HEADER = 3
  258. _POSSIBLE_MY_HEADER = 4
  259. _OTHER_HEADER = 5
  260. _regexp_compile_cache = {}
  261. # Finds occurrences of NOLINT or NOLINT(...).
  262. _RE_SUPPRESSION = re.compile(r'\bNOLINT\b(\([^)]*\))?')
  263. # {str, set(int)}: a map from error categories to sets of linenumbers
  264. # on which those errors are expected and should be suppressed.
  265. _error_suppressions = {}
  266. if sys.version_info < (3,):
  267. def u(x):
  268. return codecs.unicode_escape_decode(x)[0]
  269. TEXT_TYPE = unicode
  270. # BINARY_TYPE = str
  271. range = xrange
  272. itervalues = dict.itervalues
  273. iteritems = dict.iteritems
  274. else:
  275. def u(x):
  276. return x
  277. TEXT_TYPE = str
  278. # BINARY_TYPE = bytes
  279. itervalues = dict.values
  280. iteritems = dict.items
  281. def ParseNolintSuppressions(filename, raw_line, linenum, error):
  282. """Updates the global list of error-suppressions.
  283. Parses any NOLINT comments on the current line, updating the global
  284. error_suppressions store. Reports an error if the NOLINT comment
  285. was malformed.
  286. Args:
  287. filename: str, the name of the input file.
  288. raw_line: str, the line of input text, with comments.
  289. linenum: int, the number of the current line.
  290. error: function, an error handler.
  291. """
  292. # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*).
  293. matched = _RE_SUPPRESSION.search(raw_line)
  294. if matched:
  295. category = matched.group(1)
  296. if category in (None, '(*)'): # => "suppress all"
  297. _error_suppressions.setdefault(None, set()).add(linenum)
  298. else:
  299. if category.startswith('(') and category.endswith(')'):
  300. category = category[1:-1]
  301. if category in _ERROR_CATEGORIES:
  302. _error_suppressions.setdefault(category, set()).add(linenum)
  303. else:
  304. error(filename, linenum, 'readability/nolint', 5,
  305. 'Unknown NOLINT error category: %s' % category)
  306. def ResetNolintSuppressions():
  307. "Resets the set of NOLINT suppressions to empty."
  308. _error_suppressions.clear()
  309. def IsErrorSuppressedByNolint(category, linenum):
  310. """Returns true if the specified error category is suppressed on this line.
  311. Consults the global error_suppressions map populated by
  312. ParseNolintSuppressions/ResetNolintSuppressions.
  313. Args:
  314. category: str, the category of the error.
  315. linenum: int, the current line number.
  316. Returns:
  317. bool, True iff the error should be suppressed due to a NOLINT comment.
  318. """
  319. return (linenum in _error_suppressions.get(category, set()) or
  320. linenum in _error_suppressions.get(None, set()))
  321. def Match(pattern, s):
  322. """Matches the string with the pattern, caching the compiled regexp."""
  323. # The regexp compilation caching is inlined in both Match and Search for
  324. # performance reasons; factoring it out into a separate function turns out
  325. # to be noticeably expensive.
  326. if not pattern in _regexp_compile_cache:
  327. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  328. return _regexp_compile_cache[pattern].match(s)
  329. def Search(pattern, s):
  330. """Searches the string for the pattern, caching the compiled regexp."""
  331. if not pattern in _regexp_compile_cache:
  332. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  333. return _regexp_compile_cache[pattern].search(s)
  334. class _IncludeState(dict):
  335. """Tracks line numbers for includes, and the order in which includes appear.
  336. As a dict, an _IncludeState object serves as a mapping between include
  337. filename and line number on which that file was included.
  338. Call CheckNextIncludeOrder() once for each header in the file, passing
  339. in the type constants defined above. Calls in an illegal order will
  340. raise an _IncludeError with an appropriate error message.
  341. """
  342. # self._section will move monotonically through this set. If it ever
  343. # needs to move backwards, CheckNextIncludeOrder will raise an error.
  344. _INITIAL_SECTION = 0
  345. _MY_H_SECTION = 1
  346. _C_SECTION = 2
  347. _CPP_SECTION = 3
  348. _OTHER_H_SECTION = 4
  349. _TYPE_NAMES = {
  350. _C_SYS_HEADER: 'C system header',
  351. _CPP_SYS_HEADER: 'C++ system header',
  352. _LIKELY_MY_HEADER: 'header this file implements',
  353. _POSSIBLE_MY_HEADER: 'header this file may implement',
  354. _OTHER_HEADER: 'other header',
  355. }
  356. _SECTION_NAMES = {
  357. _INITIAL_SECTION: "... nothing. (This can't be an error.)",
  358. _MY_H_SECTION: 'a header this file implements',
  359. _C_SECTION: 'C system header',
  360. _CPP_SECTION: 'C++ system header',
  361. _OTHER_H_SECTION: 'other header',
  362. }
  363. def __init__(self):
  364. dict.__init__(self)
  365. # The name of the current section.
  366. self._section = self._INITIAL_SECTION
  367. # The path of last found header.
  368. self._last_header = ''
  369. def CanonicalizeAlphabeticalOrder(self, header_path):
  370. """Returns a path canonicalized for alphabetical comparison.
  371. - replaces "-" with "_" so they both cmp the same.
  372. - removes '-inl' since we don't require them to be after the main header.
  373. - lowercase everything, just in case.
  374. Args:
  375. header_path: Path to be canonicalized.
  376. Returns:
  377. Canonicalized path.
  378. """
  379. return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
  380. def IsInAlphabeticalOrder(self, header_path):
  381. """Check if a header is in alphabetical order with the previous header.
  382. Args:
  383. header_path: Header to be checked.
  384. Returns:
  385. Returns true if the header is in alphabetical order.
  386. """
  387. canonical_header = self.CanonicalizeAlphabeticalOrder(header_path)
  388. if self._last_header > canonical_header:
  389. return False
  390. self._last_header = canonical_header
  391. return True
  392. def CheckNextIncludeOrder(self, header_type):
  393. """Returns a non-empty error message if the next header is out of order.
  394. This function also updates the internal state to be ready to check
  395. the next include.
  396. Args:
  397. header_type: One of the _XXX_HEADER constants defined above.
  398. Returns:
  399. The empty string if the header is in the right order, or an
  400. error message describing what's wrong.
  401. """
  402. error_message = ('Found %s after %s' %
  403. (self._TYPE_NAMES[header_type],
  404. self._SECTION_NAMES[self._section]))
  405. last_section = self._section
  406. if header_type == _C_SYS_HEADER:
  407. if self._section <= self._C_SECTION:
  408. self._section = self._C_SECTION
  409. else:
  410. self._last_header = ''
  411. return error_message
  412. elif header_type == _CPP_SYS_HEADER:
  413. if self._section <= self._CPP_SECTION:
  414. self._section = self._CPP_SECTION
  415. else:
  416. self._last_header = ''
  417. return error_message
  418. elif header_type == _LIKELY_MY_HEADER:
  419. if self._section <= self._MY_H_SECTION:
  420. self._section = self._MY_H_SECTION
  421. else:
  422. self._section = self._OTHER_H_SECTION
  423. elif header_type == _POSSIBLE_MY_HEADER:
  424. if self._section <= self._MY_H_SECTION:
  425. self._section = self._MY_H_SECTION
  426. else:
  427. # This will always be the fallback because we're not sure
  428. # enough that the header is associated with this file.
  429. self._section = self._OTHER_H_SECTION
  430. else:
  431. assert header_type == _OTHER_HEADER
  432. self._section = self._OTHER_H_SECTION
  433. if last_section != self._section:
  434. self._last_header = ''
  435. return ''
  436. class _CppLintState(object):
  437. """Maintains module-wide state.."""
  438. def __init__(self):
  439. self.verbose_level = 1 # global setting.
  440. self.error_count = 0 # global count of reported errors
  441. # filters to apply when emitting error messages
  442. self.filters = _DEFAULT_FILTERS[:]
  443. self.counting = 'total' # In what way are we counting errors?
  444. self.errors_by_category = {} # string to int dict storing error counts
  445. # output format:
  446. # "emacs" - format that emacs can parse (default)
  447. # "vs7" - format that Microsoft Visual Studio 7 can parse
  448. self.output_format = 'emacs'
  449. def SetOutputFormat(self, output_format):
  450. """Sets the output format for errors."""
  451. self.output_format = output_format
  452. def SetVerboseLevel(self, level):
  453. """Sets the module's verbosity, and returns the previous setting."""
  454. last_verbose_level = self.verbose_level
  455. self.verbose_level = level
  456. return last_verbose_level
  457. def SetCountingStyle(self, counting_style):
  458. """Sets the module's counting options."""
  459. self.counting = counting_style
  460. def SetFilters(self, filters):
  461. """Sets the error-message filters.
  462. These filters are applied when deciding whether to emit a given
  463. error message.
  464. Args:
  465. filters: A string of comma-separated filters (eg "+whitespace/indent").
  466. Each filter should start with + or -; else we die.
  467. Raises:
  468. ValueError: The comma-separated filters did not all start with '+' or '-'.
  469. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
  470. """
  471. # Default filters always have less priority than the flag ones.
  472. self.filters = _DEFAULT_FILTERS[:]
  473. for filt in filters.split(','):
  474. clean_filt = filt.strip()
  475. if clean_filt:
  476. self.filters.append(clean_filt)
  477. for filt in self.filters:
  478. if not (filt.startswith('+') or filt.startswith('-')):
  479. raise ValueError('Every filter in --filters must start with + or -'
  480. ' (%s does not)' % filt)
  481. def ResetErrorCounts(self):
  482. """Sets the module's error statistic back to zero."""
  483. self.error_count = 0
  484. self.errors_by_category = {}
  485. def IncrementErrorCount(self, category):
  486. """Bumps the module's error statistic."""
  487. self.error_count += 1
  488. if self.counting in ('toplevel', 'detailed'):
  489. if self.counting != 'detailed':
  490. category = category.split('/')[0]
  491. if category not in self.errors_by_category:
  492. self.errors_by_category[category] = 0
  493. self.errors_by_category[category] += 1
  494. def PrintErrorCounts(self):
  495. """Print a summary of errors by category, and the total."""
  496. for category, count in iteritems(self.errors_by_category):
  497. sys.stderr.write('Category \'%s\' errors found: %d\n' %
  498. (category, count))
  499. sys.stderr.write('Total errors found: %d\n' % self.error_count)
  500. _cpplint_state = _CppLintState()
  501. def _OutputFormat():
  502. """Gets the module's output format."""
  503. return _cpplint_state.output_format
  504. def _SetOutputFormat(output_format):
  505. """Sets the module's output format."""
  506. _cpplint_state.SetOutputFormat(output_format)
  507. def _VerboseLevel():
  508. """Returns the module's verbosity setting."""
  509. return _cpplint_state.verbose_level
  510. def _SetVerboseLevel(level):
  511. """Sets the module's verbosity, and returns the previous setting."""
  512. return _cpplint_state.SetVerboseLevel(level)
  513. def _SetCountingStyle(level):
  514. """Sets the module's counting options."""
  515. _cpplint_state.SetCountingStyle(level)
  516. def _Filters():
  517. """Returns the module's list of output filters, as a list."""
  518. return _cpplint_state.filters
  519. def _SetFilters(filters):
  520. """Sets the module's error-message filters.
  521. These filters are applied when deciding whether to emit a given
  522. error message.
  523. Args:
  524. filters: A string of comma-separated filters (eg "whitespace/indent").
  525. Each filter should start with + or -; else we die.
  526. """
  527. _cpplint_state.SetFilters(filters)
  528. class _FunctionState(object):
  529. """Tracks current function name and the number of lines in its body."""
  530. _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
  531. _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
  532. def __init__(self):
  533. self.in_a_function = False
  534. self.lines_in_function = 0
  535. self.current_function = ''
  536. def Begin(self, function_name):
  537. """Start analyzing function body.
  538. Args:
  539. function_name: The name of the function being tracked.
  540. """
  541. self.in_a_function = True
  542. self.lines_in_function = 0
  543. self.current_function = function_name
  544. def Count(self):
  545. """Count line in current function body."""
  546. if self.in_a_function:
  547. self.lines_in_function += 1
  548. def Check(self, error, filename, linenum):
  549. """Report if too many lines in function body.
  550. Args:
  551. error: The function to call with any errors found.
  552. filename: The name of the current file.
  553. linenum: The number of the line to check.
  554. """
  555. if Match(r'T(EST|est)', self.current_function):
  556. base_trigger = self._TEST_TRIGGER
  557. else:
  558. base_trigger = self._NORMAL_TRIGGER
  559. trigger = base_trigger * 2**_VerboseLevel()
  560. if self.lines_in_function > trigger:
  561. error_level = int(math.log(self.lines_in_function / base_trigger, 2))
  562. # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
  563. if error_level > 5:
  564. error_level = 5
  565. error(filename, linenum, 'readability/fn_size', error_level,
  566. 'Small and focused functions are preferred:'
  567. ' %s has %d non-comment lines'
  568. ' (error triggered by exceeding %d lines).' % (
  569. self.current_function, self.lines_in_function, trigger))
  570. def End(self):
  571. """Stop analyzing function body."""
  572. self.in_a_function = False
  573. class _IncludeError(Exception):
  574. """Indicates a problem with the include order in a file."""
  575. pass
  576. class FileInfo:
  577. """Provides utility functions for filenames.
  578. FileInfo provides easy access to the components of a file's path
  579. relative to the project root.
  580. """
  581. def __init__(self, filename):
  582. self._filename = filename
  583. def FullName(self):
  584. """Make Windows paths like Unix."""
  585. return os.path.abspath(self._filename).replace('\\', '/')
  586. def RepositoryName(self):
  587. """FullName after removing the local path to the repository.
  588. If we have a real absolute path name here we can try to do something smart:
  589. detecting the root of the checkout and truncating /path/to/checkout from
  590. the name so that we get header guards that don't include things like
  591. "C:\Documents and Settings\..." or "/home/username/..." in them and thus
  592. people on different computers who have checked the source out to different
  593. locations won't see bogus errors.
  594. """
  595. fullname = self.FullName()
  596. if os.path.exists(fullname):
  597. project_dir = os.path.dirname(fullname)
  598. if os.path.exists(os.path.join(project_dir, ".svn")):
  599. # If there's a .svn file in the current directory, we recursively look
  600. # up the directory tree for the top of the SVN checkout
  601. root_dir = project_dir
  602. one_up_dir = os.path.dirname(root_dir)
  603. while os.path.exists(os.path.join(one_up_dir, ".svn")):
  604. root_dir = os.path.dirname(root_dir)
  605. one_up_dir = os.path.dirname(one_up_dir)
  606. prefix = os.path.commonprefix([root_dir, project_dir])
  607. return fullname[len(prefix) + 1:]
  608. # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
  609. # searching up from the current path.
  610. root_dir = os.path.dirname(fullname)
  611. while (root_dir != os.path.dirname(root_dir) and
  612. not os.path.exists(os.path.join(root_dir, ".git")) and
  613. not os.path.exists(os.path.join(root_dir, ".hg")) and
  614. not os.path.exists(os.path.join(root_dir, ".svn"))):
  615. root_dir = os.path.dirname(root_dir)
  616. if (os.path.exists(os.path.join(root_dir, ".git")) or
  617. os.path.exists(os.path.join(root_dir, ".hg")) or
  618. os.path.exists(os.path.join(root_dir, ".svn"))):
  619. prefix = os.path.commonprefix([root_dir, project_dir])
  620. return fullname[len(prefix) + 1:]
  621. # Don't know what to do; header guard warnings may be wrong...
  622. return fullname
  623. def Split(self):
  624. """Splits the file into the directory, basename, and extension.
  625. For 'chrome/browser/browser.cc', Split() would
  626. return ('chrome/browser', 'browser', '.cc')
  627. Returns:
  628. A tuple of (directory, basename, extension).
  629. """
  630. googlename = self.RepositoryName()
  631. project, rest = os.path.split(googlename)
  632. return (project,) + os.path.splitext(rest)
  633. def BaseName(self):
  634. """File base name - text after the final slash, before the final period."""
  635. return self.Split()[1]
  636. def Extension(self):
  637. """File extension - text following the final period."""
  638. return self.Split()[2]
  639. def NoExtension(self):
  640. """File has no source file extension."""
  641. return '/'.join(self.Split()[0:2])
  642. def IsSource(self):
  643. """File has a source file extension."""
  644. return self.Extension()[1:] in EXTENSIONS
  645. def _ShouldPrintError(category, confidence, linenum):
  646. """If confidence >= verbose, category passes filter and is not suppressed."""
  647. # There are three ways we might decide not to print an error message:
  648. # a "NOLINT(category)" comment appears in the source,
  649. # the verbosity level isn't high enough, or the filters filter it out.
  650. if IsErrorSuppressedByNolint(category, linenum):
  651. return False
  652. if confidence < _cpplint_state.verbose_level:
  653. return False
  654. is_filtered = False
  655. for one_filter in _Filters():
  656. if one_filter.startswith('-'):
  657. if category.startswith(one_filter[1:]):
  658. is_filtered = True
  659. elif one_filter.startswith('+'):
  660. if category.startswith(one_filter[1:]):
  661. is_filtered = False
  662. else:
  663. assert False # should have been checked for in SetFilter.
  664. if is_filtered:
  665. return False
  666. return True
  667. def Error(filename, linenum, category, confidence, message):
  668. """Logs the fact we've found a lint error.
  669. We log where the error was found, and also our confidence in the error,
  670. that is, how certain we are this is a legitimate style regression, and
  671. not a misidentification or a use that's sometimes justified.
  672. False positives can be suppressed by the use of
  673. "cpplint(category)" comments on the offending line. These are
  674. parsed into _error_suppressions.
  675. Args:
  676. filename: The name of the file containing the error.
  677. linenum: The number of the line containing the error.
  678. category: A string used to describe the "category" this bug
  679. falls under: "whitespace", say, or "runtime". Categories
  680. may have a hierarchy separated by slashes: "whitespace/indent".
  681. confidence: A number from 1-5 representing a confidence score for
  682. the error, with 5 meaning that we are certain of the problem,
  683. and 1 meaning that it could be a legitimate construct.
  684. message: The error message.
  685. """
  686. if _ShouldPrintError(category, confidence, linenum):
  687. _cpplint_state.IncrementErrorCount(category)
  688. if _cpplint_state.output_format == 'vs7':
  689. sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
  690. filename, linenum, message, category, confidence))
  691. else:
  692. m = '%s:%s: %s [%s] [%d]\n' % (
  693. filename, linenum, message, category, confidence)
  694. sys.stderr.write(m)
  695. # Matches standard C++ escape esequences per 2.13.2.3 of the C++ standard.
  696. _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
  697. r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
  698. # Matches strings. Escape codes should already be removed by ESCAPES.
  699. _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"')
  700. # Matches characters. Escape codes should already be removed by ESCAPES.
  701. _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'")
  702. # Matches multi-line C++ comments.
  703. # This RE is a little bit more complicated than one might expect, because we
  704. # have to take care of space removals tools so we can handle comments inside
  705. # statements better.
  706. # The current rule is: We only clear spaces from both sides when we're at the
  707. # end of the line. Otherwise, we try to remove spaces from the right side,
  708. # if this doesn't work we try on left side but only if there's a non-character
  709. # on the right.
  710. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
  711. r"""(\s*/\*.*\*/\s*$|
  712. /\*.*\*/\s+|
  713. \s+/\*.*\*/(?=\W)|
  714. /\*.*\*/)""", re.VERBOSE)
  715. def IsCppString(line):
  716. """Does line terminate so, that the next symbol is in string constant.
  717. This function does not consider single-line nor multi-line comments.
  718. Args:
  719. line: is a partial line of code starting from the 0..n.
  720. Returns:
  721. True, if next character appended to 'line' is inside a
  722. string constant.
  723. """
  724. line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
  725. return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
  726. def FindNextMultiLineCommentStart(lines, lineix):
  727. """Find the beginning marker for a multiline comment."""
  728. while lineix < len(lines):
  729. if lines[lineix].strip().startswith('/*'):
  730. # Only return this marker if the comment goes beyond this line
  731. if lines[lineix].strip().find('*/', 2) < 0:
  732. return lineix
  733. lineix += 1
  734. return len(lines)
  735. def FindNextMultiLineCommentEnd(lines, lineix):
  736. """We are inside a comment, find the end marker."""
  737. while lineix < len(lines):
  738. if lines[lineix].strip().endswith('*/'):
  739. return lineix
  740. lineix += 1
  741. return len(lines)
  742. def RemoveMultiLineCommentsFromRange(lines, begin, end):
  743. """Clears a range of lines for multi-line comments."""
  744. # Having // dummy comments makes the lines non-empty, so we will not get
  745. # unnecessary blank line warnings later in the code.
  746. for i in range(begin, end):
  747. lines[i] = '// dummy'
  748. def RemoveMultiLineComments(filename, lines, error):
  749. """Removes multiline (c-style) comments from lines."""
  750. lineix = 0
  751. while lineix < len(lines):
  752. lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
  753. if lineix_begin >= len(lines):
  754. return
  755. lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
  756. if lineix_end >= len(lines):
  757. error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
  758. 'Could not find end of multi-line comment')
  759. return
  760. RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
  761. lineix = lineix_end + 1
  762. def CleanseComments(line):
  763. """Removes //-comments and single-line C-style /* */ comments.
  764. Args:
  765. line: A line of C++ source.
  766. Returns:
  767. The line with single-line comments removed.
  768. """
  769. commentpos = line.find('//')
  770. if commentpos != -1 and not IsCppString(line[:commentpos]):
  771. line = line[:commentpos].rstrip()
  772. # get rid of /* ... */
  773. return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
  774. class CleansedLines(object):
  775. """Holds 3 copies of all lines with different preprocessing applied to them.
  776. 1) elided member contains lines without strings and comments,
  777. 2) lines member contains lines without comments, and
  778. 3) raw member contains all the lines without processing.
  779. All these three members are of <type 'list'>, and of the same length.
  780. """
  781. def __init__(self, lines):
  782. self.elided = []
  783. self.lines = []
  784. self.raw_lines = lines
  785. self.num_lines = len(lines)
  786. for linenum in range(len(lines)):
  787. self.lines.append(CleanseComments(lines[linenum]))
  788. elided = self._CollapseStrings(lines[linenum])
  789. self.elided.append(CleanseComments(elided))
  790. def NumLines(self):
  791. """Returns the number of lines represented."""
  792. return self.num_lines
  793. @staticmethod
  794. def _CollapseStrings(elided):
  795. """Collapses strings and chars on a line to simple "" or '' blocks.
  796. We nix strings first so we're not fooled by text like '"http://"'
  797. Args:
  798. elided: The line being processed.
  799. Returns:
  800. The line with collapsed strings.
  801. """
  802. if not _RE_PATTERN_INCLUDE.match(elided):
  803. # Remove escaped characters first to make quote/single quote collapsing
  804. # basic. Things that look like escaped characters shouldn't occur
  805. # outside of strings and chars.
  806. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
  807. elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
  808. elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
  809. return elided
  810. def CloseExpression(clean_lines, linenum, pos):
  811. """If input points to ( or { or [, finds the position that closes it.
  812. If lines[linenum][pos] points to a '(' or '{' or '[', finds the
  813. linenum/pos that correspond to the closing of the expression.
  814. Args:
  815. clean_lines: A CleansedLines instance containing the file.
  816. linenum: The number of the line to check.
  817. pos: A position on the line.
  818. Returns:
  819. A tuple (line, linenum, pos) pointer *past* the closing brace, or
  820. (line, len(lines), -1) if we never find a close. Note we ignore
  821. strings and comments when matching; and the line we return is the
  822. 'cleansed' line at linenum.
  823. """
  824. line = clean_lines.elided[linenum]
  825. startchar = line[pos]
  826. if startchar not in '({[':
  827. return (line, clean_lines.NumLines(), -1)
  828. if startchar == '(': endchar = ')'
  829. if startchar == '[': endchar = ']'
  830. if startchar == '{': endchar = '}'
  831. num_open = line.count(startchar) - line.count(endchar)
  832. while linenum < clean_lines.NumLines() and num_open > 0:
  833. linenum += 1
  834. line = clean_lines.elided[linenum]
  835. num_open += line.count(startchar) - line.count(endchar)
  836. # OK, now find the endchar that actually got us back to even
  837. endpos = len(line)
  838. while num_open >= 0:
  839. endpos = line.rfind(')', 0, endpos)
  840. num_open -= 1 # chopped off another )
  841. return (line, linenum, endpos + 1)
  842. def CheckForCopyright(filename, lines, error):
  843. """Logs an error if no Copyright message appears at the top of the file."""
  844. # We'll say it should occur by line 10. Don't forget there's a
  845. # dummy line at the front.
  846. for line in range(1, min(len(lines), 11)):
  847. if re.search(r'Copyright', lines[line], re.I):
  848. break
  849. else: # means no copyright line was found
  850. error(filename, 0, 'legal/copyright', 5,
  851. 'No copyright message found. '
  852. 'You should have a line: "Copyright [year] <Copyright Owner>"')
  853. def GetHeaderGuardCPPVariable(filename):
  854. """Returns the CPP variable that should be used as a header guard.
  855. Args:
  856. filename: The name of a C++ header file.
  857. Returns:
  858. The CPP variable that should be used as a header guard in the
  859. named file.
  860. """
  861. # Restores original filename in case that cpplint is invoked from Emacs's
  862. # flymake.
  863. filename = re.sub(r'_flymake\.h$', '.h', filename)
  864. fileinfo = FileInfo(filename)
  865. return re.sub(r'[-./\s]', '_', fileinfo.RepositoryName()).upper() + '_'
  866. def CheckForHeaderGuard(filename, lines, error):
  867. """Checks that the file contains a header guard.
  868. Logs an error if no #ifndef header guard is present. For other
  869. headers, checks that the full pathname is used.
  870. Args:
  871. filename: The name of the C++ header file.
  872. lines: An array of strings, each representing a line of the file.
  873. error: The function to call with any errors found.
  874. """
  875. cppvar = GetHeaderGuardCPPVariable(filename)
  876. ifndef = None
  877. ifndef_linenum = 0
  878. define = None
  879. endif = None
  880. endif_linenum = 0
  881. for linenum, line in enumerate(lines):
  882. linesplit = line.split()
  883. if len(linesplit) >= 2:
  884. # find the first occurrence of #ifndef and #define, save arg
  885. if not ifndef and linesplit[0] == '#ifndef':
  886. # set ifndef to the header guard presented on the #ifndef line.
  887. ifndef = linesplit[1]
  888. ifndef_linenum = linenum
  889. if not define and linesplit[0] == '#define':
  890. define = linesplit[1]
  891. # find the last occurrence of #endif, save entire line
  892. if line.startswith('#endif'):
  893. endif = line
  894. endif_linenum = linenum
  895. if not ifndef:
  896. error(filename, 0, 'build/header_guard', 5,
  897. 'No #ifndef header guard found, suggested CPP variable is: %s' %
  898. cppvar)
  899. return
  900. if not define:
  901. error(filename, 0, 'build/header_guard', 5,
  902. 'No #define header guard found, suggested CPP variable is: %s' %
  903. cppvar)
  904. return
  905. # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
  906. # for backward compatibility.
  907. if ifndef != cppvar:
  908. error_level = 0
  909. if ifndef != cppvar + '_':
  910. error_level = 5
  911. ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum,
  912. error)
  913. error(filename, ifndef_linenum, 'build/header_guard', error_level,
  914. '#ifndef header guard has wrong style, please use: %s' % cppvar)
  915. if define != ifndef:
  916. error(filename, 0, 'build/header_guard', 5,
  917. '#ifndef and #define don\'t match, suggested CPP variable is: %s' %
  918. cppvar)
  919. return
  920. if endif != ('#endif // %s' % cppvar):
  921. error_level = 0
  922. if endif != ('#endif // %s' % (cppvar + '_')):
  923. error_level = 5
  924. ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum,
  925. error)
  926. error(filename, endif_linenum, 'build/header_guard', error_level,
  927. '#endif line should be "#endif // %s"' % cppvar)
  928. def CheckForUnicodeReplacementCharacters(filename, lines, error):
  929. """Logs an error for each line containing Unicode replacement characters.
  930. These indicate that either the file contained invalid UTF-8 (likely)
  931. or Unicode replacement characters (which it shouldn't). Note that
  932. it's possible for this to throw off line numbering if the invalid
  933. UTF-8 occurred adjacent to a newline.
  934. Args:
  935. filename: The name of the current file.
  936. lines: An array of strings, each representing a line of the file.
  937. error: The function to call with any errors found.
  938. """
  939. for linenum, line in enumerate(lines):
  940. if u('\ufffd') in line:
  941. error(filename, linenum, 'readability/utf8', 5,
  942. 'Line contains invalid UTF-8 (or Unicode replacement character).')
  943. def CheckForNewlineAtEOF(filename, lines, error):
  944. """Logs an error if there is no newline char at the end of the file.
  945. Args:
  946. filename: The name of the current file.
  947. lines: An array of strings, each representing a line of the file.
  948. error: The function to call with any errors found.
  949. """
  950. # The array lines() was created by adding two newlines to the
  951. # original file (go figure), then splitting on \n.
  952. # To verify that the file ends in \n, we just have to make sure the
  953. # last-but-two element of lines() exists and is empty.
  954. if len(lines) < 3 or lines[-2]:
  955. error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
  956. 'Could not find a newline character at the end of the file.')
  957. def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
  958. """Logs an error if we see /* ... */ or "..." that extend past one line.
  959. /* ... */ comments are legit inside macros, for one line.
  960. Otherwise, we prefer // comments, so it's ok to warn about the
  961. other. Likewise, it's ok for strings to extend across multiple
  962. lines, as long as a line continuation character (backslash)
  963. terminates each line. Although not currently prohibited by the C++
  964. style guide, it's ugly and unnecessary. We don't do well with either
  965. in this lint program, so we warn about both.
  966. Args:
  967. filename: The name of the current file.
  968. clean_lines: A CleansedLines instance containing the file.
  969. linenum: The number of the line to check.
  970. error: The function to call with any errors found.
  971. """
  972. line = clean_lines.elided[linenum]
  973. # Remove all \\ (escaped backslashes) from the line. They are OK, and the
  974. # second (escaped) slash may trigger later \" detection erroneously.
  975. line = line.replace('\\\\', '')
  976. if line.count('/*') > line.count('*/'):
  977. error(filename, linenum, 'readability/multiline_comment', 5,
  978. 'Complex multi-line /*...*/-style comment found. '
  979. 'Lint may give bogus warnings. '
  980. 'Consider replacing these with //-style comments, '
  981. 'with #if 0...#endif, '
  982. 'or with more clearly structured multi-line comments.')
  983. if (line.count('"') - line.count('\\"')) % 2:
  984. error(filename, linenum, 'readability/multiline_string', 5,
  985. 'Multi-line string ("...") found. This lint script doesn\'t '
  986. 'do well with such strings, and may give bogus warnings. They\'re '
  987. 'ugly and unnecessary, and you should use concatenation instead".')
  988. threading_list = (
  989. ('asctime(', 'asctime_r('),
  990. ('ctime(', 'ctime_r('),
  991. ('getgrgid(', 'getgrgid_r('),
  992. ('getgrnam(', 'getgrnam_r('),
  993. ('getlogin(', 'getlogin_r('),
  994. ('getpwnam(', 'getpwnam_r('),
  995. ('getpwuid(', 'getpwuid_r('),
  996. ('gmtime(', 'gmtime_r('),
  997. ('localtime(', 'localtime_r('),
  998. ('rand(', 'rand_r('),
  999. ('readdir(', 'readdir_r('),
  1000. ('strtok(', 'strtok_r('),
  1001. ('ttyname(', 'ttyname_r('),
  1002. )
  1003. def CheckPosixThreading(filename, clean_lines, linenum, error):
  1004. """Checks for calls to thread-unsafe functions.
  1005. Much code has been originally written without consideration of
  1006. multi-threading. Also, engineers are relying on their old experience;
  1007. they have learned posix before threading extensions were added. These
  1008. tests guide the engineers to use thread-safe functions (when using
  1009. posix directly).
  1010. Args:
  1011. filename: The name of the current file.
  1012. clean_lines: A CleansedLines instance containing the file.
  1013. linenum: The number of the line to check.
  1014. error: The function to call with any errors found.
  1015. """
  1016. line = clean_lines.elided[linenum]
  1017. for single_thread_function, multithread_safe_function in threading_list:
  1018. ix = line.find(single_thread_function)
  1019. # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
  1020. if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
  1021. line[ix - 1] not in ('_', '.', '>'))):
  1022. error(filename, linenum, 'runtime/threadsafe_fn', 2,
  1023. 'Consider using ' + multithread_safe_function +
  1024. '...) instead of ' + single_thread_function +
  1025. '...) for improved thread safety.')
  1026. # Matches invalid increment: *count++, which moves pointer instead of
  1027. # incrementing a value.
  1028. _RE_PATTERN_INVALID_INCREMENT = re.compile(
  1029. r'^\s*\*\w+(\+\+|--);')
  1030. def CheckInvalidIncrement(filename, clean_lines, linenum, error):
  1031. """Checks for invalid increment *count++.
  1032. For example following function:
  1033. void increment_counter(int* count) {
  1034. *count++;
  1035. }
  1036. is invalid, because it effectively does count++, moving pointer, and should
  1037. be replaced with ++*count, (*count)++ or *count += 1.
  1038. Args:
  1039. filename: The name of the current file.
  1040. clean_lines: A CleansedLines instance containing the file.
  1041. linenum: The number of the line to check.
  1042. error: The function to call with any errors found.
  1043. """
  1044. line = clean_lines.elided[linenum]
  1045. if _RE_PATTERN_INVALID_INCREMENT.match(line):
  1046. error(filename, linenum, 'runtime/invalid_increment', 5,
  1047. 'Changing pointer instead of value (or unused value of operator*).')
  1048. class _ClassInfo(object):
  1049. """Stores information about a class."""
  1050. def __init__(self, name, clean_lines, linenum):
  1051. self.name = name
  1052. self.linenum = linenum
  1053. self.seen_open_brace = False
  1054. self.is_derived = False
  1055. self.virtual_method_linenumber = None
  1056. self.has_virtual_destructor = False
  1057. self.brace_depth = 0
  1058. # Try to find the end of the class. This will be confused by things like:
  1059. # class A {
  1060. # } *x = { ...
  1061. #
  1062. # But it's still good enough for CheckSectionSpacing.
  1063. self.last_line = 0
  1064. depth = 0
  1065. for i in range(linenum, clean_lines.NumLines()):
  1066. line = clean_lines.lines[i]
  1067. depth += line.count('{') - line.count('}')
  1068. if not depth:
  1069. self.last_line = i
  1070. break
  1071. class _ClassState(object):
  1072. """Holds the current state of the parse relating to class declarations.
  1073. It maintains a stack of _ClassInfos representing the parser's guess
  1074. as to the current nesting of class declarations. The innermost class
  1075. is at the top (back) of the stack. Typically, the stack will either
  1076. be empty or have exactly one entry.
  1077. """
  1078. def __init__(self):
  1079. self.classinfo_stack = []
  1080. def CheckFinished(self, filename, error):
  1081. """Checks that all classes have been completely parsed.
  1082. Call this when all lines in a file have been processed.
  1083. Args:
  1084. filename: The name of the current file.
  1085. error: The function to call with any errors found.
  1086. """
  1087. if self.classinfo_stack:
  1088. # Note: This test can result in false positives if #ifdef constructs
  1089. # get in the way of brace matching. See the testBuildClass test in
  1090. # cpplint_unittest.py for an example of this.
  1091. error(filename, self.classinfo_stack[0].linenum, 'build/class', 5,
  1092. 'Failed to find complete declaration of class %s' %
  1093. self.classinfo_stack[0].name)
  1094. def CheckForNonStandardConstructs(filename, clean_lines, linenum,
  1095. class_state, error):
  1096. """Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
  1097. Complain about several constructs which gcc-2 accepts, but which are
  1098. not standard C++. Warning about these in lint is one way to ease the
  1099. transition to new compilers.
  1100. - put storage class first (e.g. "static const" instead of "const static").
  1101. - "%lld" instead of %qd" in printf-type functions.
  1102. - "%1$d" is non-standard in printf-type functions.
  1103. - "\%" is an undefined character escape sequence.
  1104. - text after #endif is not allowed.
  1105. - invalid inner-style forward declaration.
  1106. - >? and <? operators, and their >?= and <?= cousins.
  1107. - classes with virtual methods need virtual destructors (compiler warning
  1108. available, but not turned on yet.)
  1109. Additionally, check for constructor/destructor style violations and reference
  1110. members, as it is very convenient to do so while checking for
  1111. gcc-2 compliance.
  1112. Args:
  1113. filename: The name of the current file.
  1114. clean_lines: A CleansedLines instance containing the file.
  1115. linenum: The number of the line to check.
  1116. class_state: A _ClassState instance which maintains information about
  1117. the current stack of nested class declarations being parsed.
  1118. error: A callable to which errors are reported, which takes 4 arguments:
  1119. filename, line number, error level, and message
  1120. """
  1121. # Remove comments from the line, but leave in strings for now.
  1122. line = clean_lines.lines[linenum]
  1123. if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
  1124. error(filename, linenum, 'runtime/printf_format', 3,
  1125. '%q in format strings is deprecated. Use %ll instead.')
  1126. if Search(r'printf\s*\(.*".*%\d+\$', line):
  1127. error(filename, linenum, 'runtime/printf_format', 2,
  1128. '%N$ formats are unconventional. Try rewriting to avoid them.')
  1129. # Remove escaped backslashes before looking for undefined escapes.
  1130. line = line.replace('\\\\', '')
  1131. if Search(r'("|\').*\\(%|\[|\(|{)', line):
  1132. error(filename, linenum, 'build/printf_format', 3,
  1133. '%, [, (, and { are undefined character escapes. Unescape them.')
  1134. # For the rest, work with both comments and strings removed.
  1135. line = clean_lines.elided[linenum]
  1136. if Search(r'\b(const|volatile|void|char|short|int|long'
  1137. r'|float|double|signed|unsigned'
  1138. r'|schar|u?int8|u?int16|u?int32|u?int64)'
  1139. r'\s+(auto|register|static|extern|typedef)\b',
  1140. line):
  1141. error(filename, linenum, 'build/storage_class', 5,
  1142. 'Storage class (static, extern, typedef, etc) should be first.')
  1143. if Match(r'\s*#\s*endif\s*[^/\s]+', line):
  1144. error(filename, linenum, 'build/endif_comment', 5,
  1145. 'Uncommented text after #endif is non-standard. Use a comment.')
  1146. if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
  1147. error(filename, linenum, 'build/forward_decl', 5,
  1148. 'Inner-style forward declarations are invalid. Remove this line.')
  1149. if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
  1150. line):
  1151. error(filename, linenum, 'build/deprecated', 3,
  1152. '>? and <? (max and min) operators are non-standard and deprecated.')
  1153. if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
  1154. # TODO(unknown): Could it be expanded safely to arbitrary references,
  1155. # without triggering too many false positives? The first
  1156. # attempt triggered 5 warnings for mostly benign code in the regtest, hence
  1157. # the restriction.
  1158. # Here's the original regexp, for the reference:
  1159. # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
  1160. # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
  1161. error(filename, linenum, 'runtime/member_string_references', 2,
  1162. 'const string& members are dangerous. It is much better to use '
  1163. 'alternatives, such as pointers or simple constants.')
  1164. # Track class entry and exit, and attempt to find cases within the
  1165. # class declaration that don't meet the C++ style
  1166. # guidelines. Tracking is very dependent on the code matching Google
  1167. # style guidelines, but it seems to perform well enough in testing
  1168. # to be a worthwhile addition to the checks.
  1169. classinfo_stack = class_state.classinfo_stack
  1170. # Look for a class declaration. The regexp accounts for decorated classes
  1171. # such as in:
  1172. # class LOCKABLE API Object {
  1173. # };
  1174. class_decl_match = Match(
  1175. r'\s*(template\s*<[\w\s<>,:]*>\s*)?'
  1176. '(class|struct)\s+([A-Z_]+\s+)*(\w+(::\w+)*)', line)
  1177. if class_decl_match:
  1178. classinfo_stack.append(_ClassInfo(
  1179. class_decl_match.group(4), clean_lines, linenum))
  1180. # Everything else in this function uses the top of the stack if it's
  1181. # not empty.
  1182. if not classinfo_stack:
  1183. return
  1184. classinfo = classinfo_stack[-1]
  1185. # If the opening brace hasn't been seen look for it and also
  1186. # parent class declarations.
  1187. if not classinfo.seen_open_brace:
  1188. # If the line has a ';' in it, assume it's a forward declaration or
  1189. # a single-line class declaration, which we won't process.
  1190. if line.find(';') != -1:
  1191. classinfo_stack.pop()
  1192. return
  1193. classinfo.seen_open_brace = (line.find('{') != -1)
  1194. # Look for a bare ':'
  1195. if Search('(^|[^:]):($|[^:])', line):
  1196. classinfo.is_derived = True
  1197. if not classinfo.seen_open_brace:
  1198. return # Everything else in this function is for after open brace
  1199. # The class may have been declared with namespace or classname qualifiers.
  1200. # The constructor and destructor will not have those qualifiers.
  1201. base_classname = classinfo.name.split('::')[-1]
  1202. # Look for single-argument constructors that aren't marked explicit.
  1203. # Technically a valid construct, but against style.
  1204. args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
  1205. % re.escape(base_classname),
  1206. line)
  1207. if (args and
  1208. args.group(1) != 'void' and
  1209. not Match(r'(const\s+)?%s\s*(?:<\w+>\s*)?&' % re.escape(base_classname),
  1210. args.group(1).strip())):
  1211. error(filename, linenum, 'runtime/explicit', 5,
  1212. 'Single-argument constructors should be marked explicit.')
  1213. # Look for methods declared virtual.
  1214. if Search(r'\bvirtual\b', line):
  1215. classinfo.virtual_method_linenumber = linenum
  1216. # Only look for a destructor declaration on the same line. It would
  1217. # be extremely unlikely for the destructor declaration to occupy
  1218. # more than one line.
  1219. if Search(r'~%s\s*\(' % base_classname, line):
  1220. classinfo.has_virtual_destructor = True
  1221. # Look for class end.
  1222. brace_depth = classinfo.brace_depth
  1223. brace_depth = brace_depth + line.count('{') - line.count('}')
  1224. if brace_depth <= 0:
  1225. classinfo = classinfo_stack.pop()
  1226. # Try to detect missing virtual destructor declarations.
  1227. # For now, only warn if a non-derived class with virtual methods lacks
  1228. # a virtual destructor. This is to make it less likely that people will
  1229. # declare derived virtual destructors without declaring the base
  1230. # destructor virtual.
  1231. if ((classinfo.virtual_method_linenumber is not None) and
  1232. (not classinfo.has_virtual_destructor) and
  1233. (not classinfo.is_derived)): # Only warn for base classes
  1234. error(filename, classinfo.linenum, 'runtime/virtual', 4,
  1235. 'The class %s probably needs a virtual destructor due to '
  1236. 'having virtual method(s), one declared at line %d.'
  1237. % (classinfo.name, classinfo.virtual_method_linenumber))
  1238. else:
  1239. classinfo.brace_depth = brace_depth
  1240. def CheckSpacingForFunctionCall(filename, line, linenum, error):
  1241. """Checks for the correctness of various spacing around function calls.
  1242. Args:
  1243. filename: The name of the current file.
  1244. line: The text of the line to check.
  1245. linenum: The number of the line to check.
  1246. error: The function to call with any errors found.
  1247. """
  1248. # Since function calls often occur inside if/for/while/switch
  1249. # expressions - which have their own, more liberal conventions - we
  1250. # first see if we should be looking inside such an expression for a
  1251. # function call, to which we can apply more strict standards.
  1252. fncall = line # if there's no control flow construct, look at whole line
  1253. for pattern in (r'\bif\s*\((.*)\)\s*{',
  1254. r'\bfor\s*\((.*)\)\s*{',
  1255. r'\bwhile\s*\((.*)\)\s*[{;]',
  1256. r'\bswitch\s*\((.*)\)\s*{'):
  1257. match = Search(pattern, line)
  1258. if match:
  1259. fncall = match.group(1) # look inside the parens for function calls
  1260. break
  1261. # Except in if/for/while/switch, there should never be space
  1262. # immediately inside parens (eg "f( 3, 4 )"). We make an exception
  1263. # for nested parens ( (a+b) + c ). Likewise, there should never be
  1264. # a space before a ( when it's a function argument. I assume it's a
  1265. # function argument when the char before the whitespace is legal in
  1266. # a function name (alnum + _) and we're not starting a macro. Also ignore
  1267. # pointers and references to arrays and functions coz they're too tricky:
  1268. # we use a very simple way to recognize these:
  1269. # " (something)(maybe-something)" or
  1270. # " (something)(maybe-something," or
  1271. # " (something)[something]"
  1272. # Note that we assume the contents of [] to be short enough that
  1273. # they'll never need to wrap.
  1274. if ( # Ignore control structures.
  1275. not Search(r'\b(if|for|while|switch|return|delete)\b', fncall) and
  1276. # Ignore pointers/references to functions.
  1277. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
  1278. # Ignore pointers/references to arrays.
  1279. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
  1280. if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
  1281. error(filename, linenum, 'whitespace/parens', 4,
  1282. 'Extra space after ( in function call')
  1283. elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
  1284. error(filename, linenum, 'whitespace/parens', 2,
  1285. 'Extra space after (')
  1286. if (Search(r'\w\s+\(', fncall) and
  1287. not Search(r'#\s*define|typedef', fncall)):
  1288. error(filename, linenum, 'whitespace/parens', 4,
  1289. 'Extra space before ( in function call')
  1290. # If the ) is followed only by a newline or a { + newline, assume it's
  1291. # part of a control statement (if/while/etc), and don't complain
  1292. if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
  1293. # If the closing parenthesis is preceded by only whitespaces,
  1294. # try to give a more descriptive error message.
  1295. if Search(r'^\s+\)', fncall):
  1296. error(filename, linenum, 'whitespace/parens', 2,
  1297. 'Closing ) should be moved to the previous line')
  1298. else:
  1299. error(filename, linenum, 'whitespace/parens', 2,
  1300. 'Extra space before )')
  1301. def IsBlankLine(line):
  1302. """Returns true if the given line is blank.
  1303. We consider a line to be blank if the line is empty or consists of
  1304. only white spaces.
  1305. Args:
  1306. line: A line of a string.
  1307. Returns:
  1308. True, if the given line is blank.
  1309. """
  1310. return not line or line.isspace()
  1311. def CheckForFunctionLengths(filename, clean_lines, linenum,
  1312. function_state, error):
  1313. """Reports for long function bodies.
  1314. For an overview why this is done, see:
  1315. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
  1316. Uses a simplistic algorithm assuming other style guidelines
  1317. (especially spacing) are followed.
  1318. Only checks unindented functions, so class members are unchecked.
  1319. Trivial bodies are unchecked, so constructors with huge initializer lists
  1320. may be missed.
  1321. Blank/comment lines are not counted so as to avoid encouraging the removal
  1322. of vertical space and comments just to get through a lint check.
  1323. NOLINT *on the last line of a function* disables this check.
  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. function_state: Current function name and lines in body so far.
  1329. error: The function to call with any errors found.
  1330. """
  1331. lines = clean_lines.lines
  1332. line = lines[linenum]
  1333. raw = clean_lines.raw_lines
  1334. raw_line = raw[linenum]
  1335. joined_line = ''
  1336. starting_func = False
  1337. regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
  1338. match_result = Match(regexp, line)
  1339. if match_result:
  1340. # If the name is all caps and underscores, figure it's a macro and
  1341. # ignore it, unless it's TEST or TEST_F.
  1342. function_name = match_result.group(1).split()[-1]
  1343. if function_name == 'TEST' or function_name == 'TEST_F' or (
  1344. not Match(r'[A-Z_]+$', function_name)):
  1345. starting_func = True
  1346. if starting_func:
  1347. body_found = False
  1348. for start_linenum in range(linenum, clean_lines.NumLines()):
  1349. start_line = lines[start_linenum]
  1350. joined_line += ' ' + start_line.lstrip()
  1351. if Search(r'(;|})', start_line): # Declarations and trivial functions
  1352. body_found = True
  1353. break # ... ignore
  1354. elif Search(r'{', start_line):
  1355. body_found = True
  1356. function = Search(r'((\w|:)*)\(', line).group(1)
  1357. if Match(r'TEST', function): # Handle TEST... macros
  1358. parameter_regexp = Search(r'(\(.*\))', joined_line)
  1359. if parameter_regexp: # Ignore bad syntax
  1360. function += parameter_regexp.group(1)
  1361. else:
  1362. function += '()'
  1363. function_state.Begin(function)
  1364. break
  1365. if not body_found:
  1366. # No body for the function (or evidence of a non-function) was found.
  1367. error(filename, linenum, 'readability/fn_size', 5,
  1368. 'Lint failed to find start of function body.')
  1369. elif Match(r'^\}\s*$', line): # function end
  1370. function_state.Check(error, filename, linenum)
  1371. function_state.End()
  1372. elif not Match(r'^\s*$', line):
  1373. function_state.Count() # Count non-blank/non-comment lines.
  1374. _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
  1375. def CheckComment(comment, filename, linenum, error):
  1376. """Checks for common mistakes in TODO comments.
  1377. Args:
  1378. comment: The text of the comment from the line in question.
  1379. filename: The name of the current file.
  1380. linenum: The number of the line to check.
  1381. error: The function to call with any errors found.
  1382. """
  1383. match = _RE_PATTERN_TODO.match(comment)
  1384. if match:
  1385. # One whitespace is correct; zero whitespace is handled elsewhere.
  1386. leading_whitespace = match.group(1)
  1387. if len(leading_whitespace) > 1:
  1388. error(filename, linenum, 'whitespace/todo', 2,
  1389. 'Too many spaces before TODO')
  1390. username = match.group(2)
  1391. if not username:
  1392. error(filename, linenum, 'readability/todo', 2,
  1393. 'Missing username in TODO; it should look like '
  1394. '"// TODO(my_username): Stuff."')
  1395. middle_whitespace = match.group(3)
  1396. # Comparisons made explicit for correctness -- pylint: disable-msg=C6403
  1397. if middle_whitespace != ' ' and middle_whitespace != '':
  1398. error(filename, linenum, 'whitespace/todo', 2,
  1399. 'TODO(my_username) should be followed by a space')
  1400. def CheckSpacing(filename, clean_lines, linenum, error):
  1401. """Checks for the correctness of various spacing issues in the code.
  1402. Things we check for: spaces around operators, spaces after
  1403. if/for/while/switch, no spaces around parens in function calls, two
  1404. spaces between code and comment, don't start a block with a blank
  1405. line, don't end a function with a blank line, don't add a blank line
  1406. after public/protected/private, don't have too many blank lines in a row.
  1407. Args:
  1408. filename: The name of the current file.
  1409. clean_lines: A CleansedLines instance containing the file.
  1410. linenum: The number of the line to check.
  1411. error: The function to call with any errors found.
  1412. """
  1413. raw = clean_lines.raw_lines
  1414. line = raw[linenum]
  1415. # Before nixing comments, check if the line is blank for no good
  1416. # reason. This includes the first line after a block is opened, and
  1417. # blank lines at the end of a function (ie, right before a line like '}'
  1418. if IsBlankLine(line):
  1419. elided = clean_lines.elided
  1420. prev_line = elided[linenum - 1]
  1421. prevbrace = prev_line.rfind('{')
  1422. # TODO(unknown): Don't complain if line before blank line, and line after,
  1423. # both start with alnums and are indented the same amount.
  1424. # This ignores whitespace at the start of a namespace block
  1425. # because those are not usually indented.
  1426. if (prevbrace != -1 and prev_line[prevbrace:].find('}') == -1
  1427. and prev_line[:prevbrace].find('namespace') == -1):
  1428. # OK, we have a blank line at the start of a code block. Before we
  1429. # complain, we check if it is an exception to the rule: The previous
  1430. # non-empty line has the parameters of a function header that are indented
  1431. # 4 spaces (because they did not fit in a 80 column line when placed on
  1432. # the same line as the function name). We also check for the case where
  1433. # the previous line is indented 6 spaces, which may happen when the
  1434. # initializers of a constructor do not fit into a 80 column line.
  1435. exception = False
  1436. if Match(r' {6}\w', prev_line): # Initializer list?
  1437. # We are looking for the opening column of initializer list, which
  1438. # should be indented 4 spaces to cause 6 space indentation afterwards.
  1439. search_position = linenum-2
  1440. while (search_position >= 0
  1441. and Match(r' {6}\w', elided[search_position])):
  1442. search_position -= 1
  1443. exception = (search_position >= 0
  1444. and elided[search_position][:5] == ' :')
  1445. else:
  1446. # Search for the function arguments or an initializer list. We use a
  1447. # simple heuristic here: If the line is indented 4 spaces; and we have a
  1448. # closing paren, without the opening paren, followed by an opening brace
  1449. # or colon (for initializer lists) we assume that it is the last line of
  1450. # a function header. If we have a colon indented 4 spaces, it is an
  1451. # initializer list.
  1452. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
  1453. prev_line)
  1454. or Match(r' {4}:', prev_line))
  1455. if not exception:
  1456. error(filename, linenum, 'whitespace/blank_line', 2,
  1457. 'Blank line at the start of a code block. Is this needed?')
  1458. # This doesn't ignore whitespace at the end of a namespace block
  1459. # because that is too hard without pairing open/close braces;
  1460. # however, a special exception is made for namespace closing
  1461. # brackets which have a comment containing "namespace".
  1462. #
  1463. # Also, ignore blank lines at the end of a block in a long if-else
  1464. # chain, like this:
  1465. # if (condition1) {
  1466. # // Something followed by a blank line
  1467. #
  1468. # } else if (condition2) {
  1469. # // Something else
  1470. # }
  1471. if linenum + 1 < clean_lines.NumLines():
  1472. next_line = raw[linenum + 1]
  1473. if (next_line
  1474. and Match(r'\s*}', next_line)
  1475. and next_line.find('namespace') == -1
  1476. and next_line.find('} else ') == -1):
  1477. error(filename, linenum, 'whitespace/blank_line', 3,
  1478. 'Blank line at the end of a code block. Is this needed?')
  1479. matched = Match(r'\s*(public|protected|private):', prev_line)
  1480. if matched:
  1481. error(filename, linenum, 'whitespace/blank_line', 3,
  1482. 'Do not leave a blank line after "%s:"' % matched.group(1))
  1483. # Next, we complain if there's a comment too near the text
  1484. commentpos = line.find('//')
  1485. if commentpos != -1:
  1486. # Check if the // may be in quotes. If so, ignore it
  1487. # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
  1488. if (line.count('"', 0, commentpos) -
  1489. line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
  1490. # Allow one space for new scopes, two spaces otherwise:
  1491. if (not Match(r'^\s*{ //', line) and
  1492. ((commentpos >= 1 and
  1493. line[commentpos-1] not in string.whitespace) or
  1494. (commentpos >= 2 and
  1495. line[commentpos-2] not in string.whitespace))):
  1496. error(filename, linenum, 'whitespace/comments', 2,
  1497. 'At least two spaces is best between code and comments')
  1498. # There should always be a space between the // and the comment
  1499. commentend = commentpos + 2
  1500. if commentend < len(line) and not line[commentend] == ' ':
  1501. # but some lines are exceptions -- e.g. if they're big
  1502. # comment delimiters like:
  1503. # //----------------------------------------------------------
  1504. # or are an empty C++ style Doxygen comment, like:
  1505. # ///
  1506. # or they begin with multiple slashes followed by a space:
  1507. # //////// Header comment
  1508. match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
  1509. Search(r'^/$', line[commentend:]) or
  1510. Search(r'^/+ ', line[commentend:]))
  1511. if not match:
  1512. error(filename, linenum, 'whitespace/comments', 4,
  1513. 'Should have a space between // and comment')
  1514. CheckComment(line[commentpos:], filename, linenum, error)
  1515. line = clean_lines.elided[linenum] # get rid of comments and strings
  1516. # Don't try to do spacing checks for operator methods
  1517. line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
  1518. # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
  1519. # Otherwise not. Note we only check for non-spaces on *both* sides;
  1520. # sometimes people put non-spaces on one side when aligning ='s among
  1521. # many lines (not that this is behavior that I approve of...)
  1522. if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line):
  1523. error(filename, linenum, 'whitespace/operators', 4,
  1524. 'Missing spaces around =')
  1525. # It's ok not to have spaces around binary operators like + - * /, but if
  1526. # there's too little whitespace, we get concerned. It's hard to tell,
  1527. # though, so we punt on this one for now. TODO.
  1528. # You should always have whitespace around binary operators.
  1529. # Alas, we can't test < or > because they're legitimately used sans spaces
  1530. # (a->b, vector<int> a). The only time we can tell is a < with no >, and
  1531. # only if it's not template params list spilling into the next line.
  1532. match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
  1533. if not match:
  1534. # Note that while it seems that the '<[^<]*' term in the following
  1535. # regexp could be simplified to '<.*', which would indeed match
  1536. # the same class of strings, the [^<] means that searching for the
  1537. # regexp takes linear rather than quadratic time.
  1538. if not Search(r'<[^<]*,\s*$', line): # template params spill
  1539. match = Search(r'[^<>=!\s](<)[^<>=!\s]([^>]|->)*$', line)
  1540. if match:
  1541. error(filename, linenum, 'whitespace/operators', 3,
  1542. 'Missing spaces around %s' % match.group(1))
  1543. # We allow no-spaces around << and >> when used like this: 10<<20, but
  1544. # not otherwise (particularly, not when used as streams)
  1545. match = Search(r'[^0-9\s](<<|>>)[^0-9\s]', line)
  1546. if match:
  1547. error(filename, linenum, 'whitespace/operators', 3,
  1548. 'Missing spaces around %s' % match.group(1))
  1549. # There shouldn't be space around unary operators
  1550. match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
  1551. if match:
  1552. error(filename, linenum, 'whitespace/operators', 4,
  1553. 'Extra space for operator %s' % match.group(1))
  1554. # A pet peeve of mine: no spaces after an if, while, switch, or for
  1555. match = Search(r' (if\(|for\(|while\(|switch\()', line)
  1556. if match:
  1557. error(filename, linenum, 'whitespace/parens', 5,
  1558. 'Missing space before ( in %s' % match.group(1))
  1559. # For if/for/while/switch, the left and right parens should be
  1560. # consistent about how many spaces are inside the parens, and
  1561. # there should either be zero or one spaces inside the parens.
  1562. # We don't want: "if ( foo)" or "if ( foo )".
  1563. # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
  1564. match = Search(r'\b(if|for|while|switch)\s*'
  1565. r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
  1566. line)
  1567. if match:
  1568. if len(match.group(2)) != len(match.group(4)):
  1569. if not (match.group(3) == ';' and
  1570. len(match.group(2)) == 1 + len(match.group(4)) or
  1571. not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
  1572. error(filename, linenum, 'whitespace/parens', 5,
  1573. 'Mismatching spaces inside () in %s' % match.group(1))
  1574. if not len(match.group(2)) in [0, 1]:
  1575. error(filename, linenum, 'whitespace/parens', 5,
  1576. 'Should have zero or one spaces inside ( and ) in %s' %
  1577. match.group(1))
  1578. # You should always have a space after a comma (either as fn arg or operator)
  1579. if Search(r',[^\s]', line):
  1580. error(filename, linenum, 'whitespace/comma', 3,
  1581. 'Missing space after ,')
  1582. # You should always have a space after a semicolon
  1583. # except for few corner cases
  1584. # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
  1585. # space after ;
  1586. if Search(r';[^\s};\\)/]', line):
  1587. error(filename, linenum, 'whitespace/semicolon', 3,
  1588. 'Missing space after ;')
  1589. # Next we will look for issues with function calls.
  1590. CheckSpacingForFunctionCall(filename, line, linenum, error)
  1591. # Except after an opening paren, or after another opening brace (in case of
  1592. # an initializer list, for instance), you should have spaces before your
  1593. # braces. And since you should never have braces at the beginning of a line,
  1594. # this is an easy test.
  1595. if Search(r'[^ ({]{', line):
  1596. error(filename, linenum, 'whitespace/braces', 5,
  1597. 'Missing space before {')
  1598. # Make sure '} else {' has spaces.
  1599. if Search(r'}else', line):
  1600. error(filename, linenum, 'whitespace/braces', 5,
  1601. 'Missing space before else')
  1602. # You shouldn't have spaces before your brackets, except maybe after
  1603. # 'delete []' or 'new char * []'.
  1604. if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
  1605. error(filename, linenum, 'whitespace/braces', 5,
  1606. 'Extra space before [')
  1607. # You shouldn't have a space before a semicolon at the end of the line.
  1608. # There's a special case for "for" since the style guide allows space before
  1609. # the semicolon there.
  1610. if Search(r':\s*;\s*$', line):
  1611. error(filename, linenum, 'whitespace/semicolon', 5,
  1612. 'Semicolon defining empty statement. Use { } instead.')
  1613. elif Search(r'^\s*;\s*$', line):
  1614. error(filename, linenum, 'whitespace/semicolon', 5,
  1615. 'Line contains only semicolon. If this should be an empty statement, '
  1616. 'use { } instead.')
  1617. elif (Search(r'\s+;\s*$', line) and
  1618. not Search(r'\bfor\b', line)):
  1619. error(filename, linenum, 'whitespace/semicolon', 5,
  1620. 'Extra space before last semicolon. If this should be an empty '
  1621. 'statement, use { } instead.')
  1622. def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
  1623. """Checks for additional blank line issues related to sections.
  1624. Currently the only thing checked here is blank line before protected/private.
  1625. Args:
  1626. filename: The name of the current file.
  1627. clean_lines: A CleansedLines instance containing the file.
  1628. class_info: A _ClassInfo objects.
  1629. linenum: The number of the line to check.
  1630. error: The function to call with any errors found.
  1631. """
  1632. # Skip checks if the class is small, where small means 25 lines or less.
  1633. # 25 lines seems like a good cutoff since that's the usual height of
  1634. # terminals, and any class that can't fit in one screen can't really
  1635. # be considered "small".
  1636. #
  1637. # Also skip checks if we are on the first line. This accounts for
  1638. # classes that look like
  1639. # class Foo { public: ... };
  1640. #
  1641. # If we didn't find the end of the class, last_line would be zero,
  1642. # and the check will be skipped by the first condition.
  1643. if (class_info.last_line - class_info.linenum <= 24 or
  1644. linenum <= class_info.linenum):
  1645. return
  1646. matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
  1647. if matched:
  1648. # Issue warning if the line before public/protected/private was
  1649. # not a blank line, but don't do this if the previous line contains
  1650. # "class" or "struct". This can happen two ways:
  1651. # - We are at the beginning of the class.
  1652. # - We are forward-declaring an inner class that is semantically
  1653. # private, but needed to be public for implementation reasons.
  1654. prev_line = clean_lines.lines[linenum - 1]
  1655. if (not IsBlankLine(prev_line) and
  1656. not Search(r'\b(class|struct)\b', prev_line)):
  1657. # Try a bit harder to find the beginning of the class. This is to
  1658. # account for multi-line base-specifier lists, e.g.:
  1659. # class Derived
  1660. # : public Base {
  1661. end_class_head = class_info.linenum
  1662. for i in range(class_info.linenum, linenum):
  1663. if Search(r'\{\s*$', clean_lines.lines[i]):
  1664. end_class_head = i
  1665. break
  1666. if end_class_head < linenum - 1:
  1667. error(filename, linenum, 'whitespace/blank_line', 3,
  1668. '"%s:" should be preceded by a blank line' % matched.group(1))
  1669. def GetPreviousNonBlankLine(clean_lines, linenum):
  1670. """Return the most recent non-blank line and its line number.
  1671. Args:
  1672. clean_lines: A CleansedLines instance containing the file contents.
  1673. linenum: The number of the line to check.
  1674. Returns:
  1675. A tuple with two elements. The first element is the contents of the last
  1676. non-blank line before the current line, or the empty string if this is the
  1677. first non-blank line. The second is the line number of that line, or -1
  1678. if this is the first non-blank line.
  1679. """
  1680. prevlinenum = linenum - 1
  1681. while prevlinenum >= 0:
  1682. prevline = clean_lines.elided[prevlinenum]
  1683. if not IsBlankLine(prevline): # if not a blank line...
  1684. return (prevline, prevlinenum)
  1685. prevlinenum -= 1
  1686. return ('', -1)
  1687. def CheckBraces(filename, clean_lines, linenum, error):
  1688. """Looks for misplaced braces (e.g. at the end of line).
  1689. Args:
  1690. filename: The name of the current file.
  1691. clean_lines: A CleansedLines instance containing the file.
  1692. linenum: The number of the line to check.
  1693. error: The function to call with any errors found.
  1694. """
  1695. line = clean_lines.elided[linenum] # get rid of comments and strings
  1696. if Match(r'\s*{\s*$', line):
  1697. # We allow an open brace to start a line in the case where someone
  1698. # is using braces in a block to explicitly create a new scope,
  1699. # which is commonly used to control the lifetime of
  1700. # stack-allocated variables. We don't detect this perfectly: we
  1701. # just don't complain if the last non-whitespace character on the
  1702. # previous non-blank line is ';', ':', '{', or '}'.
  1703. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  1704. if not Search(r'[;:}{]\s*$', prevline):
  1705. error(filename, linenum, 'whitespace/braces', 4,
  1706. '{ should almost always be at the end of the previous line')
  1707. # An else clause should be on the same line as the preceding closing brace.
  1708. if Match(r'\s*else\s*', line):
  1709. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  1710. if Match(r'\s*}\s*$', prevline):
  1711. error(filename, linenum, 'whitespace/newline', 4,
  1712. 'An else should appear on the same line as the preceding }')
  1713. # If braces come on one side of an else, they should be on both.
  1714. # However, we have to worry about "else if" that spans multiple lines!
  1715. if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
  1716. if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if
  1717. # find the ( after the if
  1718. pos = line.find('else if')
  1719. pos = line.find('(', pos)
  1720. if pos > 0:
  1721. (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
  1722. if endline[endpos:].find('{') == -1: # must be brace after if
  1723. error(filename, linenum, 'readability/braces', 5,
  1724. 'If an else has a brace on one side, it should have it on both')
  1725. else: # common case: else not followed by a multi-line if
  1726. error(filename, linenum, 'readability/braces', 5,
  1727. 'If an else has a brace on one side, it should have it on both')
  1728. # Likewise, an else should never have the else clause on the same line
  1729. if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
  1730. error(filename, linenum, 'whitespace/newline', 4,
  1731. 'Else clause should never be on same line as else (use 2 lines)')
  1732. # In the same way, a do/while should never be on one line
  1733. if Match(r'\s*do [^\s{]', line):
  1734. error(filename, linenum, 'whitespace/newline', 4,
  1735. 'do/while clauses should not be on a single line')
  1736. # Braces shouldn't be followed by a ; unless they're defining a struct
  1737. # or initializing an array.
  1738. # We can't tell in general, but we can for some common cases.
  1739. prevlinenum = linenum
  1740. while True:
  1741. (prevline, prevlinenum) = GetPreviousNonBlankLine(clean_lines, prevlinenum)
  1742. if Match(r'\s+{.*}\s*;', line) and not prevline.count(';'):
  1743. line = prevline + line
  1744. else:
  1745. break
  1746. if (Search(r'{.*}\s*;', line) and
  1747. line.count('{') == line.count('}') and
  1748. not Search(r'struct|class|enum|\s*=\s*{', line)):
  1749. error(filename, linenum, 'readability/braces', 4,
  1750. "You don't need a ; after a }")
  1751. def ReplaceableCheck(operator, macro, line):
  1752. """Determine whether a basic CHECK can be replaced with a more specific one.
  1753. For example suggest using CHECK_EQ instead of CHECK(a == b) and
  1754. similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE.
  1755. Args:
  1756. operator: The C++ operator used in the CHECK.
  1757. macro: The CHECK or EXPECT macro being called.
  1758. line: The current source line.
  1759. Returns:
  1760. True if the CHECK can be replaced with a more specific one.
  1761. """
  1762. # This matches decimal and hex integers, strings, and chars (in that order).
  1763. match_constant = r'([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')'
  1764. # Expression to match two sides of the operator with something that
  1765. # looks like a literal, since CHECK(x == iterator) won't compile.
  1766. # This means we can't catch all the cases where a more specific
  1767. # CHECK is possible, but it's less annoying than dealing with
  1768. # extraneous warnings.
  1769. match_this = (r'\s*' + macro + r'\((\s*' +
  1770. match_constant + r'\s*' + operator + r'[^<>].*|'
  1771. r'.*[^<>]' + operator + r'\s*' + match_constant +
  1772. r'\s*\))')
  1773. # Don't complain about CHECK(x == NULL) or similar because
  1774. # CHECK_EQ(x, NULL) won't compile (requires a cast).
  1775. # Also, don't complain about more complex boolean expressions
  1776. # involving && or || such as CHECK(a == b || c == d).
  1777. return Match(match_this, line) and not Search(r'NULL|&&|\|\|', line)
  1778. def CheckCheck(filename, clean_lines, linenum, error):
  1779. """Checks the use of CHECK and EXPECT macros.
  1780. Args:
  1781. filename: The name of the current file.
  1782. clean_lines: A CleansedLines instance containing the file.
  1783. linenum: The number of the line to check.
  1784. error: The function to call with any errors found.
  1785. """
  1786. # Decide the set of replacement macros that should be suggested
  1787. raw_lines = clean_lines.raw_lines
  1788. current_macro = ''
  1789. for macro in _CHECK_MACROS:
  1790. if raw_lines[linenum].find(macro) >= 0:
  1791. current_macro = macro
  1792. break
  1793. if not current_macro:
  1794. # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'
  1795. return
  1796. line = clean_lines.elided[linenum] # get rid of comments and strings
  1797. # Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc.
  1798. for operator in ['==', '!=', '>=', '>', '<=', '<']:
  1799. if ReplaceableCheck(operator, current_macro, line):
  1800. error(filename, linenum, 'readability/check', 2,
  1801. 'Consider using %s instead of %s(a %s b)' % (
  1802. _CHECK_REPLACEMENT[current_macro][operator],
  1803. current_macro, operator))
  1804. break
  1805. def GetLineWidth(line):
  1806. """Determines the width of the line in column positions.
  1807. Args:
  1808. line: A string, which may be a Unicode string.
  1809. Returns:
  1810. The width of the line in column positions, accounting for Unicode
  1811. combining characters and wide characters.
  1812. """
  1813. if isinstance(line, TEXT_TYPE):
  1814. width = 0
  1815. for uc in unicodedata.normalize('NFC', line):
  1816. if unicodedata.east_asian_width(uc) in ('W', 'F'):
  1817. width += 2
  1818. elif not unicodedata.combining(uc):
  1819. width += 1
  1820. return width
  1821. else:
  1822. return len(line)
  1823. def CheckStyle(filename, clean_lines, linenum, file_extension, class_state,
  1824. error):
  1825. """Checks rules from the 'C++ style rules' section of cppguide.html.
  1826. Most of these rules are hard to test (naming, comment style), but we
  1827. do what we can. In particular we check for 2-space indents, line lengths,
  1828. tab usage, spaces inside code, etc.
  1829. Args:
  1830. filename: The name of the current file.
  1831. clean_lines: A CleansedLines instance containing the file.
  1832. linenum: The number of the line to check.
  1833. file_extension: The extension (without the dot) of the filename.
  1834. error: The function to call with any errors found.
  1835. """
  1836. raw_lines = clean_lines.raw_lines
  1837. line = raw_lines[linenum]
  1838. if line.find('\t') != -1:
  1839. error(filename, linenum, 'whitespace/tab', 1,
  1840. 'Tab found; better to use spaces')
  1841. # One or three blank spaces at the beginning of the line is weird; it's
  1842. # hard to reconcile that with 2-space indents.
  1843. # NOTE: here are the conditions rob pike used for his tests. Mine aren't
  1844. # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
  1845. # if(RLENGTH > 20) complain = 0;
  1846. # if(match($0, " +(error|private|public|protected):")) complain = 0;
  1847. # if(match(prev, "&& *$")) complain = 0;
  1848. # if(match(prev, "\\|\\| *$")) complain = 0;
  1849. # if(match(prev, "[\",=><] *$")) complain = 0;
  1850. # if(match($0, " <<")) complain = 0;
  1851. # if(match(prev, " +for \\(")) complain = 0;
  1852. # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
  1853. initial_spaces = 0
  1854. cleansed_line = clean_lines.elided[linenum]
  1855. while initial_spaces < len(line) and line[initial_spaces] == ' ':
  1856. initial_spaces += 1
  1857. if line and line[-1].isspace():
  1858. error(filename, linenum, 'whitespace/end_of_line', 4,
  1859. 'Line ends in whitespace. Consider deleting these extra spaces.')
  1860. # There are certain situations we allow one space, notably for labels
  1861. elif ((initial_spaces == 1 or initial_spaces == 3) and
  1862. not Match(r'\s*\w+\s*:\s*$', cleansed_line)):
  1863. error(filename, linenum, 'whitespace/indent', 3,
  1864. 'Weird number of spaces at line-start. '
  1865. 'Are you using a 2-space indent?')
  1866. # Labels should always be indented at least one space.
  1867. elif not initial_spaces and line[:2] != '//' and Search(r'[^:]:\s*$',
  1868. line):
  1869. error(filename, linenum, 'whitespace/labels', 4,
  1870. 'Labels should always be indented at least one space. '
  1871. 'If this is a member-initializer list in a constructor or '
  1872. 'the base class list in a class definition, the colon should '
  1873. 'be on the following line.')
  1874. # Check if the line is a header guard.
  1875. is_header_guard = False
  1876. if file_extension == 'h':
  1877. cppvar = GetHeaderGuardCPPVariable(filename)
  1878. if (line.startswith('#ifndef %s' % cppvar) or
  1879. line.startswith('#define %s' % cppvar) or
  1880. line.startswith('#endif // %s' % cppvar)):
  1881. is_header_guard = True
  1882. # #include lines and header guards can be long, since there's no clean way to
  1883. # split them.
  1884. #
  1885. # URLs can be long too. It's possible to split these, but it makes them
  1886. # harder to cut&paste.
  1887. #
  1888. # The "$Id:...$" comment may also get very long without it being the
  1889. # developers fault.
  1890. if (not line.startswith('#include') and not is_header_guard and
  1891. not Match(r'^\s*//.*http(s?)://\S*$', line) and
  1892. not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
  1893. line_width = GetLineWidth(line)
  1894. if line_width > 100:
  1895. error(filename, linenum, 'whitespace/line_length', 4,
  1896. 'Lines should very rarely be longer than 100 characters')
  1897. elif line_width > 80:
  1898. error(filename, linenum, 'whitespace/line_length', 2,
  1899. 'Lines should be <= 80 characters long')
  1900. if (cleansed_line.count(';') > 1 and
  1901. # for loops are allowed two ;'s (and may run over two lines).
  1902. cleansed_line.find('for') == -1 and
  1903. (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
  1904. GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
  1905. # It's ok to have many commands in a switch case that fits in 1 line
  1906. not ((cleansed_line.find('case ') != -1 or
  1907. cleansed_line.find('default:') != -1) and
  1908. cleansed_line.find('break;') != -1)):
  1909. error(filename, linenum, 'whitespace/newline', 4,
  1910. 'More than one command on the same line')
  1911. # Some more style checks
  1912. CheckBraces(filename, clean_lines, linenum, error)
  1913. CheckSpacing(filename, clean_lines, linenum, error)
  1914. CheckCheck(filename, clean_lines, linenum, error)
  1915. if class_state and class_state.classinfo_stack:
  1916. CheckSectionSpacing(filename, clean_lines,
  1917. class_state.classinfo_stack[-1], linenum, error)
  1918. _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"')
  1919. _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
  1920. # Matches the first component of a filename delimited by -s and _s. That is:
  1921. # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
  1922. # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
  1923. # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
  1924. # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
  1925. _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
  1926. def _DropCommonSuffixes(filename):
  1927. """Drops common suffixes like _test.cc or -inl.h from filename.
  1928. For example:
  1929. >>> _DropCommonSuffixes('foo/foo-inl.h')
  1930. 'foo/foo'
  1931. >>> _DropCommonSuffixes('foo/bar/foo.cc')
  1932. 'foo/bar/foo'
  1933. >>> _DropCommonSuffixes('foo/foo_internal.h')
  1934. 'foo/foo'
  1935. >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
  1936. 'foo/foo_unusualinternal'
  1937. Args:
  1938. filename: The input filename.
  1939. Returns:
  1940. The filename with the common suffix removed.
  1941. """
  1942. for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
  1943. 'inl.h', 'impl.h', 'internal.h'):
  1944. if (filename.endswith(suffix) and len(filename) > len(suffix) and
  1945. filename[-len(suffix) - 1] in ('-', '_')):
  1946. return filename[:-len(suffix) - 1]
  1947. return os.path.splitext(filename)[0]
  1948. def _IsTestFilename(filename):
  1949. """Determines if the given filename has a suffix that identifies it as a test.
  1950. Args:
  1951. filename: The input filename.
  1952. Returns:
  1953. True if 'filename' looks like a test, False otherwise.
  1954. """
  1955. if (filename.endswith('_test.cc') or
  1956. filename.endswith('_unittest.cc') or
  1957. filename.endswith('_regtest.cc')):
  1958. return True
  1959. else:
  1960. return False
  1961. def _ClassifyInclude(fileinfo, include, is_system):
  1962. """Figures out what kind of header 'include' is.
  1963. Args:
  1964. fileinfo: The current file cpplint is running over. A FileInfo instance.
  1965. include: The path to a #included file.
  1966. is_system: True if the #include used <> rather than "".
  1967. Returns:
  1968. One of the _XXX_HEADER constants.
  1969. For example:
  1970. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
  1971. _C_SYS_HEADER
  1972. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
  1973. _CPP_SYS_HEADER
  1974. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
  1975. _LIKELY_MY_HEADER
  1976. >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
  1977. ... 'bar/foo_other_ext.h', False)
  1978. _POSSIBLE_MY_HEADER
  1979. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
  1980. _OTHER_HEADER
  1981. """
  1982. # This is a list of all standard c++ header files, except
  1983. # those already checked for above.
  1984. is_stl_h = include in _STL_HEADERS
  1985. is_cpp_h = is_stl_h or include in _CPP_HEADERS
  1986. if is_system:
  1987. if is_cpp_h:
  1988. return _CPP_SYS_HEADER
  1989. else:
  1990. return _C_SYS_HEADER
  1991. # If the target file and the include we're checking share a
  1992. # basename when we drop common extensions, and the include
  1993. # lives in . , then it's likely to be owned by the target file.
  1994. target_dir, target_base = (
  1995. os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
  1996. include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
  1997. if target_base == include_base and (
  1998. include_dir == target_dir or
  1999. include_dir == os.path.normpath(target_dir + '/../public')):
  2000. return _LIKELY_MY_HEADER
  2001. # If the target and include share some initial basename
  2002. # component, it's possible the target is implementing the
  2003. # include, so it's allowed to be first, but we'll never
  2004. # complain if it's not there.
  2005. target_first_component = _RE_FIRST_COMPONENT.match(target_base)
  2006. include_first_component = _RE_FIRST_COMPONENT.match(include_base)
  2007. if (target_first_component and include_first_component and
  2008. target_first_component.group(0) ==
  2009. include_first_component.group(0)):
  2010. return _POSSIBLE_MY_HEADER
  2011. return _OTHER_HEADER
  2012. def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
  2013. """Check rules that are applicable to #include lines.
  2014. Strings on #include lines are NOT removed from elided line, to make
  2015. certain tasks easier. However, to prevent false positives, checks
  2016. applicable to #include lines in CheckLanguage must be put here.
  2017. Args:
  2018. filename: The name of the current file.
  2019. clean_lines: A CleansedLines instance containing the file.
  2020. linenum: The number of the line to check.
  2021. include_state: An _IncludeState instance in which the headers are inserted.
  2022. error: The function to call with any errors found.
  2023. """
  2024. fileinfo = FileInfo(filename)
  2025. line = clean_lines.lines[linenum]
  2026. # "include" should use the new style "foo/bar.h" instead of just "bar.h"
  2027. if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line):
  2028. error(filename, linenum, 'build/include', 4,
  2029. 'Include the directory when naming .h files')
  2030. # we shouldn't include a file more than once. actually, there are a
  2031. # handful of instances where doing so is okay, but in general it's
  2032. # not.
  2033. match = _RE_PATTERN_INCLUDE.search(line)
  2034. if match:
  2035. include = match.group(2)
  2036. is_system = (match.group(1) == '<')
  2037. if include in include_state:
  2038. error(filename, linenum, 'build/include', 4,
  2039. '"%s" already included at %s:%s' %
  2040. (include, filename, include_state[include]))
  2041. else:
  2042. include_state[include] = linenum
  2043. # We want to ensure that headers appear in the right order:
  2044. # 1) for foo.cc, foo.h (preferred location)
  2045. # 2) c system files
  2046. # 3) cpp system files
  2047. # 4) for foo.cc, foo.h (deprecated location)
  2048. # 5) other google headers
  2049. #
  2050. # We classify each include statement as one of those 5 types
  2051. # using a number of techniques. The include_state object keeps
  2052. # track of the highest type seen, and complains if we see a
  2053. # lower type after that.
  2054. error_message = include_state.CheckNextIncludeOrder(
  2055. _ClassifyInclude(fileinfo, include, is_system))
  2056. if error_message:
  2057. error(filename, linenum, 'build/include_order', 4,
  2058. '%s. Should be: %s.h, c system, c++ system, other.' %
  2059. (error_message, fileinfo.BaseName()))
  2060. if not include_state.IsInAlphabeticalOrder(include):
  2061. error(filename, linenum, 'build/include_alpha', 4,
  2062. 'Include "%s" not in alphabetical order' % include)
  2063. # Look for any of the stream classes that are part of standard C++.
  2064. match = _RE_PATTERN_INCLUDE.match(line)
  2065. if match:
  2066. include = match.group(2)
  2067. if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
  2068. # Many unit tests use cout, so we exempt them.
  2069. if not _IsTestFilename(filename):
  2070. error(filename, linenum, 'readability/streams', 3,
  2071. 'Streams are highly discouraged.')
  2072. def _GetTextInside(text, start_pattern):
  2073. """Retrieves all the text between matching open and close parentheses.
  2074. Given a string of lines and a regular expression string, retrieve all the text
  2075. following the expression and between opening punctuation symbols like
  2076. (, [, or {, and the matching close-punctuation symbol. This properly nested
  2077. occurrences of the punctuations, so for the text like
  2078. printf(a(), b(c()));
  2079. a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
  2080. start_pattern must match string having an open punctuation symbol at the end.
  2081. Args:
  2082. text: The lines to extract text. Its comments and strings must be elided.
  2083. It can be single line and can span multiple lines.
  2084. start_pattern: The regexp string indicating where to start extracting
  2085. the text.
  2086. Returns:
  2087. The extracted text.
  2088. None if either the opening string or ending punctuation could not be found.
  2089. """
  2090. # TODO(sugawarayu): Audit cpplint.py to see what places could be profitably
  2091. # rewritten to use _GetTextInside (and use inferior regexp matching today).
  2092. # Give opening punctuations to get the matching close-punctuations.
  2093. matching_punctuation = {'(': ')', '{': '}', '[': ']'}
  2094. closing_punctuation = set(itervalues(matching_punctuation))
  2095. # Find the position to start extracting text.
  2096. match = re.search(start_pattern, text, re.M)
  2097. if not match: # start_pattern not found in text.
  2098. return None
  2099. start_position = match.end(0)
  2100. assert start_position > 0, (
  2101. 'start_pattern must ends with an opening punctuation.')
  2102. assert text[start_position - 1] in matching_punctuation, (
  2103. 'start_pattern must ends with an opening punctuation.')
  2104. # Stack of closing punctuations we expect to have in text after position.
  2105. punctuation_stack = [matching_punctuation[text[start_position - 1]]]
  2106. position = start_position
  2107. while punctuation_stack and position < len(text):
  2108. if text[position] == punctuation_stack[-1]:
  2109. punctuation_stack.pop()
  2110. elif text[position] in closing_punctuation:
  2111. # A closing punctuation without matching opening punctuations.
  2112. return None
  2113. elif text[position] in matching_punctuation:
  2114. punctuation_stack.append(matching_punctuation[text[position]])
  2115. position += 1
  2116. if punctuation_stack:
  2117. # Opening punctuations left without matching close-punctuations.
  2118. return None
  2119. # punctuations match.
  2120. return text[start_position:position - 1]
  2121. def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state,
  2122. error):
  2123. """Checks rules from the 'C++ language rules' section of cppguide.html.
  2124. Some of these rules are hard to test (function overloading, using
  2125. uint32 inappropriately), but we do the best we can.
  2126. Args:
  2127. filename: The name of the current file.
  2128. clean_lines: A CleansedLines instance containing the file.
  2129. linenum: The number of the line to check.
  2130. file_extension: The extension (without the dot) of the filename.
  2131. include_state: An _IncludeState instance in which the headers are inserted.
  2132. error: The function to call with any errors found.
  2133. """
  2134. # If the line is empty or consists of entirely a comment, no need to
  2135. # check it.
  2136. line = clean_lines.elided[linenum]
  2137. if not line:
  2138. return
  2139. match = _RE_PATTERN_INCLUDE.search(line)
  2140. if match:
  2141. CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
  2142. return
  2143. # Create an extended_line, which is the concatenation of the current and
  2144. # next lines, for more effective checking of code that may span more than one
  2145. # line.
  2146. if linenum + 1 < clean_lines.NumLines():
  2147. extended_line = line + clean_lines.elided[linenum + 1]
  2148. else:
  2149. extended_line = line
  2150. # Make Windows paths like Unix.
  2151. fullname = os.path.abspath(filename).replace('\\', '/')
  2152. # TODO(unknown): figure out if they're using default arguments in fn proto.
  2153. # Check for non-const references in functions. This is tricky because &
  2154. # is also used to take the address of something. We allow <> for templates,
  2155. # (ignoring whatever is between the braces) and : for classes.
  2156. # These are complicated re's. They try to capture the following:
  2157. # paren (for fn-prototype start), typename, &, varname. For the const
  2158. # version, we're willing for const to be before typename or after
  2159. # Don't check the implementation on same line.
  2160. fnline = line.split('{', 1)[0]
  2161. if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) >
  2162. len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?'
  2163. r'(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) +
  2164. len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+\s+const(\s?&|&\s?)[\w]+',
  2165. fnline))):
  2166. # We allow non-const references in a few standard places, like functions
  2167. # called "swap()" or iostream operators like "<<" or ">>".
  2168. if not Search(
  2169. r'(swap|Swap|operator[<>][<>])\s*\(\s*(?:[\w:]|<.*>)+\s*&',
  2170. fnline):
  2171. error(filename, linenum, 'runtime/references', 2,
  2172. 'Is this a non-const reference? '
  2173. 'If so, make const or use a pointer.')
  2174. # Check to see if they're using an conversion function cast.
  2175. # I just try to capture the most common basic types, though there are more.
  2176. # Parameterless conversion functions, such as bool(), are allowed as they are
  2177. # probably a member operator declaration or default constructor.
  2178. match = Search(
  2179. r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there
  2180. r'(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line)
  2181. if match:
  2182. # gMock methods are defined using some variant of MOCK_METHODx(name, type)
  2183. # where type may be float(), int(string), etc. Without context they are
  2184. # virtually indistinguishable from int(x) casts. Likewise, gMock's
  2185. # MockCallback takes a template parameter of the form return_type(arg_type),
  2186. # which looks much like the cast we're trying to detect.
  2187. if (match.group(1) is None and # If new operator, then this isn't a cast
  2188. not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
  2189. Match(r'^\s*MockCallback<.*>', line))):
  2190. error(filename, linenum, 'readability/casting', 4,
  2191. 'Using deprecated casting style. '
  2192. 'Use static_cast<%s>(...) instead' %
  2193. match.group(2))
  2194. CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  2195. 'static_cast',
  2196. r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
  2197. # This doesn't catch all cases. Consider (const char * const)"hello".
  2198. #
  2199. # (char *) "foo" should always be a const_cast (reinterpret_cast won't
  2200. # compile).
  2201. if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  2202. 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error):
  2203. pass
  2204. else:
  2205. # Check pointer casts for other than string constants
  2206. CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  2207. 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
  2208. # In addition, we look for people taking the address of a cast. This
  2209. # is dangerous -- casts can assign to temporaries, so the pointer doesn't
  2210. # point where you think.
  2211. if Search(
  2212. r'(&\([^)]+\)[\w(])|(&(static|dynamic|reinterpret)_cast\b)', line):
  2213. error(filename, linenum, 'runtime/casting', 4,
  2214. ('Are you taking an address of a cast? '
  2215. 'This is dangerous: could be a temp var. '
  2216. 'Take the address before doing the cast, rather than after'))
  2217. # Check for people declaring static/global STL strings at the top level.
  2218. # This is dangerous because the C++ language does not guarantee that
  2219. # globals with constructors are initialized before the first access.
  2220. match = Match(
  2221. r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
  2222. line)
  2223. # Make sure it's not a function.
  2224. # Function template specialization looks like: "string foo<Type>(...".
  2225. # Class template definitions look like: "string Foo<Type>::Method(...".
  2226. if match and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)',
  2227. match.group(3)):
  2228. error(filename, linenum, 'runtime/string', 4,
  2229. 'For a static/global string constant, use a C style string instead: '
  2230. '"%schar %s[]".' %
  2231. (match.group(1), match.group(2)))
  2232. # Check that we're not using RTTI outside of testing code.
  2233. if Search(r'\bdynamic_cast<', line) and not _IsTestFilename(filename):
  2234. error(filename, linenum, 'runtime/rtti', 5,
  2235. 'Do not use dynamic_cast<>. If you need to cast within a class '
  2236. "hierarchy, use static_cast<> to upcast. Google doesn't support "
  2237. 'RTTI.')
  2238. if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
  2239. error(filename, linenum, 'runtime/init', 4,
  2240. 'You seem to be initializing a member variable with itself.')
  2241. if file_extension == 'h':
  2242. # TODO(unknown): check that 1-arg constructors are explicit.
  2243. # How to tell it's a constructor?
  2244. # (handled in CheckForNonStandardConstructs for now)
  2245. # TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS
  2246. # (level 1 error)
  2247. pass
  2248. # Check if people are using the verboten C basic types. The only exception
  2249. # we regularly allow is "unsigned short port" for port.
  2250. if Search(r'\bshort port\b', line):
  2251. if not Search(r'\bunsigned short port\b', line):
  2252. error(filename, linenum, 'runtime/int', 4,
  2253. 'Use "unsigned short" for ports, not "short"')
  2254. else:
  2255. match = Search(r'\b(short|long(?! +double)|long long)\b', line)
  2256. if match:
  2257. error(filename, linenum, 'runtime/int', 4,
  2258. 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
  2259. # When snprintf is used, the second argument shouldn't be a literal.
  2260. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
  2261. if match and match.group(2) != '0':
  2262. # If 2nd arg is zero, snprintf is used to calculate size.
  2263. error(filename, linenum, 'runtime/printf', 3,
  2264. 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
  2265. 'to snprintf.' % (match.group(1), match.group(2)))
  2266. # Check if some verboten C functions are being used.
  2267. if Search(r'\bsprintf\b', line):
  2268. error(filename, linenum, 'runtime/printf', 5,
  2269. 'Never use sprintf. Use snprintf instead.')
  2270. match = Search(r'\b(strcpy|strcat)\b', line)
  2271. if match:
  2272. error(filename, linenum, 'runtime/printf', 4,
  2273. 'Almost always, snprintf is better than %s' % match.group(1))
  2274. if Search(r'\bsscanf\b', line):
  2275. error(filename, linenum, 'runtime/printf', 1,
  2276. 'sscanf can be ok, but is slow and can overflow buffers.')
  2277. # Check if some verboten operator overloading is going on
  2278. # TODO(unknown): catch out-of-line unary operator&:
  2279. # class X {};
  2280. # int operator&(const X& x) { return 42; } // unary operator&
  2281. # The trick is it's hard to tell apart from binary operator&:
  2282. # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
  2283. if Search(r'\boperator\s*&\s*\(\s*\)', line):
  2284. error(filename, linenum, 'runtime/operator', 4,
  2285. 'Unary operator& is dangerous. Do not use it.')
  2286. # Check for suspicious usage of "if" like
  2287. # } if (a == b) {
  2288. if Search(r'\}\s*if\s*\(', line):
  2289. error(filename, linenum, 'readability/braces', 4,
  2290. 'Did you mean "else if"? If not, start a new line for "if".')
  2291. # Check for potential format string bugs like printf(foo).
  2292. # We constrain the pattern not to pick things like DocidForPrintf(foo).
  2293. # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
  2294. # TODO(sugawarayu): Catch the following case. Need to change the calling
  2295. # convention of the whole function to process multiple line to handle it.
  2296. # printf(
  2297. # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
  2298. printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
  2299. if printf_args:
  2300. match = Match(r'([\w.\->()]+)$', printf_args)
  2301. if match:
  2302. function_name = re.search(r'\b((?:string)?printf)\s*\(',
  2303. line, re.I).group(1)
  2304. error(filename, linenum, 'runtime/printf', 4,
  2305. 'Potential format string bug. Do %s("%%s", %s) instead.'
  2306. % (function_name, match.group(1)))
  2307. # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
  2308. match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
  2309. if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
  2310. error(filename, linenum, 'runtime/memset', 4,
  2311. 'Did you mean "memset(%s, 0, %s)"?'
  2312. % (match.group(1), match.group(2)))
  2313. if Search(r'\busing namespace\b', line):
  2314. error(filename, linenum, 'build/namespaces', 5,
  2315. 'Do not use namespace using-directives. '
  2316. 'Use using-declarations instead.')
  2317. # Detect variable-length arrays.
  2318. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
  2319. if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
  2320. match.group(3).find(']') == -1):
  2321. # Split the size using space and arithmetic operators as delimiters.
  2322. # If any of the resulting tokens are not compile time constants then
  2323. # report the error.
  2324. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
  2325. is_const = True
  2326. skip_next = False
  2327. for tok in tokens:
  2328. if skip_next:
  2329. skip_next = False
  2330. continue
  2331. if Search(r'sizeof\(.+\)', tok): continue
  2332. if Search(r'arraysize\(\w+\)', tok): continue
  2333. tok = tok.lstrip('(')
  2334. tok = tok.rstrip(')')
  2335. if not tok: continue
  2336. if Match(r'\d+', tok): continue
  2337. if Match(r'0[xX][0-9a-fA-F]+', tok): continue
  2338. if Match(r'k[A-Z0-9]\w*', tok): continue
  2339. if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
  2340. if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
  2341. # A catch all for tricky sizeof cases, including 'sizeof expression',
  2342. # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
  2343. # requires skipping the next token because we split on ' ' and '*'.
  2344. if tok.startswith('sizeof'):
  2345. skip_next = True
  2346. continue
  2347. is_const = False
  2348. break
  2349. if not is_const:
  2350. error(filename, linenum, 'runtime/arrays', 1,
  2351. 'Do not use variable-length arrays. Use an appropriately named '
  2352. "('k' followed by CamelCase) compile-time constant for the size.")
  2353. # If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or
  2354. # DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing
  2355. # in the class declaration.
  2356. match = Match(
  2357. (r'\s*'
  2358. r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'
  2359. r'\(.*\);$'),
  2360. line)
  2361. if match and linenum + 1 < clean_lines.NumLines():
  2362. next_line = clean_lines.elided[linenum + 1]
  2363. # We allow some, but not all, declarations of variables to be present
  2364. # in the statement that defines the class. The [\w\*,\s]* fragment of
  2365. # the regular expression below allows users to declare instances of
  2366. # the class or pointers to instances, but not less common types such
  2367. # as function pointers or arrays. It's a tradeoff between allowing
  2368. # reasonable code and avoiding trying to parse more C++ using regexps.
  2369. if not Search(r'^\s*}[\w\*,\s]*;', next_line):
  2370. error(filename, linenum, 'readability/constructors', 3,
  2371. match.group(1) + ' should be the last thing in the class')
  2372. # Check for use of unnamed namespaces in header files. Registration
  2373. # macros are typically OK, so we allow use of "namespace {" on lines
  2374. # that end with backslashes.
  2375. if (file_extension == 'h'
  2376. and Search(r'\bnamespace\s*{', line)
  2377. and line[-1] != '\\'):
  2378. error(filename, linenum, 'build/namespaces', 4,
  2379. 'Do not use unnamed namespaces in header files. See '
  2380. 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
  2381. ' for more information.')
  2382. def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
  2383. error):
  2384. """Checks for a C-style cast by looking for the pattern.
  2385. This also handles sizeof(type) warnings, due to similarity of content.
  2386. Args:
  2387. filename: The name of the current file.
  2388. linenum: The number of the line to check.
  2389. line: The line of code to check.
  2390. raw_line: The raw line of code to check, with comments.
  2391. cast_type: The string for the C++ cast to recommend. This is either
  2392. reinterpret_cast, static_cast, or const_cast, depending.
  2393. pattern: The regular expression used to find C-style casts.
  2394. error: The function to call with any errors found.
  2395. Returns:
  2396. True if an error was emitted.
  2397. False otherwise.
  2398. """
  2399. match = Search(pattern, line)
  2400. if not match:
  2401. return False
  2402. # e.g., sizeof(int)
  2403. sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
  2404. if sizeof_match:
  2405. error(filename, linenum, 'runtime/sizeof', 1,
  2406. 'Using sizeof(type). Use sizeof(varname) instead if possible')
  2407. return True
  2408. remainder = line[match.end(0):]
  2409. # The close paren is for function pointers as arguments to a function.
  2410. # eg, void foo(void (*bar)(int));
  2411. # The semicolon check is a more basic function check; also possibly a
  2412. # function pointer typedef.
  2413. # eg, void foo(int); or void foo(int) const;
  2414. # The equals check is for function pointer assignment.
  2415. # eg, void *(*foo)(int) = ...
  2416. # The > is for MockCallback<...> ...
  2417. #
  2418. # Right now, this will only catch cases where there's a single argument, and
  2419. # it's unnamed. It should probably be expanded to check for multiple
  2420. # arguments with some unnamed.
  2421. function_match = Match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)|>))', remainder)
  2422. if function_match:
  2423. if (not function_match.group(3) or
  2424. function_match.group(3) == ';' or
  2425. ('MockCallback<' not in raw_line and
  2426. '/*' not in raw_line)):
  2427. error(filename, linenum, 'readability/function', 3,
  2428. 'All parameters should be named in a function')
  2429. return True
  2430. # At this point, all that should be left is actual casts.
  2431. error(filename, linenum, 'readability/casting', 4,
  2432. 'Using C-style cast. Use %s<%s>(...) instead' %
  2433. (cast_type, match.group(1)))
  2434. return True
  2435. _HEADERS_CONTAINING_TEMPLATES = (
  2436. ('<deque>', ('deque',)),
  2437. ('<functional>', ('unary_function', 'binary_function',
  2438. 'plus', 'minus', 'multiplies', 'divides', 'modulus',
  2439. 'negate',
  2440. 'equal_to', 'not_equal_to', 'greater', 'less',
  2441. 'greater_equal', 'less_equal',
  2442. 'logical_and', 'logical_or', 'logical_not',
  2443. 'unary_negate', 'not1', 'binary_negate', 'not2',
  2444. 'bind1st', 'bind2nd',
  2445. 'pointer_to_unary_function',
  2446. 'pointer_to_binary_function',
  2447. 'ptr_fun',
  2448. 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
  2449. 'mem_fun_ref_t',
  2450. 'const_mem_fun_t', 'const_mem_fun1_t',
  2451. 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
  2452. 'mem_fun_ref',
  2453. )),
  2454. ('<limits>', ('numeric_limits',)),
  2455. ('<list>', ('list',)),
  2456. ('<map>', ('map', 'multimap',)),
  2457. ('<memory>', ('allocator',)),
  2458. ('<queue>', ('queue', 'priority_queue',)),
  2459. ('<set>', ('set', 'multiset',)),
  2460. ('<stack>', ('stack',)),
  2461. ('<string>', ('char_traits', 'basic_string',)),
  2462. ('<utility>', ('pair',)),
  2463. ('<vector>', ('vector',)),
  2464. # gcc extensions.
  2465. # Note: std::hash is their hash, ::hash is our hash
  2466. ('<hash_map>', ('hash_map', 'hash_multimap',)),
  2467. ('<hash_set>', ('hash_set', 'hash_multiset',)),
  2468. ('<slist>', ('slist',)),
  2469. )
  2470. _RE_PATTERN_STRING = re.compile(r'\bstring\b')
  2471. _re_pattern_algorithm_header = []
  2472. for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap',
  2473. 'transform'):
  2474. # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
  2475. # type::max().
  2476. _re_pattern_algorithm_header.append(
  2477. (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
  2478. _template,
  2479. '<algorithm>'))
  2480. _re_pattern_templates = []
  2481. for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
  2482. for _template in _templates:
  2483. _re_pattern_templates.append(
  2484. (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
  2485. _template + '<>',
  2486. _header))
  2487. def FilesBelongToSameModule(filename_cc, filename_h):
  2488. """Check if these two filenames belong to the same module.
  2489. The concept of a 'module' here is a as follows:
  2490. foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
  2491. same 'module' if they are in the same directory.
  2492. some/path/public/xyzzy and some/path/internal/xyzzy are also considered
  2493. to belong to the same module here.
  2494. If the filename_cc contains a longer path than the filename_h, for example,
  2495. '/absolute/path/to/base/sysinfo.cc', and this file would include
  2496. 'base/sysinfo.h', this function also produces the prefix needed to open the
  2497. header. This is used by the caller of this function to more robustly open the
  2498. header file. We don't have access to the real include paths in this context,
  2499. so we need this guesswork here.
  2500. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
  2501. according to this implementation. Because of this, this function gives
  2502. some false positives. This should be sufficiently rare in practice.
  2503. Args:
  2504. filename_cc: is the path for the .cc file
  2505. filename_h: is the path for the header path
  2506. Returns:
  2507. Tuple with a bool and a string:
  2508. bool: True if filename_cc and filename_h belong to the same module.
  2509. string: the additional prefix needed to open the header file.
  2510. """
  2511. if not filename_cc.endswith('.cc'):
  2512. return (False, '')
  2513. filename_cc = filename_cc[:-len('.cc')]
  2514. if filename_cc.endswith('_unittest'):
  2515. filename_cc = filename_cc[:-len('_unittest')]
  2516. elif filename_cc.endswith('_test'):
  2517. filename_cc = filename_cc[:-len('_test')]
  2518. filename_cc = filename_cc.replace('/public/', '/')
  2519. filename_cc = filename_cc.replace('/internal/', '/')
  2520. if not filename_h.endswith('.h'):
  2521. return (False, '')
  2522. filename_h = filename_h[:-len('.h')]
  2523. if filename_h.endswith('-inl'):
  2524. filename_h = filename_h[:-len('-inl')]
  2525. filename_h = filename_h.replace('/public/', '/')
  2526. filename_h = filename_h.replace('/internal/', '/')
  2527. files_belong_to_same_module = filename_cc.endswith(filename_h)
  2528. common_path = ''
  2529. if files_belong_to_same_module:
  2530. common_path = filename_cc[:-len(filename_h)]
  2531. return files_belong_to_same_module, common_path
  2532. def UpdateIncludeState(filename, include_state, io=codecs):
  2533. """Fill up the include_state with new includes found from the file.
  2534. Args:
  2535. filename: the name of the header to read.
  2536. include_state: an _IncludeState instance in which the headers are inserted.
  2537. io: The io factory to use to read the file. Provided for testability.
  2538. Returns:
  2539. True if a header was succesfully added. False otherwise.
  2540. """
  2541. headerfile = None
  2542. try:
  2543. headerfile = io.open(filename, 'r', 'utf8', 'replace')
  2544. except IOError:
  2545. return False
  2546. linenum = 0
  2547. for line in headerfile:
  2548. linenum += 1
  2549. clean_line = CleanseComments(line)
  2550. match = _RE_PATTERN_INCLUDE.search(clean_line)
  2551. if match:
  2552. include = match.group(2)
  2553. # The value formatting is cute, but not really used right now.
  2554. # What matters here is that the key is in include_state.
  2555. include_state.setdefault(include, '%s:%d' % (filename, linenum))
  2556. return True
  2557. def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
  2558. io=codecs):
  2559. """Reports for missing stl includes.
  2560. This function will output warnings to make sure you are including the headers
  2561. necessary for the stl containers and functions that you use. We only give one
  2562. reason to include a header. For example, if you use both equal_to<> and
  2563. less<> in a .h file, only one (the latter in the file) of these will be
  2564. reported as a reason to include the <functional>.
  2565. Args:
  2566. filename: The name of the current file.
  2567. clean_lines: A CleansedLines instance containing the file.
  2568. include_state: An _IncludeState instance.
  2569. error: The function to call with any errors found.
  2570. io: The IO factory to use to read the header file. Provided for unittest
  2571. injection.
  2572. """
  2573. required = {} # A map of header name to linenumber and the template entity.
  2574. # Example of required: { '<functional>': (1219, 'less<>') }
  2575. for linenum in range(clean_lines.NumLines()):
  2576. line = clean_lines.elided[linenum]
  2577. if not line or line[0] == '#':
  2578. continue
  2579. # String is special -- it is a non-templatized type in STL.
  2580. matched = _RE_PATTERN_STRING.search(line)
  2581. if matched:
  2582. # Don't warn about strings in non-STL namespaces:
  2583. # (We check only the first match per line; good enough.)
  2584. prefix = line[:matched.start()]
  2585. if prefix.endswith('std::') or not prefix.endswith('::'):
  2586. required['<string>'] = (linenum, 'string')
  2587. for pattern, template, header in _re_pattern_algorithm_header:
  2588. if pattern.search(line):
  2589. required[header] = (linenum, template)
  2590. # The following function is just a speed up, no semantics are changed.
  2591. if not '<' in line: # Reduces the cpu time usage by skipping lines.
  2592. continue
  2593. for pattern, template, header in _re_pattern_templates:
  2594. if pattern.search(line):
  2595. required[header] = (linenum, template)
  2596. # The policy is that if you #include something in foo.h you don't need to
  2597. # include it again in foo.cc. Here, we will look at possible includes.
  2598. # Let's copy the include_state so it is only messed up within this function.
  2599. include_state = include_state.copy()
  2600. # Did we find the header for this file (if any) and succesfully load it?
  2601. header_found = False
  2602. # Use the absolute path so that matching works properly.
  2603. abs_filename = FileInfo(filename).FullName()
  2604. # For Emacs's flymake.
  2605. # If cpplint is invoked from Emacs's flymake, a temporary file is generated
  2606. # by flymake and that file name might end with '_flymake.cc'. In that case,
  2607. # restore original file name here so that the corresponding header file can be
  2608. # found.
  2609. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
  2610. # instead of 'foo_flymake.h'
  2611. abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
  2612. # include_state is modified during iteration, so we iterate over a copy of
  2613. # the keys.
  2614. header_keys = list(include_state.keys())
  2615. for header in header_keys:
  2616. (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
  2617. fullpath = common_path + header
  2618. if same_module and UpdateIncludeState(fullpath, include_state, io):
  2619. header_found = True
  2620. # If we can't find the header file for a .cc, assume it's because we don't
  2621. # know where to look. In that case we'll give up as we're not sure they
  2622. # didn't include it in the .h file.
  2623. # TODO(unknown): Do a better job of finding .h files so we are confident that
  2624. # not having the .h file means there isn't one.
  2625. if filename.endswith('.cc') and not header_found:
  2626. return
  2627. # All the lines have been processed, report the errors found.
  2628. for required_header_unstripped in required:
  2629. template = required[required_header_unstripped][1]
  2630. if required_header_unstripped.strip('<>"') not in include_state:
  2631. error(filename, required[required_header_unstripped][0],
  2632. 'build/include_what_you_use', 4,
  2633. 'Add #include ' + required_header_unstripped + ' for ' + template)
  2634. _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
  2635. def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
  2636. """Check that make_pair's template arguments are deduced.
  2637. G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
  2638. specified explicitly, and such use isn't intended in any case.
  2639. Args:
  2640. filename: The name of the current file.
  2641. clean_lines: A CleansedLines instance containing the file.
  2642. linenum: The number of the line to check.
  2643. error: The function to call with any errors found.
  2644. """
  2645. raw = clean_lines.raw_lines
  2646. line = raw[linenum]
  2647. match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
  2648. if match:
  2649. error(filename, linenum, 'build/explicit_make_pair',
  2650. 4, # 4 = high confidence
  2651. 'Omit template arguments from make_pair OR use pair directly OR'
  2652. ' if appropriate, construct a pair directly')
  2653. def ProcessLine(filename, file_extension,
  2654. clean_lines, line, include_state, function_state,
  2655. class_state, error, extra_check_functions=[]):
  2656. """Processes a single line in the file.
  2657. Args:
  2658. filename: Filename of the file that is being processed.
  2659. file_extension: The extension (dot not included) of the file.
  2660. clean_lines: An array of strings, each representing a line of the file,
  2661. with comments stripped.
  2662. line: Number of line being processed.
  2663. include_state: An _IncludeState instance in which the headers are inserted.
  2664. function_state: A _FunctionState instance which counts function lines, etc.
  2665. class_state: A _ClassState instance which maintains information about
  2666. the current stack of nested class declarations being parsed.
  2667. error: A callable to which errors are reported, which takes 4 arguments:
  2668. filename, line number, error level, and message
  2669. extra_check_functions: An array of additional check functions that will be
  2670. run on each source line. Each function takes 4
  2671. arguments: filename, clean_lines, line, error
  2672. """
  2673. raw_lines = clean_lines.raw_lines
  2674. ParseNolintSuppressions(filename, raw_lines[line], line, error)
  2675. CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
  2676. CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
  2677. CheckStyle(filename, clean_lines, line, file_extension, class_state, error)
  2678. CheckLanguage(filename, clean_lines, line, file_extension, include_state,
  2679. error)
  2680. CheckForNonStandardConstructs(filename, clean_lines, line,
  2681. class_state, error)
  2682. CheckPosixThreading(filename, clean_lines, line, error)
  2683. CheckInvalidIncrement(filename, clean_lines, line, error)
  2684. CheckMakePairUsesDeduction(filename, clean_lines, line, error)
  2685. for check_fn in extra_check_functions:
  2686. check_fn(filename, clean_lines, line, error)
  2687. def ProcessFileData(filename, file_extension, lines, error,
  2688. extra_check_functions=[]):
  2689. """Performs lint checks and reports any errors to the given error function.
  2690. Args:
  2691. filename: Filename of the file that is being processed.
  2692. file_extension: The extension (dot not included) of the file.
  2693. lines: An array of strings, each representing a line of the file, with the
  2694. last element being empty if the file is terminated with a newline.
  2695. error: A callable to which errors are reported, which takes 4 arguments:
  2696. filename, line number, error level, and message
  2697. extra_check_functions: An array of additional check functions that will be
  2698. run on each source line. Each function takes 4
  2699. arguments: filename, clean_lines, line, error
  2700. """
  2701. lines = (['// marker so line numbers and indices both start at 1'] + lines +
  2702. ['// marker so line numbers end in a known way'])
  2703. include_state = _IncludeState()
  2704. function_state = _FunctionState()
  2705. class_state = _ClassState()
  2706. ResetNolintSuppressions()
  2707. CheckForCopyright(filename, lines, error)
  2708. if file_extension == 'h':
  2709. CheckForHeaderGuard(filename, lines, error)
  2710. RemoveMultiLineComments(filename, lines, error)
  2711. clean_lines = CleansedLines(lines)
  2712. for line in range(clean_lines.NumLines()):
  2713. ProcessLine(filename, file_extension, clean_lines, line,
  2714. include_state, function_state, class_state, error,
  2715. extra_check_functions)
  2716. class_state.CheckFinished(filename, error)
  2717. CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
  2718. # We check here rather than inside ProcessLine so that we see raw
  2719. # lines rather than "cleaned" lines.
  2720. CheckForUnicodeReplacementCharacters(filename, lines, error)
  2721. CheckForNewlineAtEOF(filename, lines, error)
  2722. def ProcessFile(filename, vlevel, extra_check_functions=[]):
  2723. """Does google-lint on a single file.
  2724. Args:
  2725. filename: The name of the file to parse.
  2726. vlevel: The level of errors to report. Every error of confidence
  2727. >= verbose_level will be reported. 0 is a good default.
  2728. extra_check_functions: An array of additional check functions that will be
  2729. run on each source line. Each function takes 4
  2730. arguments: filename, clean_lines, line, error
  2731. """
  2732. _SetVerboseLevel(vlevel)
  2733. try:
  2734. # Support the UNIX convention of using "-" for stdin. Note that
  2735. # we are not opening the file with universal newline support
  2736. # (which codecs doesn't support anyway), so the resulting lines do
  2737. # contain trailing '\r' characters if we are reading a file that
  2738. # has CRLF endings.
  2739. # If after the split a trailing '\r' is present, it is removed
  2740. # below. If it is not expected to be present (i.e. os.linesep !=
  2741. # '\r\n' as in Windows), a warning is issued below if this file
  2742. # is processed.
  2743. if filename == '-':
  2744. lines = codecs.StreamReaderWriter(sys.stdin,
  2745. codecs.getreader('utf8'),
  2746. codecs.getwriter('utf8'),
  2747. 'replace').read().split('\n')
  2748. else:
  2749. lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
  2750. carriage_return_found = False
  2751. # Remove trailing '\r'.
  2752. for linenum in range(len(lines)):
  2753. if lines[linenum].endswith('\r'):
  2754. lines[linenum] = lines[linenum].rstrip('\r')
  2755. carriage_return_found = True
  2756. except IOError:
  2757. sys.stderr.write(
  2758. "Skipping input '%s': Can't open for reading\n" % filename)
  2759. return
  2760. # Note, if no dot is found, this will give the entire filename as the ext.
  2761. file_extension = filename[filename.rfind('.') + 1:]
  2762. # When reading from stdin, the extension is unknown, so no cpplint tests
  2763. # should rely on the extension.
  2764. if (filename != '-' and file_extension not in EXTENSIONS):
  2765. sys.stderr.write('Ignoring %s; extension not in %s\n' % (filename, EXTENSIONS))
  2766. else:
  2767. ProcessFileData(filename, file_extension, lines, Error,
  2768. extra_check_functions)
  2769. if carriage_return_found and os.linesep != '\r\n':
  2770. # Use 0 for linenum since outputting only one error for potentially
  2771. # several lines.
  2772. Error(filename, 0, 'whitespace/newline', 1,
  2773. 'One or more unexpected \\r (^M) found;'
  2774. 'better to use only a \\n')
  2775. sys.stderr.write('Done processing %s\n' % filename)
  2776. def PrintUsage(message):
  2777. """Prints a brief usage string and exits, optionally with an error message.
  2778. Args:
  2779. message: The optional error message.
  2780. """
  2781. sys.stderr.write(_USAGE)
  2782. if message:
  2783. sys.exit('\nFATAL ERROR: ' + message)
  2784. else:
  2785. sys.exit(1)
  2786. def PrintCategories():
  2787. """Prints a list of all the error-categories used by error messages.
  2788. These are the categories used to filter messages via --filter.
  2789. """
  2790. sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
  2791. sys.exit(0)
  2792. def ParseArguments(args):
  2793. """Parses the command line arguments.
  2794. This may set the output format and verbosity level as side-effects.
  2795. Args:
  2796. args: The command line arguments:
  2797. Returns:
  2798. The list of filenames to lint.
  2799. """
  2800. try:
  2801. (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
  2802. 'counting=',
  2803. 'filter='])
  2804. except getopt.GetoptError:
  2805. PrintUsage('Invalid arguments.')
  2806. verbosity = _VerboseLevel()
  2807. output_format = _OutputFormat()
  2808. filters = ''
  2809. counting_style = ''
  2810. for (opt, val) in opts:
  2811. if opt == '--help':
  2812. PrintUsage(None)
  2813. elif opt == '--output':
  2814. if not val in ('emacs', 'vs7'):
  2815. PrintUsage('The only allowed output formats are emacs and vs7.')
  2816. output_format = val
  2817. elif opt == '--verbose':
  2818. verbosity = int(val)
  2819. elif opt == '--filter':
  2820. filters = val
  2821. if not filters:
  2822. PrintCategories()
  2823. elif opt == '--counting':
  2824. if val not in ('total', 'toplevel', 'detailed'):
  2825. PrintUsage('Valid counting options are total, toplevel, and detailed')
  2826. counting_style = val
  2827. if not filenames:
  2828. PrintUsage('No files were specified.')
  2829. _SetOutputFormat(output_format)
  2830. _SetVerboseLevel(verbosity)
  2831. _SetFilters(filters)
  2832. _SetCountingStyle(counting_style)
  2833. return filenames
  2834. def main():
  2835. filenames = ParseArguments(sys.argv[1:])
  2836. backup_err = sys.stderr
  2837. try:
  2838. # Change stderr to write with replacement characters so we don't die
  2839. # if we try to print something containing non-ASCII characters.
  2840. sys.stderr = codecs.StreamReader(sys.stderr,
  2841. 'replace')
  2842. _cpplint_state.ResetErrorCounts()
  2843. for filename in filenames:
  2844. ProcessFile(filename, _cpplint_state.verbose_level)
  2845. _cpplint_state.PrintErrorCounts()
  2846. finally:
  2847. sys.stderr = backup_err
  2848. sys.exit(_cpplint_state.error_count > 0)
  2849. if __name__ == '__main__':
  2850. main()