cpplint.py 104 KB

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