def read_chunk(filename, offset=-1, length=-1, escape_data=False):
  """
  Read a chunk of a file from an offset upto the length.
  """
  try:
    length = int(length)
    offset = int(offset)
  except ValueError:
    return {}

  if not os.path.isfile(filename):
    return {}

  try:
    fstat = os.stat(filename)
  except Exception:
    return {}

  if offset == -1:
    offset = fstat.st_size

  if length == -1:
    length = fstat.st_size - offset

  with open(filename, "r") as fp:
    fp.seek(offset)
    try:
      data = fp.read(length)
    except IOError:
      return {}

  if data:
    data = _escape_data(data) if escape_data else data
    return dict(offset=offset, length=len(data), data=data)

  return dict(offset=offset, length=0)

def read_chunk ( filename , offset = - 1 , length = - 1 , escape_data = False ) : try : length = int ( length ) offset = int ( offset ) except ValueError : return { } if not os . path . isfile ( filename ) : return { } try : fstat = os . stat ( filename ) except Exception : return { } if offset == - 1 : offset = fstat . st_size if length == - 1 : length = fstat . st_size - offset with open ( filename , "r" ) as fp : fp . seek ( offset ) try : data = fp . read ( length ) except IOError : return { } if data : data = _escape_data ( data ) if escape_data else data return dict ( offset = offset , length = len ( data ) , data = data ) return dict ( offset = offset , length = 0 )

Read a chunk of a file from an offset upto the length .


def pipe(prev_proc, to_cmd):
  """
  Pipes output of prev_proc into to_cmd.
  Returns piped process
  """
  stdin = None if prev_proc is None else prev_proc.stdout
  process = subprocess.Popen(to_cmd,
                             stdout=subprocess.PIPE,
                             stdin=stdin)
  if prev_proc is not None:
    prev_proc.stdout.close() # Allow prev_proc to receive a SIGPIPE
  return process

def pipe ( prev_proc , to_cmd ) : stdin = None if prev_proc is None else prev_proc . stdout process = subprocess . Popen ( to_cmd , stdout = subprocess . PIPE , stdin = stdin ) if prev_proc is not None : prev_proc . stdout . close ( ) return process

Pipes output of prev_proc into to_cmd . Returns piped process


def str_cmd(cmd, cwd, env):
  """
  Runs the command and returns its stdout and stderr.
  """
  process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, cwd=cwd, env=env)
  stdout_builder, stderr_builder = proc.async_stdout_stderr_builder(process)
  process.wait()
  stdout, stderr = stdout_builder.result(), stderr_builder.result()
  return {'command': ' '.join(cmd), 'stderr': stderr, 'stdout': stdout}

def
str_cmd
(
cmd
,
cwd
,
env
)
:
process
=
subprocess
.
Popen
(
cmd
,
stdout
=
subprocess
.
PIPE
,
stderr
=
subprocess
.
PIPE
,
cwd
=
cwd
,
env
=
env
)
stdout_builder
,
stderr_builder
=
proc
.
async_stdout_stderr_builder
(
process
)
process
.
wait
(
)
stdout
,
stderr
=
stdout_builder
.
result
(
)
,
stderr_builder
.
result
(
)
return
{
'command'
:
' '
.
join
(
cmd
)
,
'stderr'
:
stderr
,
'stdout'
:
stdout
}

Runs the command and returns its stdout and stderr .


def chain(cmd_list):
  """
  Feed output of one command to the next and return final output
  Returns string output of chained application of commands.
  """
  command = ' | '.join(map(lambda x: ' '.join(x), cmd_list))
  chained_proc = functools.reduce(pipe, [None] + cmd_list)
  stdout_builder = proc.async_stdout_builder(chained_proc)
  chained_proc.wait()
  return {
      'command': command,
      'stdout': stdout_builder.result()
  }

def
chain
(
cmd_list
)
:
command
=
' | '
.
join
(
map
(
lambda
x
:
' '
.
join
(
x
)
,
cmd_list
)
)
chained_proc
=
functools
.
reduce
(
pipe
,
[
]
+
cmd_list
)
stdout_builder
=
proc
.
async_stdout_builder
(
chained_proc
)
chained_proc
.
wait
(
)
return
{
'command'
:
command
,
'stdout'
:
stdout_builder
.
result
(
)
}

Feed output of one command to the next and return final output Returns string output of chained application of commands .


def parse_topo_loc(cl_args):
  """ parse topology location """
  try:
    topo_loc = cl_args['cluster/[role]/[env]'].split('/')
    topo_name = cl_args['topology-name']
    topo_loc.append(topo_name)
    if len(topo_loc) != 4:
      raise
    return topo_loc
  except Exception:
    Log.error('Invalid topology location')
    raise

def
parse_topo_loc
(
cl_args
)
:
try
:
topo_loc
=
cl_args
[
'cluster/[role]/[env]'
]
.
split
(
'/'
)
topo_name
=
cl_args
[
'topology-name'
]
topo_loc
.
append
(
topo_name
)
if
len
(
topo_loc
)
!=
4
:
raise
return
topo_loc
except
Exception
:
Log
.
error
(
'Invalid topology location'
)
raise


def to_table(metrics):
  """ normalize raw metrics API result to table """
  all_queries = tracker_access.metric_queries()
  m = tracker_access.queries_map()
  names = metrics.values()[0].keys()
  stats = []
  for n in names:
    info = [n]
    for field in all_queries:
      try:
        info.append(str(metrics[field][n]))
      except KeyError:
        pass
    stats.append(info)
  header = ['container id'] + [m[k] for k in all_queries if k in metrics.keys()]
  return stats, header

def
to_table
(
metrics
)
:
all_queries
=
tracker_access
.
metric_queries
(
)
m
=
tracker_access
.
queries_map
(
)
names
=
metrics
.
values
(
)
[
0
]
.
keys
(
)
stats
=
[
]
for
n
in
names
:
info
=
[
n
]
for
field
in
all_queries
:
try
:
info
.
append
(
str
(
metrics
[
field
]
[
n
]
)
)
except
KeyError
:
pass
stats
.
append
(
info
)
header
=
[
'container id'
]
+
[
m
[
k
]
for
k
in
all_queries
if
k
in
metrics
.
keys
(
)
]
return
stats
,
header


def run_metrics(command, parser, cl_args, unknown_args):
  """ run metrics subcommand """
  cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ']
  topology = cl_args['topology-name']
  try:
    result = tracker_access.get_topology_info(cluster, env, topology, role)
    spouts = result['physical_plan']['spouts'].keys()
    bolts = result['physical_plan']['bolts'].keys()
    components = spouts + bolts
    cname = cl_args['component']
    if cname:
      if cname in components:
        components = [cname]
      else:
        Log.error('Unknown component: \'%s\'' % cname)
        raise
  except Exception:
    Log.error("Fail to connect to tracker: \'%s\'", cl_args["tracker_url"])
    return False
  cresult = []
  for comp in components:
    try:
      metrics = tracker_access.get_component_metrics(comp, cluster, env, topology, role)
    except:
      Log.error("Fail to connect to tracker: \'%s\'", cl_args["tracker_url"])
      return False
    stat, header = to_table(metrics)
    cresult.append((comp, stat, header))
  for i, (comp, stat, header) in enumerate(cresult):
    if i != 0:
      print('')
    print('\'%s\' metrics:' % comp)
    print(tabulate(stat, headers=header))
  return True

def
run_metrics
(
command
,
parser
,
cl_args
,
unknown_args
)
:
cluster
,
role
,
env
=
cl_args
[
'cluster'
]
,
cl_args
[
'role'
]
,
cl_args
[
'environ'
]
topology
=
cl_args
[
'topology-name'
]
try
:
result
=
tracker_access
.
get_topology_info
(
cluster
,
env
,
topology
,
role
)
spouts
=
result
[
'physical_plan'
]
[
'spouts'
]
.
keys
(
)
bolts
=
result
[
'physical_plan'
]
[
'bolts'
]
.
keys
(
)
components
=
spouts
+
bolts
cname
=
cl_args
[
'component'
]
if
cname
:
if
cname
in
components
:
components
=
[
cname
]
else
:
Log
.
error
(
'Unknown component: \'%s\''
%
cname
)
raise
except
Exception
:
Log
.
error
(
"Fail to connect to tracker: \'%s\'"
,
cl_args
[
"tracker_url"
]
)
return
False
cresult
=
[
]
for
comp
in
components
:
try
:
metrics
=
tracker_access
.
get_component_metrics
(
comp
,
cluster
,
env
,
topology
,
role
)
except
:
Log
.
error
(
"Fail to connect to tracker: \'%s\'"
,
cl_args
[
"tracker_url"
]
)
return
False
stat
,
header
=
to_table
(
metrics
)
cresult
.
append
(
(
comp
,
stat
,
header
)
)
for
i
,
(
comp
,
stat
,
header
)
in
enumerate
(
cresult
)
:
if
i
!=
0
:
print
(
''
)
print
(
'\'%s\' metrics:'
%
comp
)
print
(
tabulate
(
stat
,
headers
=
header
)
)
return
True


def run_bolts(command, parser, cl_args, unknown_args):
  """ run bolts subcommand """
  cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ']
  topology = cl_args['topology-name']
  try:
    result = tracker_access.get_topology_info(cluster, env, topology, role)
    bolts = result['physical_plan']['bolts'].keys()
    bolt_name = cl_args['bolt']
    if bolt_name:
      if bolt_name in bolts:
        bolts = [bolt_name]
      else:
        Log.error('Unknown bolt: \'%s\'' % bolt_name)
        raise
  except Exception:
    Log.error("Fail to connect to tracker: \'%s\'", cl_args["tracker_url"])
    return False
  bolts_result = []
  for bolt in bolts:
    try:
      metrics = tracker_access.get_component_metrics(bolt, cluster, env, topology, role)
      stat, header = to_table(metrics)
      bolts_result.append((bolt, stat, header))
    except Exception:
      Log.error("Fail to connect to tracker: \'%s\'", cl_args["tracker_url"])
      return False
  for i, (bolt, stat, header) in enumerate(bolts_result):
    if i != 0:
      print('')
    print('\'%s\' metrics:' % bolt)
    print(tabulate(stat, headers=header))
  return True

def
run_bolts
(
command
,
parser
,
cl_args
,
unknown_args
)
:
cluster
,
role
,
env
=
cl_args
[
'cluster'
]
,
cl_args
[
'role'
]
,
cl_args
[
'environ'
]
topology
=
cl_args
[
'topology-name'
]
try
:
result
=
tracker_access
.
get_topology_info
(
cluster
,
env
,
topology
,
role
)
bolts
=
result
[
'physical_plan'
]
[
'bolts'
]
.
keys
(
)
bolt_name
=
cl_args
[
'bolt'
]
if
bolt_name
:
if
bolt_name
in
bolts
:
bolts
=
[
bolt_name
]
else
:
Log
.
error
(
'Unknown bolt: \'%s\''
%
bolt_name
)
raise
except
Exception
:
Log
.
error
(
"Fail to connect to tracker: \'%s\'"
,
cl_args
[
"tracker_url"
]
)
return
False
bolts_result
=
[
]
for
bolt
in
bolts
:
try
:
metrics
=
tracker_access
.
get_component_metrics
(
bolt
,
cluster
,
env
,
topology
,
role
)
stat
,
header
=
to_table
(
metrics
)
bolts_result
.
append
(
(
bolt
,
stat
,
header
)
)
except
Exception
:
Log
.
error
(
"Fail to connect to tracker: \'%s\'"
,
cl_args
[
"tracker_url"
]
)
return
False
for
i
,
(
bolt
,
stat
,
header
)
in
enumerate
(
bolts_result
)
:
if
i
!=
0
:
print
(
''
)
print
(
'\'%s\' metrics:'
%
bolt
)
print
(
tabulate
(
stat
,
headers
=
header
)
)
return
True


def run_containers(command, parser, cl_args, unknown_args):
  """ run containers subcommand """
  cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ']
  topology = cl_args['topology-name']
  container_id = cl_args['id']
  try:
    result = tracker_access.get_topology_info(cluster, env, topology, role)
  except:
    Log.error("Fail to connect to tracker: \'%s\'", cl_args["tracker_url"])
    return False
  containers = result['physical_plan']['stmgrs']
  all_bolts, all_spouts = set(), set()
  for _, bolts in result['physical_plan']['bolts'].items():
    all_bolts = all_bolts | set(bolts)
  for _, spouts in result['physical_plan']['spouts'].items():
    all_spouts = all_spouts | set(spouts)
  stmgrs = containers.keys()
  stmgrs.sort()
  if container_id is not None:
    try:
      normalized_cid = container_id - 1
      if normalized_cid < 0:
        raise
      stmgrs = [stmgrs[normalized_cid]]
    except:
      Log.error('Invalid container id: %d' % container_id)
      return False
  table = []
  for sid, name in enumerate(stmgrs):
    cid = sid + 1
    host = containers[name]["host"]
    port = containers[name]["port"]
    pid = containers[name]["pid"]
    instances = containers[name]["instance_ids"]
    bolt_nums = len([instance for instance in instances if instance in all_bolts])
    spout_nums = len([instance for instance in instances if instance in all_spouts])
    table.append([cid, host, port, pid, bolt_nums, spout_nums, len(instances)])
  headers = ["container", "host", "port", "pid", "#bolt", "#spout", "#instance"]
  sys.stdout.flush()
  print(tabulate(table, headers=headers))
  return True

def
run_containers
(
command
,
parser
,
cl_args
,
unknown_args
)
:
cluster
,
role
,
env
=
cl_args
[
'cluster'
]
,
cl_args
[
'role'
]
,
cl_args
[
'environ'
]
topology
=
cl_args
[
'topology-name'
]
container_id
=
cl_args
[
'id'
]
try
:
result
=
tracker_access
.
get_topology_info
(
cluster
,
env
,
topology
,
role
)
except
:
Log
.
error
(
"Fail to connect to tracker: \'%s\'"
,
cl_args
[
"tracker_url"
]
)
return
False
containers
=
result
[
'physical_plan'
]
[
'stmgrs'
]
all_bolts
,
all_spouts
=
set
(
)
,
set
(
)
for
_
,
bolts
in
result
[
'physical_plan'
]
[
'bolts'
]
.
items
(
)
:
all_bolts
=
all_bolts
|
set
(
bolts
)
for
_
,
spouts
in
result
[
'physical_plan'
]
[
'spouts'
]
.
items
(
)
:
all_spouts
=
all_spouts
|
set
(
spouts
)
stmgrs
=
containers
.
keys
(
)
stmgrs
.
sort
(
)
if
container_id
is
not
:
try
:
normalized_cid
=
container_id
1
if
normalized_cid
<
0
:
raise
stmgrs
=
[
stmgrs
[
normalized_cid
]
]
except
:
Log
.
error
(
'Invalid container id: %d'
%
container_id
)
return
False
table
=
[
]
for
sid
,
name
in
enumerate
(
stmgrs
)
:
cid
=
sid
+
1
host
=
containers
[
name
]
[
"host"
]
port
=
containers
[
name
]
[
"port"
]
pid
=
containers
[
name
]
[
"pid"
]
instances
=
containers
[
name
]
[
"instance_ids"
]
bolt_nums
=
len
(
[
instance
for
instance
in
instances
if
instance
in
all_bolts
]
)
spout_nums
=
len
(
[
instance
for
instance
in
instances
if
instance
in
all_spouts
]
)
table
.
append
(
[
cid
,
host
,
port
,
pid
,
bolt_nums
,
spout_nums
,
len
(
instances
)
]
)
headers
=
[
"container"
,
"host"
,
"port"
,
"pid"
,
"#bolt"
,
"#spout"
,
"#instance"
]
sys
.
stdout
.
flush
(
)
print
(
tabulate
(
table
,
headers
=
headers
)
)
return
True


def spec(cls, name=None, inputs=None, par=1, config=None, optional_outputs=None):
    """Register this bolt to the topology and create ``HeronComponentSpec``

    This method takes an optional ``outputs`` argument for supporting dynamic output fields
    declaration. However, it is recommended that ``outputs`` should be declared as
    an attribute of your ``Bolt`` subclass. Also, some ways of declaring inputs is not supported
    in this implementation; please read the documentation below.

    :type name: str
    :param name: Name of this bolt.
    :type inputs: dict or list
    :param inputs: Streams that feed into this Bolt.

                   Two forms of this are acceptable:

                   1. A `dict` mapping from ``HeronComponentSpec`` to ``Grouping``.
                      In this case, default stream is used.
                   2. A `dict` mapping from ``GlobalStreamId`` to ``Grouping``.
                      This ``GlobalStreamId`` object itself is different from StreamParse, because
                      Heron does not use thrift, although its constructor method is compatible.
                   3. A `list` of ``HeronComponentSpec``. In this case, default stream with
                      SHUFFLE grouping is used.
                   4. A `list` of ``GlobalStreamId``. In this case, SHUFFLE grouping is used.
    :type par: int
    :param par: Parallelism hint for this spout.
    :type config: dict
    :param config: Component-specific config settings.
    :type optional_outputs: list of (str or Stream) or tuple of (str or Stream)
    :param optional_outputs: Additional output fields for this bolt. These fields are added to
                             existing ``outputs`` class attributes of your bolt. This is an optional
                             argument, and exists only for supporting dynamic output field
                             declaration.
    """
    python_class_path = "%s.%s" % (cls.__module__, cls.__name__)

    if hasattr(cls, 'outputs'):
      # avoid modification to cls.outputs
      _outputs = copy.copy(cls.outputs)
    else:
      _outputs = []

    if optional_outputs is not None:
      assert isinstance(optional_outputs, (list, tuple))
      for out in optional_outputs:
        assert isinstance(out, (str, Stream))
        _outputs.append(out)

    return HeronComponentSpec(name, python_class_path, is_spout=False, par=par,
                              inputs=inputs, outputs=_outputs, config=config)

def spec ( cls , name = None , inputs = None , par = 1 , config = None , optional_outputs = None ) : python_class_path = "%s.%s" % ( cls . __module__ , cls . __name__ ) if hasattr ( cls , 'outputs' ) : _outputs = copy . copy ( cls . outputs ) else : _outputs = [ ] if optional_outputs is not None : assert isinstance ( optional_outputs , ( list , tuple ) ) for out in optional_outputs : assert isinstance ( out , ( str , Stream ) ) _outputs . append ( out ) return HeronComponentSpec ( name , python_class_path , is_spout = False , par = par , inputs = inputs , outputs = _outputs , config = config )

Register this bolt to the topology and create HeronComponentSpec


def make_tuple(stream, tuple_key, values, roots=None):
    """Creates a HeronTuple

    :param stream: protobuf message ``StreamId``
    :param tuple_key: tuple id
    :param values: a list of values
    :param roots: a list of protobuf message ``RootId``
    """
    component_name = stream.component_name
    stream_id = stream.id
    gen_task = roots[0].taskid if roots is not None and len(roots) > 0 else None
    return HeronTuple(id=str(tuple_key), component=component_name, stream=stream_id,
                      task=gen_task, values=values, creation_time=time.time(), roots=roots)

def make_tuple ( stream , tuple_key , values , roots = None ) : component_name = stream . component_name stream_id = stream . id gen_task = roots [ 0 ] . taskid if roots is not None and len ( roots ) > 0 else None return HeronTuple ( id = str ( tuple_key ) , component = component_name , stream = stream_id , task = gen_task , values = values , creation_time = time . time ( ) , roots = roots )


def make_tick_tuple():
    """Creates a TickTuple"""
    return HeronTuple(id=TupleHelper.TICK_TUPLE_ID, component=TupleHelper.TICK_SOURCE_COMPONENT,
                      stream=TupleHelper.TICK_TUPLE_ID, task=None, values=None,
                      creation_time=time.time(), roots=None)

def make_tick_tuple ( ) : return HeronTuple ( id = TupleHelper . TICK_TUPLE_ID , component = TupleHelper . TICK_SOURCE_COMPONENT , stream = TupleHelper . TICK_TUPLE_ID , task = None , values = None , creation_time = time . time ( ) , roots = None )


def make_root_tuple_info(stream_id, tuple_id):
    """Creates a RootTupleInfo"""
    key = random.getrandbits(TupleHelper.MAX_SFIXED64_RAND_BITS)
    return RootTupleInfo(stream_id=stream_id, tuple_id=tuple_id,
                         insertion_time=time.time(), key=key)

def make_root_tuple_info ( stream_id , tuple_id ) : key = random . getrandbits ( TupleHelper . MAX_SFIXED64_RAND_BITS ) return RootTupleInfo ( stream_id = stream_id , tuple_id = tuple_id , insertion_time = time . time ( ) , key = key )


def ParseNolintSuppressions(filename, raw_line, linenum, error):
  """Updates the global list of line error-suppressions.

  Parses any NOLINT comments on the current line, updating the global
  error_suppressions store.  Reports an error if the NOLINT comment
  was malformed.

  Args:
    filename: str, the name of the input file.
    raw_line: str, the line of input text, with comments.
    linenum: int, the number of the current line.
    error: function, an error handler.
  """
  matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
  if matched:
    if matched.group(1):
      suppressed_line = linenum + 1
    else:
      suppressed_line = linenum
    category = matched.group(2)
    if category in (None, '(*)'):  # => "suppress all"
      _error_suppressions.setdefault(None, set()).add(suppressed_line)
    else:
      if category.startswith('(') and category.endswith(')'):
        category = category[1:-1]
        if category in _ERROR_CATEGORIES:
          _error_suppressions.setdefault(category, set()).add(suppressed_line)
        elif category not in _LEGACY_ERROR_CATEGORIES:
          error(filename, linenum, 'readability/nolint', 5,
                'Unknown NOLINT error category: %s' % category)

def
ParseNolintSuppressions
(
filename
,
raw_line
,
linenum
,
error
)
:
matched
=
Search
(
r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?'
,
raw_line
)
if
matched
:
if
matched
.
group
(
1
)
:
suppressed_line
=
linenum
+
1
else
:
suppressed_line
=
linenum
category
=
matched
.
group
(
2
)
if
category
in
(
,
'(*)'
)
:
_error_suppressions
.
setdefault
(
,
set
(
)
)
.
add
(
suppressed_line
)
else
:
if
category
.
startswith
(
'('
)
and
category
.
endswith
(
')'
)
:
category
=
category
[
1
:
1
]
if
category
in
_ERROR_CATEGORIES
:
_error_suppressions
.
setdefault
(
category
,
set
(
)
)
.
add
(
suppressed_line
)
elif
category
not
in
_LEGACY_ERROR_CATEGORIES
:
error
(
filename
,
linenum
,
'readability/nolint'
,
5
,
'Unknown NOLINT error category: %s'
%
category
)

Updates the global list of line error - suppressions .


def ProcessGlobalSuppresions(lines):
  """Updates the list of global error suppressions.

  Parses any lint directives in the file that have global effect.

  Args:
    lines: An array of strings, each representing a line of the file, with the
           last element being empty if the file is terminated with a newline.
  """
  for line in lines:
    if _SEARCH_C_FILE.search(line):
      for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
        _global_error_suppressions[category] = True
    if _SEARCH_KERNEL_FILE.search(line):
      for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
        _global_error_suppressions[category] = True

def ProcessGlobalSuppresions ( lines ) : for line in lines : if _SEARCH_C_FILE . search ( line ) : for category in _DEFAULT_C_SUPPRESSED_CATEGORIES : _global_error_suppressions [ category ] = True if _SEARCH_KERNEL_FILE . search ( line ) : for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES : _global_error_suppressions [ category ] = True

Updates the list of global error suppressions .


def IsErrorSuppressedByNolint(category, linenum):
  """Returns true if the specified error category is suppressed on this line.

  Consults the global error_suppressions map populated by
  ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.

  Args:
    category: str, the category of the error.
    linenum: int, the current line number.
  Returns:
    bool, True iff the error should be suppressed due to a NOLINT comment or
    global suppression.
  """
  return (_global_error_suppressions.get(category, False) or
          linenum in _error_suppressions.get(category, set()) or
          linenum in _error_suppressions.get(None, set()))

def IsErrorSuppressedByNolint ( category , linenum ) : return ( _global_error_suppressions . get ( category , False ) or linenum in _error_suppressions . get ( category , set ( ) ) or linenum in _error_suppressions . get ( None , set ( ) ) )

Returns true if the specified error category is suppressed on this line .


def Match(pattern, s):
  """Matches the string with the pattern, caching the compiled regexp."""
  # The regexp compilation caching is inlined in both Match and Search for
  # performance reasons; factoring it out into a separate function turns out
  # to be noticeably expensive.
  if pattern not in _regexp_compile_cache:
    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  return _regexp_compile_cache[pattern].match(s)

def Match ( pattern , s ) : if pattern not in _regexp_compile_cache : _regexp_compile_cache [ pattern ] = sre_compile . compile ( pattern ) return _regexp_compile_cache [ pattern ] . match ( s )

Matches the string with the pattern caching the compiled regexp .


def ReplaceAll(pattern, rep, s):
  """Replaces instances of pattern in a string with a replacement.

  The compiled regex is kept in a cache shared by Match and Search.

  Args:
    pattern: regex pattern
    rep: replacement text
    s: search string

  Returns:
    string with replacements made (or original string if no replacements)
  """
  if pattern not in _regexp_compile_cache:
    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  return _regexp_compile_cache[pattern].sub(rep, s)

def ReplaceAll ( pattern , rep , s ) : if pattern not in _regexp_compile_cache : _regexp_compile_cache [ pattern ] = sre_compile . compile ( pattern ) return _regexp_compile_cache [ pattern ] . sub ( rep , s )

Replaces instances of pattern in a string with a replacement .


def Search(pattern, s):
  """Searches the string for the pattern, caching the compiled regexp."""
  if pattern not in _regexp_compile_cache:
    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  return _regexp_compile_cache[pattern].search(s)

def Search ( pattern , s ) : if pattern not in _regexp_compile_cache : _regexp_compile_cache [ pattern ] = sre_compile . compile ( pattern ) return _regexp_compile_cache [ pattern ] . search ( s )

Searches the string for the pattern caching the compiled regexp .


def _ShouldPrintError(category, confidence, linenum):
  """If confidence >= verbose, category passes filter and is not suppressed."""

  # There are three ways we might decide not to print an error message:
  # a "NOLINT(category)" comment appears in the source,
  # the verbosity level isn't high enough, or the filters filter it out.
  if IsErrorSuppressedByNolint(category, linenum):
    return False

  if confidence < _cpplint_state.verbose_level:
    return False

  is_filtered = False
  for one_filter in _Filters():
    if one_filter.startswith('-'):
      if category.startswith(one_filter[1:]):
        is_filtered = True
    elif one_filter.startswith('+'):
      if category.startswith(one_filter[1:]):
        is_filtered = False
    else:
      assert False  # should have been checked for in SetFilter.
  if is_filtered:
    return False

  return True

def _ShouldPrintError ( category , confidence , linenum ) : if IsErrorSuppressedByNolint ( category , linenum ) : return False if confidence < _cpplint_state . verbose_level : return False is_filtered = False for one_filter in _Filters ( ) : if one_filter . startswith ( '-' ) : if category . startswith ( one_filter [ 1 : ] ) : is_filtered = True elif one_filter . startswith ( '+' ) : if category . startswith ( one_filter [ 1 : ] ) : is_filtered = False else : assert False if is_filtered : return False return True

If confidence > = verbose category passes filter and is not suppressed .


def IsCppString(line):
  """Does line terminate so, that the next symbol is in string constant.

  This function does not consider single-line nor multi-line comments.

  Args:
    line: is a partial line of code starting from the 0..n.

  Returns:
    True, if next character appended to 'line' is inside a
    string constant.
  """

  line = line.replace(r'\\', 'XX')  # after this, \\" does not match to \"
  return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1

def IsCppString ( line ) : line = line . replace ( r'\\' , 'XX' ) return ( ( line . count ( '"' ) - line . count ( r'\"' ) - line . count ( "'\"'" ) ) & 1 ) == 1

Does line terminate so that the next symbol is in string constant .


def CleanseRawStrings(raw_lines):
  """Removes C++11 raw strings from lines.

    Before:
      static const char kData[] = R"(
          multi-line string
          )";

    After:
      static const char kData[] = ""
          (replaced by blank line)
          "";

  Args:
    raw_lines: list of raw lines.

  Returns:
    list of lines with C++11 raw strings replaced by empty strings.
  """

  delimiter = None
  lines_without_raw_strings = []
  for line in raw_lines:
    if delimiter:
      # Inside a raw string, look for the end
      end = line.find(delimiter)
      if end >= 0:
        # Found the end of the string, match leading space for this
        # line and resume copying the original lines, and also insert
        # a "" on the last line.
        leading_space = Match(r'^(\s*)\S', line)
        line = leading_space.group(1) + '""' + line[end + len(delimiter):]
        delimiter = None
      else:
        # Haven't found the end yet, append a blank line.
        line = '""'

    # Look for beginning of a raw string, and replace them with
    # empty strings.  This is done in a loop to handle multiple raw
    # strings on the same line.
    while delimiter is None:
      # Look for beginning of a raw string.
      # See 2.14.15 [lex.string] for syntax.
      #
      # Once we have matched a raw string, we check the prefix of the
      # line to make sure that the line is not part of a single line
      # comment.  It's done this way because we remove raw strings
      # before removing comments as opposed to removing comments
      # before removing raw strings.  This is because there are some
      # cpplint checks that requires the comments to be preserved, but
      # we don't want to check comments that are inside raw strings.
      matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
      if (matched and
          not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
                    matched.group(1))):
        delimiter = ')' + matched.group(2) + '"'

        end = matched.group(3).find(delimiter)
        if end >= 0:
          # Raw string ended on same line
          line = (matched.group(1) + '""' +
                  matched.group(3)[end + len(delimiter):])
          delimiter = None
        else:
          # Start of a multi-line raw string
          line = matched.group(1) + '""'
      else:
        break

    lines_without_raw_strings.append(line)

  # TODO(unknown): if delimiter is not None here, we might want to
  # emit a warning for unterminated string.
  return lines_without_raw_strings

Removes C ++ 11 raw strings from lines .


def FindNextMultiLineCommentStart(lines, lineix):
  """Find the beginning marker for a multiline comment."""
  while lineix < len(lines):
    if lines[lineix].strip().startswith('/*'):
      # Only return this marker if the comment goes beyond this line
      if lines[lineix].strip().find('*/', 2) < 0:
        return lineix
    lineix += 1
  return len(lines)

def FindNextMultiLineCommentStart ( lines , lineix ) : while lineix < len ( lines ) : if lines [ lineix ] . strip ( ) . startswith ( '/*' ) : if lines [ lineix ] . strip ( ) . find ( '*/' , 2 ) < 0 : return lineix lineix += 1 return len ( lines )

Find the beginning marker for a multiline comment .


def FindNextMultiLineCommentEnd(lines, lineix):
  """We are inside a comment, find the end marker."""
  while lineix < len(lines):
    if lines[lineix].strip().endswith('*/'):
      return lineix
    lineix += 1
  return len(lines)

def FindNextMultiLineCommentEnd ( lines , lineix ) : while lineix < len ( lines ) : if lines [ lineix ] . strip ( ) . endswith ( '*/' ) : return lineix lineix += 1 return len ( lines )

We are inside a comment find the end marker .


def RemoveMultiLineCommentsFromRange(lines, begin, end):
  """Clears a range of lines for multi-line comments."""
  # Having // dummy comments makes the lines non-empty, so we will not get
  # unnecessary blank line warnings later in the code.
  for i in range(begin, end):
    lines[i] = '/**/'

def RemoveMultiLineCommentsFromRange ( lines , begin , end ) : for i in range ( begin , end ) : lines [ i ] = '/**/'

Clears a range of lines for multi - line comments .


def FindEndOfExpressionInLine(line, startpos, stack):
  """Find the position just after the end of current parenthesized expression.

  Args:
    line: a CleansedLines line.
    startpos: start searching at this position.
    stack: nesting stack at startpos.

  Returns:
    On finding matching end: (index just after matching end, None)
    On finding an unclosed expression: (-1, None)
    Otherwise: (-1, new stack at end of this line)
  """
  for i in xrange(startpos, len(line)):
    char = line[i]
    if char in '([{':
      # Found start of parenthesized expression, push to expression stack
      stack.append(char)
    elif char == '<':
      # Found potential start of template argument list
      if i > 0 and line[i - 1] == '<':
        # Left shift operator
        if stack and stack[-1] == '<':
          stack.pop()
          if not stack:
            return (-1, None)
      elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
        # operator<, don't add to stack
        continue
      else:
        # Tentative start of template argument list
        stack.append('<')
    elif char in ')]}':
      # Found end of parenthesized expression.
      #
      # If we are currently expecting a matching '>', the pending '<'
      # must have been an operator.  Remove them from expression stack.
      while stack and stack[-1] == '<':
        stack.pop()
      if not stack:
        return (-1, None)
      if ((stack[-1] == '(' and char == ')') or
          (stack[-1] == '[' and char == ']') or
          (stack[-1] == '{' and char == '}')):
        stack.pop()
        if not stack:
          return (i + 1, None)
      else:
        # Mismatched parentheses
        return (-1, None)
    elif char == '>':
      # Found potential end of template argument list.

      # Ignore "->" and operator functions
      if (i > 0 and
          (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
        continue

      # Pop the stack if there is a matching '<'.  Otherwise, ignore
      # this '>' since it must be an operator.
      if stack:
        if stack[-1] == '<':
          stack.pop()
          if not stack:
            return (i + 1, None)
    elif char == ';':
      # Found something that look like end of statements.  If we are currently
      # expecting a '>', the matching '<' must have been an operator, since
      # template argument list should not contain statements.
      while stack and stack[-1] == '<':
        stack.pop()
      if not stack:
        return (-1, None)

  # Did not find end of expression or unbalanced parentheses on this line
  return (-1, stack)

def FindEndOfExpressionInLine ( line , startpos , stack ) : for i in xrange ( startpos , len ( line ) ) : char = line [ i ] if char in '([{' : stack . append ( char ) elif char == '<' : if i > 0 and line [ i - 1 ] == '<' : if stack and stack [ - 1 ] == '<' : stack . pop ( ) if not stack : return ( - 1 , None ) elif i > 0 and Search ( r'\boperator\s*$' , line [ 0 : i ] ) : continue else : stack . append ( '<' ) elif char in ')]}' : while stack and stack [ - 1 ] == '<' : stack . pop ( ) if not stack : return ( - 1 , None ) if ( ( stack [ - 1 ] == '(' and char == ')' ) or ( stack [ - 1 ] == '[' and char == ']' ) or ( stack [ - 1 ] == '{' and char == '}' ) ) : stack . pop ( ) if not stack : return ( i + 1 , None ) else : return ( - 1 , None ) elif char == '>' : if ( i > 0 and ( line [ i - 1 ] == '-' or Search ( r'\boperator\s*$' , line [ 0 : i - 1 ] ) ) ) : continue if stack : if stack [ - 1 ] == '<' : stack . pop ( ) if not stack : return ( i + 1 , None ) elif char == ';' : while stack and stack [ - 1 ] == '<' : stack . pop ( ) if not stack : return ( - 1 , None ) return ( - 1 , stack )

Find the position just after the end of current parenthesized expression .


def CloseExpression(clean_lines, linenum, pos):
  """If input points to ( or { or [ or <, finds the position that closes it.

  If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
  linenum/pos that correspond to the closing of the expression.

  TODO(unknown): cpplint spends a fair bit of time matching parentheses.
  Ideally we would want to index all opening and closing parentheses once
  and have CloseExpression be just a simple lookup, but due to preprocessor
  tricks, this is not so easy.

  Args:
    clean_lines: A CleansedLines instance containing the file.
    linenum: The number of the line to check.
    pos: A position on the line.

  Returns:
    A tuple (line, linenum, pos) pointer *past* the closing brace, or
    (line, len(lines), -1) if we never find a close.  Note we ignore
    strings and comments when matching; and the line we return is the
    'cleansed' line at linenum.
  """

  line = clean_lines.elided[linenum]
  if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
    return (line, clean_lines.NumLines(), -1)

  # Check first line
  (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
  if end_pos > -1:
    return (line, linenum, end_pos)

  # Continue scanning forward
  while stack and linenum < clean_lines.NumLines() - 1:
    linenum += 1
    line = clean_lines.elided[linenum]
    (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
    if end_pos > -1:
      return (line, linenum, end_pos)

  # Did not find end of expression before end of file, give up
  return (line, clean_lines.NumLines(), -1)

def CloseExpression ( clean_lines , linenum , pos ) : line = clean_lines . elided [ linenum ] if ( line [ pos ] not in '({[<' ) or Match ( r'<[<=]' , line [ pos : ] ) : return ( line , clean_lines . NumLines ( ) , - 1 ) ( end_pos , stack ) = FindEndOfExpressionInLine ( line , pos , [ ] ) if end_pos > - 1 : return ( line , linenum , end_pos ) while stack and linenum < clean_lines . NumLines ( ) - 1 : linenum += 1 line = clean_lines . elided [ linenum ] ( end_pos , stack ) = FindEndOfExpressionInLine ( line , 0 , stack ) if end_pos > - 1 : return ( line , linenum , end_pos ) return ( line , clean_lines . NumLines ( ) , - 1 )

If input points to ( or { or [ or < finds the position that closes it .


def FindStartOfExpressionInLine(line, endpos, stack):
  """Find position at the matching start of current expression.

  This is almost the reverse of FindEndOfExpressionInLine, but note
  that the input position and returned position differs by 1.

  Args:
    line: a CleansedLines line.
    endpos: start searching at this position.
    stack: nesting stack at endpos.

  Returns:
    On finding matching start: (index at matching start, None)
    On finding an unclosed expression: (-1, None)
    Otherwise: (-1, new stack at beginning of this line)
  """
  i = endpos
  while i >= 0:
    char = line[i]
    if char in ')]}':
      # Found end of expression, push to expression stack
      stack.append(char)
    elif char == '>':
      # Found potential end of template argument list.
      #
      # Ignore it if it's a "->" or ">=" or "operator>"
      if (i > 0 and
          (line[i - 1] == '-' or
           Match(r'\s>=\s', line[i - 1:]) or
           Search(r'\boperator\s*$', line[0:i]))):
        i -= 1
      else:
        stack.append('>')
    elif char == '<':
      # Found potential start of template argument list
      if i > 0 and line[i - 1] == '<':
        # Left shift operator
        i -= 1
      else:
        # If there is a matching '>', we can pop the expression stack.
        # Otherwise, ignore this '<' since it must be an operator.
        if stack and stack[-1] == '>':
          stack.pop()
          if not stack:
            return (i, None)
    elif char in '([{':
      # Found start of expression.
      #
      # If there are any unmatched '>' on the stack, they must be
      # operators.  Remove those.
      while stack and stack[-1] == '>':
        stack.pop()
      if not stack:
        return (-1, None)
      if ((char == '(' and stack[-1] == ')') or
          (char == '[' and stack[-1] == ']') or
          (char == '{' and stack[-1] == '}')):
        stack.pop()
        if not stack:
          return (i, None)
      else:
        # Mismatched parentheses
        return (-1, None)
    elif char == ';':
      # Found something that look like end of statements.  If we are currently
      # expecting a '<', the matching '>' must have been an operator, since
      # template argument list should not contain statements.
      while stack and stack[-1] == '>':
        stack.pop()
      if not stack:
        return (-1, None)

    i -= 1

  return (-1, stack)

def FindStartOfExpressionInLine ( line , endpos , stack ) : i = endpos while i >= 0 : char = line [ i ] if char in ')]}' : stack . append ( char ) elif char == '>' : if ( i > 0 and ( line [ i - 1 ] == '-' or Match ( r'\s>=\s' , line [ i - 1 : ] ) or Search ( r'\boperator\s*$' , line [ 0 : i ] ) ) ) : i -= 1 else : stack . append ( '>' ) elif char == '<' : if i > 0 and line [ i - 1 ] == '<' : i -= 1 else : if stack and stack [ - 1 ] == '>' : stack . pop ( ) if not stack : return ( i , None ) elif char in '([{' : while stack and stack [ - 1 ] == '>' : stack . pop ( ) if not stack : return ( - 1 , None ) if ( ( char == '(' and stack [ - 1 ] == ')' ) or ( char == '[' and stack [ - 1 ] == ']' ) or ( char == '{' and stack [ - 1 ] == '}' ) ) : stack . pop ( ) if not stack : return ( i , None ) else : return ( - 1 , None ) elif char == ';' : while stack and stack [ - 1 ] == '>' : stack . pop ( ) if not stack : return ( - 1 , None ) i -= 1 return ( - 1 , stack )

Find position at the matching start of current expression .


def ReverseCloseExpression(clean_lines, linenum, pos):
  """If input points to ) or } or ] or >, finds the position that opens it.

  If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
  linenum/pos that correspond to the opening of the expression.

  Args:
    clean_lines: A CleansedLines instance containing the file.
    linenum: The number of the line to check.
    pos: A position on the line.

  Returns:
    A tuple (line, linenum, pos) pointer *at* the opening brace, or
    (line, 0, -1) if we never find the matching opening brace.  Note
    we ignore strings and comments when matching; and the line we
    return is the 'cleansed' line at linenum.
  """
  line = clean_lines.elided[linenum]
  if line[pos] not in ')}]>':
    return (line, 0, -1)

  # Check last line
  (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
  if start_pos > -1:
    return (line, linenum, start_pos)

  # Continue scanning backward
  while stack and linenum > 0:
    linenum -= 1
    line = clean_lines.elided[linenum]
    (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
    if start_pos > -1:
      return (line, linenum, start_pos)

  # Did not find start of expression before beginning of file, give up
  return (line, 0, -1)

def ReverseCloseExpression ( clean_lines , linenum , pos ) : line = clean_lines . elided [ linenum ] if line [ pos ] not in ')}]>' : return ( line , 0 , - 1 ) ( start_pos , stack ) = FindStartOfExpressionInLine ( line , pos , [ ] ) if start_pos > - 1 : return ( line , linenum , start_pos ) while stack and linenum > 0 : linenum -= 1 line = clean_lines . elided [ linenum ] ( start_pos , stack ) = FindStartOfExpressionInLine ( line , len ( line ) - 1 , stack ) if start_pos > - 1 : return ( line , linenum , start_pos ) return ( line , 0 , - 1 )

If input points to ) or } or ] or > finds the position that opens it .


def CheckForCopyright(filename, lines, error):
  """Logs an error if no Copyright message appears at the top of the file."""

  # We'll say it should occur by line 10. Don't forget there's a
  # dummy line at the front.
  for line in range(1, min(len(lines), 11)):
    if re.search(r'Copyright', lines[line], re.I): break
  else:                       # means no copyright line was found
    error(filename, 0, 'legal/copyright', 5,
          'No copyright message found.  '
          'You should have a line: "Copyright [year] <Copyright Owner>"')

Logs an error if no Copyright message appears at the top of the file .


def GetIndentLevel(line):
  """Return the number of leading spaces in line.

  Args:
    line: A string to check.

  Returns:
    An integer count of leading spaces, possibly zero.
  """
  indent = Match(r'^( *)\S', line)
  if indent:
    return len(indent.group(1))
  else:
    return 0

def
GetIndentLevel
(
line
)
:
indent
=
Match
(
r'^( *)\S'
,
line
)
if
indent
:
return
len
(
indent
.
group
(
1
)
)
else
:
return
0

Return the number of leading spaces in line .


def GetHeaderGuardCPPVariable(filename):
  """Returns the CPP variable that should be used as a header guard.

  Args:
    filename: The name of a C++ header file.

  Returns:
    The CPP variable that should be used as a header guard in the
    named file.

  """

  # Restores original filename in case that cpplint is invoked from Emacs's
  # flymake.
  filename = re.sub(r'_flymake\.h$', '.h', filename)
  filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
  # Replace 'c++' with 'cpp'.
  filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')

  fileinfo = FileInfo(filename)
  file_path_from_root = fileinfo.RepositoryName()
  if _root:
    suffix = os.sep
    # On Windows using directory separator will leave us with
    # "bogus escape error" unless we properly escape regex.
    if suffix == '\\':
      suffix += '\\'
    file_path_from_root = re.sub('^' + _root + suffix, '', file_path_from_root)
  return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'

def GetHeaderGuardCPPVariable ( filename ) : filename = re . sub ( r'_flymake\.h$' , '.h' , filename ) filename = re . sub ( r'/\.flymake/([^/]*)$' , r'/\1' , filename ) filename = filename . replace ( 'C++' , 'cpp' ) . replace ( 'c++' , 'cpp' ) fileinfo = FileInfo ( filename ) file_path_from_root = fileinfo . RepositoryName ( ) if _root : suffix = os . sep if suffix == '\\' : suffix += '\\' file_path_from_root = re . sub ( '^' + _root + suffix , '' , file_path_from_root ) return re . sub ( r'[^a-zA-Z0-9]' , '_' , file_path_from_root ) . upper ( ) + '_'

Returns the CPP variable that should be used as a header guard .


def CheckForHeaderGuard(filename, clean_lines, error):
  """Checks that the file contains a header guard.

  Logs an error if no #ifndef header guard is present.  For other
  headers, checks that the full pathname is used.

  Args:
    filename: The name of the C++ header file.
    clean_lines: A CleansedLines instance containing the file.
    error: The function to call with any errors found.
  """

  # Don't check for header guards if there are error suppression
  # comments somewhere in this file.
  #
  # Because this is silencing a warning for a nonexistent line, we
  # only support the very specific NOLINT(build/header_guard) syntax,
  # and not the general NOLINT or NOLINT(*) syntax.
  raw_lines = clean_lines.lines_without_raw_strings
  for i in raw_lines:
    if Search(r'//\s*NOLINT\(build/header_guard\)', i):
      return

  # Allow pragma once instead of header guards
  for i in raw_lines:
    if Search(r'^\s*#pragma\s+once', i):
      return

  cppvar = GetHeaderGuardCPPVariable(filename)

  ifndef = ''
  ifndef_linenum = 0
  define = ''
  endif = ''
  endif_linenum = 0
  for linenum, line in enumerate(raw_lines):
    linesplit = line.split()
    if len(linesplit) >= 2:
      # find the first occurrence of #ifndef and #define, save arg
      if not ifndef and linesplit[0] == '#ifndef':
        # set ifndef to the header guard presented on the #ifndef line.
        ifndef = linesplit[1]
        ifndef_linenum = linenum
      if not define and linesplit[0] == '#define':
        define = linesplit[1]
    # find the last occurrence of #endif, save entire line
    if line.startswith('#endif'):
      endif = line
      endif_linenum = linenum

  if not ifndef or not define or ifndef != define:
    error(filename, 0, 'build/header_guard', 5,
          'No #ifndef header guard found, suggested CPP variable is: %s' %
          cppvar)
    return

  # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
  # for backward compatibility.
  if ifndef != cppvar:
    error_level = 0
    if ifndef != cppvar + '_':
      error_level = 5

    ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
                            error)
    error(filename, ifndef_linenum, 'build/header_guard', error_level,
          '#ifndef header guard has wrong style, please use: %s' % cppvar)

  # Check for "//" comments on endif line.
  ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
                          error)
  match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
  if match:
    if match.group(1) == '_':
      # Issue low severity warning for deprecated double trailing underscore
      error(filename, endif_linenum, 'build/header_guard', 0,
            '#endif line should be "#endif  // %s"' % cppvar)
    return

  # Didn't find the corresponding "//" comment.  If this file does not
  # contain any "//" comments at all, it could be that the compiler
  # only wants "/**/" comments, look for those instead.
  no_single_line_comments = True
  for i in xrange(1, len(raw_lines) - 1):
    line = raw_lines[i]
    if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
      no_single_line_comments = False
      break

  if no_single_line_comments:
    match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
    if match:
      if match.group(1) == '_':
        # Low severity warning for double trailing underscore
        error(filename, endif_linenum, 'build/header_guard', 0,
              '#endif line should be "#endif  /* %s */"' % cppvar)
      return

  # Didn't find anything
  error(filename, endif_linenum, 'build/header_guard', 5,
        '#endif line should be "#endif  // %s"' % cppvar)

Checks that the file contains a header guard .


def CheckHeaderFileIncluded(filename, include_state, error):
  """Logs an error if a source file does not include its header."""

  # Do not check test files
  fileinfo = FileInfo(filename)
  if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
    return

  for ext in GetHeaderExtensions():
      basefilename = filename[0:len(filename) - len(fileinfo.Extension())]
      headerfile = basefilename + '.' + ext
      if not os.path.exists(headerfile):
        continue
      headername = FileInfo(headerfile).RepositoryName()
      first_include = None
      for section_list in include_state.include_list:
        for f in section_list:
          if headername in f[0] or f[0] in headername:
            return
          if not first_include:
            first_include = f[1]

      error(filename, first_include, 'build/include', 5,
            '%s should include its header file %s' % (fileinfo.RepositoryName(),
                                                      headername))

def
CheckHeaderFileIncluded
(
filename
,
include_state
,
error
)
:
fileinfo
=
FileInfo
(
filename
)
if
Search
(
_TEST_FILE_SUFFIX
,
fileinfo
.
BaseName
(
)
)
:
return
for
ext
in
GetHeaderExtensions
(
)
:
basefilename
=
filename
[
0
:
len
(
filename
)
len
(
fileinfo
.
Extension
(
)
)
]
headerfile
=
basefilename
+
'.'
+
ext
if
not
os
.
path
.
exists
(
headerfile
)
:
continue
headername
=
FileInfo
(
headerfile
)
.
RepositoryName
(
)
first_include
=
for
section_list
in
include_state
.
include_list
:
for
f
in
section_list
:
if
headername
in
f
[
0
]
or
f
[
0
]
in
headername
:
return
if
not
first_include
:
first_include
=
f
[
1
]
error
(
filename
,
first_include
,
'build/include'
,
5
,
'%s should include its header file %s'
%
(
fileinfo
.
RepositoryName
(
)
,
headername
)
)

Logs an error if a source file does not include its header .


def CheckForBadCharacters(filename, lines, error):
  """Logs an error for each line containing bad characters.

  Two kinds of bad characters:

  1. Unicode replacement characters: These indicate that either the file
  contained invalid UTF-8 (likely) or Unicode replacement characters (which
  it shouldn't).  Note that it's possible for this to throw off line
  numbering if the invalid UTF-8 occurred adjacent to a newline.

  2. NUL bytes.  These are problematic for some tools.

  Args:
    filename: The name of the current file.
    lines: An array of strings, each representing a line of the file.
    error: The function to call with any errors found.
  """
  for linenum, line in enumerate(lines):
    if unicode_escape_decode('\ufffd') in line:
      error(filename, linenum, 'readability/utf8', 5,
            'Line contains invalid UTF-8 (or Unicode replacement character).')
    if '\0' in line:
      error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')

Logs an error for each line containing bad characters .


def CheckForNewlineAtEOF(filename, lines, error):
  """Logs an error if there is no newline char at the end of the file.

  Args:
    filename: The name of the current file.
    lines: An array of strings, each representing a line of the file.
    error: The function to call with any errors found.
  """

  # The array lines() was created by adding two newlines to the
  # original file (go figure), then splitting on \n.
  # To verify that the file ends in \n, we just have to make sure the
  # last-but-two element of lines() exists and is empty.
  if len(lines) < 3 or lines[-2]:
    error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
          'Could not find a newline character at the end of the file.')

Logs an error if there is no newline char at the end of the file .


def CheckPosixThreading(filename, clean_lines, linenum, error):
  """Checks for calls to thread-unsafe functions.

  Much code has been originally written without consideration of
  multi-threading. Also, engineers are relying on their old experience;
  they have learned posix before threading extensions were added. These
  tests guide the engineers to use thread-safe functions (when using
  posix directly).

  Args:
    filename: The name of the current file.
    clean_lines: A CleansedLines instance containing the file.
    linenum: The number of the line to check.
    error: The function to call with any errors found.
  """
  line = clean_lines.elided[linenum]
  for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
    # Additional pattern matching check to confirm that this is the
    # function we are looking for
    if Search(pattern, line):
      error(filename, linenum, 'runtime/threadsafe_fn', 2,
            'Consider using ' + multithread_safe_func +
            '...) instead of ' + single_thread_func +
            '...) for improved thread safety.')

def
CheckPosixThreading
(
filename
,
clean_lines
,
linenum
,
error
)
:
line
=
clean_lines
.
elided
[
linenum
]
for
single_thread_func
,
multithread_safe_func
,
pattern
in
_THREADING_LIST
:
if
Search
(
pattern
,
line
)
:
error
(
filename
,
linenum
,
'runtime/threadsafe_fn'
,
2
,
'Consider using '
+
multithread_safe_func
+
'...) instead of '
+
single_thread_func
+
'...) for improved thread safety.'
)

Checks for calls to thread - unsafe functions .


def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
  """Checks for the correctness of various spacing around function calls.

  Args:
    filename: The name of the current file.
    clean_lines: A CleansedLines instance containing the file.
    linenum: The number of the line to check.
    error: The function to call with any errors found.
  """
  line = clean_lines.elided[linenum]

  # Since function calls often occur inside if/for/while/switch
  # expressions - which have their own, more liberal conventions - we
  # first see if we should be looking inside such an expression for a
  # function call, to which we can apply more strict standards.
  fncall = line    # if there's no control flow construct, look at whole line
  for pattern in (r'\bif\s*\((.*)\)\s*{',
                  r'\bfor\s*\((.*)\)\s*{',
                  r'\bwhile\s*\((.*)\)\s*[{;]',
                  r'\bswitch\s*\((.*)\)\s*{'):
    match = Search(pattern, line)
    if match:
      fncall = match.group(1)    # look inside the parens for function calls
      break

  # Except in if/for/while/switch, there should never be space
  # immediately inside parens (eg "f( 3, 4 )").  We make an exception
  # for nested parens ( (a+b) + c ).  Likewise, there should never be
  # a space before a ( when it's a function argument.  I assume it's a
  # function argument when the char before the whitespace is legal in
  # a function name (alnum + _) and we're not starting a macro. Also ignore
  # pointers and references to arrays and functions coz they're too tricky:
  # we use a very simple way to recognize these:
  # " (something)(maybe-something)" or
  # " (something)(maybe-something," or
  # " (something)[something]"
  # Note that we assume the contents of [] to be short enough that
  # they'll never need to wrap.
  if (  # Ignore control structures.
      not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
                 fncall) and
      # Ignore pointers/references to functions.
      not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
      # Ignore pointers/references to arrays.
      not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
    if Search(r'\w\s*\(\s(?!\s*\\$)', fncall):      # a ( used for a fn call
      error(filename, linenum, 'whitespace/parens', 4,
            'Extra space after ( in function call')
    elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
      error(filename, linenum, 'whitespace/parens', 2,
            'Extra space after (')
    if (Search(r'\w\s+\(', fncall) and
        not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and
        not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and
        not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
        not Search(r'\bcase\s+\(', fncall)):
      # TODO(unknown): Space after an operator function seem to be a common
      # error, silence those for now by restricting them to highest verbosity.
      if Search(r'\boperator_*\b', line):
        error(filename, linenum, 'whitespace/parens', 0,
              'Extra space before ( in function call')
      else:
        error(filename, linenum, 'whitespace/parens', 4,
              'Extra space before ( in function call')
    # If the ) is followed only by a newline or a { + newline, assume it's
    # part of a control statement (if/while/etc), and don't complain
    if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
      # If the closing parenthesis is preceded by only whitespaces,
      # try to give a more descriptive error message.
      if Search(r'^\s+\)', fncall):
        error(filename, linenum, 'whitespace/parens', 2,
              'Closing ) should be moved to the previous line')
      else:
        error(filename, linenum, 'whitespace/parens', 2,
              'Extra space before )')

Checks for the correctness of various spacing around function calls .


def CheckForFunctionLengths(filename, clean_lines, linenum,
                            function_state, error):
  """Reports for long function bodies.

  For an overview why this is done, see:
  https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions

  Uses a simplistic algorithm assuming other style guidelines
  (especially spacing) are followed.
  Only checks unindented functions, so class members are unchecked.
  Trivial bodies are unchecked, so constructors with huge initializer lists
  may be missed.
  Blank/comment lines are not counted so as to avoid encouraging the removal
  of vertical space and comments just to get through a lint check.
  NOLINT *on the last line of a function* disables this check.

  Args:
    filename: The name of the current file.
    clean_lines: A CleansedLines instance containing the file.
    linenum: The number of the line to check.
    function_state: Current function name and lines in body so far.
    error: The function to call with any errors found.
  """
  lines = clean_lines.lines
  line = lines[linenum]
  joined_line = ''

  starting_func = False
  regexp = r'(\w(\w|::|\*|\&|\s)*)\('  # decls * & space::name( ...
  match_result = Match(regexp, line)
  if match_result:
    # If the name is all caps and underscores, figure it's a macro and
    # ignore it, unless it's TEST or TEST_F.
    function_name = match_result.group(1).split()[-1]
    if function_name == 'TEST' or function_name == 'TEST_F' or (
        not Match(r'[A-Z_]+$', function_name)):
      starting_func = True

  if starting_func:
    body_found = False
    for start_linenum in range(linenum, clean_lines.NumLines()):
      start_line = lines[start_linenum]
      joined_line += ' ' + start_line.lstrip()
      if Search(r'(;|})', start_line):  # Declarations and trivial functions
        body_found = True
        break                              # ... ignore
      elif Search(r'{', start_line):
        body_found = True
        function = Search(r'((\w|:)*)\(', line).group(1)
        if Match(r'TEST', function):    # Handle TEST... macros
          parameter_regexp = Search(r'(\(.*\))', joined_line)
          if parameter_regexp:             # Ignore bad syntax
            function += parameter_regexp.group(1)
        else:
          function += '()'
        function_state.Begin(function)
        break
    if not body_found:
      # No body for the function (or evidence of a non-function) was found.
      error(filename, linenum, 'readability/fn_size', 5,
            'Lint failed to find start of function body.')
  elif Match(r'^\}\s*$', line):  # function end
    function_state.Check(error, filename, linenum)
    function_state.End()
  elif not Match(r'^\s*$', line):
    function_state.Count()


def CheckComment(line, filename, linenum, next_line_start, error):
  """Checks for common mistakes in comments.

  Args:
    line: The line in question.
    filename: The name of the current file.
    linenum: The number of the line to check.
    next_line_start: The first non-whitespace column of the next line.
    error: The function to call with any errors found.
  """
  commentpos = line.find('//')
  if commentpos != -1:
    # Check if the // may be in quotes.  If so, ignore it
    if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
      # Allow one space for new scopes, two spaces otherwise:
      if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
          ((commentpos >= 1 and
            line[commentpos-1] not in string.whitespace) or
           (commentpos >= 2 and
            line[commentpos-2] not in string.whitespace))):
        error(filename, linenum, 'whitespace/comments', 2,
              'At least two spaces is best between code and comments')

      # Checks for common mistakes in TODO comments.
      comment = line[commentpos:]
      match = _RE_PATTERN_TODO.match(comment)
      if match:
        # One whitespace is correct; zero whitespace is handled elsewhere.
        leading_whitespace = match.group(1)
        if len(leading_whitespace) > 1:
          error(filename, linenum, 'whitespace/todo', 2,
                'Too many spaces before TODO')

        username = match.group(2)
        if not username:
          error(filename, linenum, 'readability/todo', 2,
                'Missing username in TODO; it should look like '
                '"// TODO(my_username): Stuff."')

        middle_whitespace = match.group(3)
        # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
        if middle_whitespace != ' ' and middle_whitespace != '':
          error(filename, linenum, 'whitespace/todo', 2,
                'TODO(my_username) should be followed by a space')

      # If the comment contains an alphanumeric character, there
      # should be a space somewhere between it and the // unless
      # it's a /// or //! Doxygen comment.
      if (Match(r'//[^ ]*\w', comment) and
          not Match(r'(///|//\!)(\s+|$)', comment)):
        error(filename, linenum, 'whitespace/comments', 4,
              'Should have a space between // and comment')

Checks for common mistakes in comments .


def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
  """Checks for the correctness of various spacing issues in the code.

  Things we check for: spaces around operators, spaces after
  if/for/while/switch, no spaces around parens in function calls, two
  spaces between code and comment, don't start a block with a blank
  line, don't end a function with a blank line, don't add a blank line
  after public/protected/private, don't have too many blank lines in a row.

  Args:
    filename: The name of the current file.
    clean_lines: A CleansedLines instance containing the file.
    linenum: The number of the line to check.
    nesting_state: A NestingState instance which maintains information about
                   the current stack of nested blocks being parsed.
    error: The function to call with any errors found.
  """

  # Don't use "elided" lines here, otherwise we can't check commented lines.
  # Don't want to use "raw" either, because we don't want to check inside C++11
  # raw strings,
  raw = clean_lines.lines_without_raw_strings
  line = raw[linenum]

  # Before nixing comments, check if the line is blank for no good
  # reason.  This includes the first line after a block is opened, and
  # blank lines at the end of a function (ie, right before a line like '}'
  #
  # Skip all the blank line checks if we are immediately inside a
  # namespace body.  In other words, don't issue blank line warnings
  # for this block:
  #   namespace {
  #
  #   }
  #
  # A warning about missing end of namespace comments will be issued instead.
  #
  # Also skip blank line checks for 'extern "C"' blocks, which are formatted
  # like namespaces.
  if (IsBlankLine(line) and
      not nesting_state.InNamespaceBody() and
      not nesting_state.InExternC()):
    elided = clean_lines.elided
    prev_line = elided[linenum - 1]
    prevbrace = prev_line.rfind('{')
    # TODO(unknown): Don't complain if line before blank line, and line after,
    #                both start with alnums and are indented the same amount.
    #                This ignores whitespace at the start of a namespace block
    #                because those are not usually indented.
    if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
      # OK, we have a blank line at the start of a code block.  Before we
      # complain, we check if it is an exception to the rule: The previous
      # non-empty line has the parameters of a function header that are indented
      # 4 spaces (because they did not fit in a 80 column line when placed on
      # the same line as the function name).  We also check for the case where
      # the previous line is indented 6 spaces, which may happen when the
      # initializers of a constructor do not fit into a 80 column line.
      exception = False
      if Match(r' {6}\w', prev_line):  # Initializer list?
        # We are looking for the opening column of initializer list, which
        # should be indented 4 spaces to cause 6 space indentation afterwards.
        search_position = linenum-2
        while (search_position >= 0
               and Match(r' {6}\w', elided[search_position])):
          search_position -= 1
        exception = (search_position >= 0
                     and elided[search_position][:5] == '    :')
      else:
        # Search for the function arguments or an initializer list.  We use a
        # simple heuristic here: If the line is indented 4 spaces; and we have a
        # closing paren, without the opening paren, followed by an opening brace
        # or colon (for initializer lists) we assume that it is the last line of
        # a function header.  If we have a colon indented 4 spaces, it is an
        # initializer list.
        exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
                           prev_line)
                     or Match(r' {4}:', prev_line))

      if not exception:
        error(filename, linenum, 'whitespace/blank_line', 2,
              'Redundant blank line at the start of a code block '
              'should be deleted.')
    # Ignore blank lines at the end of a block in a long if-else
    # chain, like this:
    #   if (condition1) {
    #     // Something followed by a blank line
    #
    #   } else if (condition2) {
    #     // Something else
    #   }
    if linenum + 1 < clean_lines.NumLines():
      next_line = raw[linenum + 1]
      if (next_line
          and Match(r'\s*}', next_line)
          and next_line.find('} else ') == -1):
        error(filename, linenum, 'whitespace/blank_line', 3,
              'Redundant blank line at the end of a code block '
              'should be deleted.')

    matched = Match(r'\s*(public|protected|private):', prev_line)
    if matched:
      error(filename, linenum, 'whitespace/blank_line', 3,
            'Do not leave a blank line after "%s:"' % matched.group(1))

  # Next, check comments
  next_line_start = 0
  if linenum + 1 < clean_lines.NumLines():
    next_line = raw[linenum + 1]
    next_line_start = len(next_line) - len(next_line.lstrip())
  CheckComment(line, filename, linenum, next_line_start, error)

  # get rid of comments and strings
  line = clean_lines.elided[linenum]

  # You shouldn't have spaces before your brackets, except maybe after
  # 'delete []' or 'return []() {};'
  if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line):
    error(filename, linenum, 'whitespace/braces', 5,
          'Extra space before [')

  # In range-based for, we wanted spaces before and after the colon, but
  # not around "::" tokens that might appear.
  if (Search(r'for *\(.*[^:]:[^: ]', line) or
      Search(r'for *\(.*[^: ]:[^:]', line)):
    error(filename, linenum, 'whitespace/forcolon', 2,
          'Missing space around colon in range-based for loop')

Checks for the correctness of various spacing issues in the code .


def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
  """Checks for horizontal spacing around parentheses.

  Args:
    filename: The name of the current file.
    clean_lines: A CleansedLines instance containing the file.
    linenum: The number of the line to check.
    error: The function to call with any errors found.
  """
  line = clean_lines.elided[linenum]

  # No spaces after an if, while, switch, or for
  match = Search(r' (if\(|for\(|while\(|switch\()', line)
  if match:
    error(filename, linenum, 'whitespace/parens', 5,
          'Missing space before ( in %s' % match.group(1))

  # For if/for/while/switch, the left and right parens should be
  # consistent about how many spaces are inside the parens, and
  # there should either be zero or one spaces inside the parens.
  # We don't want: "if ( foo)" or "if ( foo   )".
  # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
  match = Search(r'\b(if|for|while|switch)\s*'
                 r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
                 line)
  if match:
    if len(match.group(2)) != len(match.group(4)):
      if not (match.group(3) == ';' and
              len(match.group(2)) == 1 + len(match.group(4)) or
              not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
        error(filename, linenum, 'whitespace/parens', 5,
              'Mismatching spaces inside () in %s' % match.group(1))
    if len(match.group(2)) not in [0, 1]:
      error(filename, linenum, 'whitespace/parens', 5,
            'Should have zero or one spaces inside ( and ) in %s' %
            match.group(1))

Checks for horizontal spacing around parentheses .


def CheckCommaSpacing(filename, clean_lines, linenum, error):
  """Checks for horizontal spacing near commas and semicolons.

  Args:
    filename: The name of the current file.
    clean_lines: A CleansedLines instance containing the file.
    linenum: The number of the line to check.
    error: The function to call with any errors found.
  """
  raw = clean_lines.lines_without_raw_strings
  line = clean_lines.elided[linenum]

  # You should always have a space after a comma (either as fn arg or operator)
  #
  # This does not apply when the non-space character following the
  # comma is another comma, since the only time when that happens is
  # for empty macro arguments.
  #
  # We run this check in two passes: first pass on elided lines to
  # verify that lines contain missing whitespaces, second pass on raw
  # lines to confirm that those missing whitespaces are not due to
  # elided comments.
  if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
      Search(r',[^,\s]', raw[linenum])):
    error(filename, linenum, 'whitespace/comma', 3,
          'Missing space after ,')

  # You should always have a space after a semicolon
  # except for few corner cases
  # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
  # space after ;
  if Search(r';[^\s};\\)/]', line):
    error(filename, linenum, 'whitespace/semicolon', 3,
          'Missing space after ;')

def
CheckCommaSpacing
(
filename
,
clean_lines
,
linenum
,
error
)
:
raw
=
clean_lines
.
lines_without_raw_strings
line
=
clean_lines
.
elided
[
linenum
]
if
(
Search
(
r',[^,\s]'
,
ReplaceAll
(
r'\boperator\s*,\s*\('
,
'F('
,
line
)
)
and
Search
(
r',[^,\s]'
,
raw
[
linenum
]
)
)
:
error
(
filename
,
linenum
,
'whitespace/comma'
,
3
,
'Missing space after ,'
)
if
Search
(
r';[^\s};\\)/]'
,
line
)
:
error
(
filename
,
linenum
,
'whitespace/semicolon'
,
3
,
'Missing space after ;'
)

Checks for horizontal spacing near commas and semicolons .


def _IsType(clean_lines, nesting_state, expr):
  """Check if expression looks like a type name, returns true if so.

  Args:
    clean_lines: A CleansedLines instance containing the file.
    nesting_state: A NestingState instance which maintains information about
                   the current stack of nested blocks being parsed.
    expr: The expression to check.
  Returns:
    True, if token looks like a type.
  """
  # Keep only the last token in the expression
  last_word = Match(r'^.*(\b\S+)$', expr)
  if last_word:
    token = last_word.group(1)
  else:
    token = expr

  # Match native types and stdint types
  if _TYPES.match(token):
    return True

  # Try a bit harder to match templated types.  Walk up the nesting
  # stack until we find something that resembles a typename
  # declaration for what we are looking for.
  typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
                      r'\b')
  block_index = len(nesting_state.stack) - 1
  while block_index >= 0:
    if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
      return False

    # Found where the opening brace is.  We want to scan from this
    # line up to the beginning of the function, minus a few lines.
    #   template <typename Type1,  // stop scanning here
    #             ...>
    #   class C
    #     : public ... {  // start scanning here
    last_line = nesting_state.stack[block_index].starting_linenum

    next_block_start = 0
    if block_index > 0:
      next_block_start = nesting_state.stack[block_index - 1].starting_linenum
    first_line = last_line
    while first_line >= next_block_start:
      if clean_lines.elided[first_line].find('template') >= 0:
        break
      first_line -= 1
    if first_line < next_block_start:
      # Didn't find any "template" keyword before reaching the next block,
      # there are probably no template things to check for this block
      block_index -= 1
      continue

    # Look for typename in the specified range
    for i in xrange(first_line, last_line + 1, 1):
      if Search(typename_pattern, clean_lines.elided[i]):
        return True
    block_index -= 1

  return False

def _IsType ( clean_lines , nesting_state , expr ) : last_word = Match ( r'^.*(\b\S+)$' , expr ) if last_word : token = last_word . group ( 1 ) else : token = expr if _TYPES . match ( token ) : return True typename_pattern = ( r'\b(?:typename|class|struct)\s+' + re . escape ( token ) + r'\b' ) block_index = len ( nesting_state . stack ) - 1 while block_index >= 0 : if isinstance ( nesting_state . stack [ block_index ] , _NamespaceInfo ) : return False last_line = nesting_state . stack [ block_index ] . starting_linenum next_block_start = 0 if block_index > 0 : next_block_start = nesting_state . stack [ block_index - 1 ] . starting_linenum first_line = last_line while first_line >= next_block_start : if clean_lines . elided [ first_line ] . find ( 'template' ) >= 0 : break first_line -= 1 if first_line < next_block_start : block_index -= 1 continue for i in xrange ( first_line , last_line + 1 , 1 ) : if Search ( typename_pattern , clean_lines . elided [ i ] ) : return True block_index -= 1 return False

Check if expression looks like a type name returns true if so .


def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
  """Checks for horizontal spacing near commas.

  Args:
    filename: The name of the current file.
    clean_lines: A CleansedLines instance containing the file.
    linenum: The number of the line to check.
    nesting_state: A NestingState instance which maintains information about
                   the current stack of nested blocks being parsed.
    error: The function to call with any errors found.
  """
  line = clean_lines.elided[linenum]

  # Except after an opening paren, or after another opening brace (in case of
  # an initializer list, for instance), you should have spaces before your
  # braces when they are delimiting blocks, classes, namespaces etc.
  # And since you should never have braces at the beginning of a line,
  # this is an easy test.  Except that braces used for initialization don't
  # follow the same rule; we often don't want spaces before those.
  match = Match(r'^(.*[^ ({>]){', line)

  if match:
    # Try a bit harder to check for brace initialization.  This
    # happens in one of the following forms:
    #   Constructor() : initializer_list_{} { ... }
    #   Constructor{}.MemberFunction()
    #   Type variable{};
    #   FunctionCall(type{}, ...);
    #   LastArgument(..., type{});
    #   LOG(INFO) << type{} << " ...";
    #   map_of_type[{...}] = ...;
    #   ternary = expr ? new type{} : nullptr;
    #   OuterTemplate<InnerTemplateConstructor<Type>{}>
    #
    # We check for the character following the closing brace, and
    # silence the warning if it's one of those listed above, i.e.
    # "{.;,)<>]:".
    #
    # To account for nested initializer list, we allow any number of
    # closing braces up to "{;,)<".  We can't simply silence the
    # warning on first sight of closing brace, because that would
    # cause false negatives for things that are not initializer lists.
    #   Silence this:         But not this:
    #     Outer{                if (...) {
    #       Inner{...}            if (...){  // Missing space before {
    #     };                    }
    #
    # There is a false negative with this approach if people inserted
    # spurious semicolons, e.g. "if (cond){};", but we will catch the
    # spurious semicolon with a separate check.
    leading_text = match.group(1)
    (endline, endlinenum, endpos) = CloseExpression(
        clean_lines, linenum, len(match.group(1)))
    trailing_text = ''
    if endpos > -1:
      trailing_text = endline[endpos:]
    for offset in xrange(endlinenum + 1,
                         min(endlinenum + 3, clean_lines.NumLines() - 1)):
      trailing_text += clean_lines.elided[offset]
    # We also suppress warnings for `uint64_t{expression}` etc., as the style
    # guide recommends brace initialization for integral types to avoid
    # overflow/truncation.
    if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
        and not _IsType(clean_lines, nesting_state, leading_text)):
      error(filename, linenum, 'whitespace/braces', 5,
            'Missing space before {')

  # Make sure '} else {' has spaces.
  if Search(r'}else', line):
    error(filename, linenum, 'whitespace/braces', 5,
          'Missing space before else')

  # You shouldn't have a space before a semicolon at the end of the line.
  # There's a special case for "for" since the style guide allows space before
  # the semicolon there.
  if Search(r':\s*;\s*$', line):
    error(filename, linenum, 'whitespace/semicolon', 5,
          'Semicolon defining empty statement. Use {} instead.')
  elif Search(r'^\s*;\s*$', line):
    error(filename, linenum, 'whitespace/semicolon', 5,
          'Line contains only semicolon. If this should be an empty statement, '
          'use {} instead.')
  elif (Search(r'\s+;\s*$', line) and
        not Search(r'\bfor\b', line)):
    error(filename, linenum, 'whitespace/semicolon', 5,
          'Extra space before last semicolon. If this should be an empty '
          'statement, use {} instead.')

Checks for horizontal spacing near commas .


def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
  """Checks for additional blank line issues related to sections.

  Currently the only thing checked here is blank line before protected/private.

  Args:
    filename: The name of the current file.
    clean_lines: A CleansedLines instance containing the file.
    class_info: A _ClassInfo objects.
    linenum: The number of the line to check.
    error: The function to call with any errors found.
  """
  # Skip checks if the class is small, where small means 25 lines or less.
  # 25 lines seems like a good cutoff since that's the usual height of
  # terminals, and any class that can't fit in one screen can't really
  # be considered "small".
  #
  # Also skip checks if we are on the first line.  This accounts for
  # classes that look like
  #   class Foo { public: ... };
  #
  # If we didn't find the end of the class, last_line would be zero,
  # and the check will be skipped by the first condition.
  if (class_info.last_line - class_info.starting_linenum <= 24 or
      linenum <= class_info.starting_linenum):
    return

  matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
  if matched:
    # Issue warning if the line before public/protected/private was
    # not a blank line, but don't do this if the previous line contains
    # "class" or "struct".  This can happen two ways:
    #  - We are at the beginning of the class.
    #  - We are forward-declaring an inner class that is semantically
    #    private, but needed to be public for implementation reasons.
    # Also ignores cases where the previous line ends with a backslash as can be
    # common when defining classes in C macros.
    prev_line = clean_lines.lines[linenum - 1]
    if (not IsBlankLine(prev_line) and
        not Search(r'\b(class|struct)\b', prev_line) and
        not Search(r'\\$', prev_line)):
      # Try a bit harder to find the beginning of the class.  This is to
      # account for multi-line base-specifier lists, e.g.:
      #   class Derived
      #       : public Base {
      end_class_head = class_info.starting_linenum
      for i in range(class_info.starting_linenum, linenum):
        if Search(r'\{\s*$', clean_lines.lines[i]):
          end_class_head = i
          break
      if end_class_head < linenum - 1:
        error(filename, linenum, 'whitespace/blank_line', 3,
              '"%s:" should be preceded by a blank line' % matched.group(1))

Checks for additional blank line issues related to sections .


def GetPreviousNonBlankLine(clean_lines, linenum):
  """Return the most recent non-blank line and its line number.

  Args:
    clean_lines: A CleansedLines instance containing the file contents.
    linenum: The number of the line to check.

  Returns:
    A tuple with two elements.  The first element is the contents of the last
    non-blank line before the current line, or the empty string if this is the
    first non-blank line.  The second is the line number of that line, or -1
    if this is the first non-blank line.
  """

  prevlinenum = linenum - 1
  while prevlinenum >= 0:
    prevline = clean_lines.elided[prevlinenum]
    if not IsBlankLine(prevline):     # if not a blank line...
      return (prevline, prevlinenum)
    prevlinenum -= 1
  return ('', -1)

def GetPreviousNonBlankLine ( clean_lines , linenum ) : prevlinenum = linenum - 1 while prevlinenum >= 0 : prevline = clean_lines . elided [ prevlinenum ] if not IsBlankLine ( prevline ) : return ( prevline , prevlinenum ) prevlinenum -= 1 return ( '' , - 1 )

Return the most recent non - blank line and its line number .


def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
  """Looks for redundant trailing semicolon.

  Args:
    filename: The name of the current file.
    clean_lines: A CleansedLines instance containing the file.
    linenum: The number of the line to check.
    error: The function to call with any errors found.
  """

  line = clean_lines.elided[linenum]

  # Block bodies should not be followed by a semicolon.  Due to C++11
  # brace initialization, there are more places where semicolons are
  # required than not, so we use a whitelist approach to check these
  # rather than a blacklist.  These are the places where "};" should
  # be replaced by just "}":
  # 1. Some flavor of block following closing parenthesis:
  #    for (;;) {};
  #    while (...) {};
  #    switch (...) {};
  #    Function(...) {};
  #    if (...) {};
  #    if (...) else if (...) {};
  #
  # 2. else block:
  #    if (...) else {};
  #
  # 3. const member function:
  #    Function(...) const {};
  #
  # 4. Block following some statement:
  #    x = 42;
  #    {};
  #
  # 5. Block at the beginning of a function:
  #    Function(...) {
  #      {};
  #    }
  #
  #    Note that naively checking for the preceding "{" will also match
  #    braces inside multi-dimensional arrays, but this is fine since
  #    that expression will not contain semicolons.
  #
  # 6. Block following another block:
  #    while (true) {}
  #    {};
  #
  # 7. End of namespaces:
  #    namespace {};
  #
  #    These semicolons seems far more common than other kinds of
  #    redundant semicolons, possibly due to people converting classes
  #    to namespaces.  For now we do not warn for this case.
  #
  # Try matching case 1 first.
  match = Match(r'^(.*\)\s*)\{', line)
  if match:
    # Matched closing parenthesis (case 1).  Check the token before the
    # matching opening parenthesis, and don't warn if it looks like a
    # macro.  This avoids these false positives:
    #  - macro that defines a base class
    #  - multi-line macro that defines a base class
    #  - macro that defines the whole class-head
    #
    # But we still issue warnings for macros that we know are safe to
    # warn, specifically:
    #  - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
    #  - TYPED_TEST
    #  - INTERFACE_DEF
    #  - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
    #
    # We implement a whitelist of safe macros instead of a blacklist of
    # unsafe macros, even though the latter appears less frequently in
    # google code and would have been easier to implement.  This is because
    # the downside for getting the whitelist wrong means some extra
    # semicolons, while the downside for getting the blacklist wrong
    # would result in compile errors.
    #
    # In addition to macros, we also don't want to warn on
    #  - Compound literals
    #  - Lambdas
    #  - alignas specifier with anonymous structs
    #  - decltype
    closing_brace_pos = match.group(1).rfind(')')
    opening_parenthesis = ReverseCloseExpression(
        clean_lines, linenum, closing_brace_pos)
    if opening_parenthesis[2] > -1:
      line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
      macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
      func = Match(r'^(.*\])\s*$', line_prefix)
      if ((macro and
           macro.group(1) not in (
               'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
               'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
               'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
          (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
          Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
          Search(r'\bdecltype$', line_prefix) or
          Search(r'\s+=\s*$', line_prefix)):
        match = None
    if (match and
        opening_parenthesis[1] > 1 and
        Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
      # Multi-line lambda-expression
      match = None

  else:
    # Try matching cases 2-3.
    match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
    if not match:
      # Try matching cases 4-6.  These are always matched on separate lines.
      #
      # Note that we can't simply concatenate the previous line to the
      # current line and do a single match, otherwise we may output
      # duplicate warnings for the blank line case:
      #   if (cond) {
      #     // blank line
      #   }
      prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
      if prevline and Search(r'[;{}]\s*$', prevline):
        match = Match(r'^(\s*)\{', line)

  # Check matching closing brace
  if match:
    (endline, endlinenum, endpos) = CloseExpression(
        clean_lines, linenum, len(match.group(1)))
    if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
      # Current {} pair is eligible for semicolon check, and we have found
      # the redundant semicolon, output warning here.
      #
      # Note: because we are scanning forward for opening braces, and
      # outputting warnings for the matching closing brace, if there are
      # nested blocks with trailing semicolons, we will get the error
      # messages in reversed order.

      # We need to check the line forward for NOLINT
      raw_lines = clean_lines.raw_lines
      ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,
                              error)
      ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum,
                              error)

      error(filename, endlinenum, 'readability/braces', 4,
            "You don't need a ; after a }")

def
CheckTrailingSemicolon
(
filename
,
clean_lines
,
linenum
,
error
)
:
line
=
clean_lines
.
elided
[
linenum
]
match
=
Match
(
r'^(.*\)\s*)\{'
,
line
)
if
match
:
closing_brace_pos
=
match
.
group
(
1
)
.
rfind
(
')'
)
opening_parenthesis
=
ReverseCloseExpression
(
clean_lines
,
linenum
,
closing_brace_pos
)
if
opening_parenthesis
[
2
]
>
1
:
line_prefix
=
opening_parenthesis
[
0
]
[
0
:
opening_parenthesis
[
2
]
]
macro
=
Search
(
r'\b([A-Z_][A-Z0-9_]*)\s*$'
,
line_prefix
)
func
=
Match
(
r'^(.*\])\s*$'
,
line_prefix
)
if
(
(
macro
and
macro
.
group
(
1
)
not
in
(
'TEST'
,
'TEST_F'
,
'MATCHER'
,
'MATCHER_P'
,
'TYPED_TEST'
,
'EXCLUSIVE_LOCKS_REQUIRED'
,
'SHARED_LOCKS_REQUIRED'
,
'LOCKS_EXCLUDED'
,
'INTERFACE_DEF'
)
)
or
(
func
and
not
Search
(
r'\boperator\s*\[\s*\]'
,
func
.
group
(
1
)
)
)
or
Search
(
r'\b(?:struct|union)\s+alignas\s*$'
,
line_prefix
)
or
Search
(
r'\bdecltype$'
,
line_prefix
)
or
Search
(
r'\s+=\s*$'
,
line_prefix
)
)
:
match
=
if
(
match
and
opening_parenthesis
[
1
]
>
1
and
Search
(
r'\]\s*$'
,
clean_lines
.
elided
[
opening_parenthesis
[
1
]
1
]
)
)
:
match
=
else
:
match
=
Match
(
r'^(.*(?:else|\)\s*const)\s*)\{'
,
line
)
if
not
match
:
prevline
=
GetPreviousNonBlankLine
(
clean_lines
,
linenum
)
[
0
]
if
prevline
and
Search
(
r'[;{}]\s*$'
,
prevline
)
:
match
=
Match
(
r'^(\s*)\{'
,
line
)
if
match
:
(
endline
,
endlinenum
,
endpos
)
=
CloseExpression
(
clean_lines
,
linenum
,
len
(
match
.
group
(
1
)
)
)
if
endpos
>
1
and
Match
(
r'^\s*;'
,
endline
[
endpos
:
]
)
:
raw_lines
=
clean_lines
.
raw_lines
ParseNolintSuppressions
(
filename
,
raw_lines
[
endlinenum
1
]
,
endlinenum
1
,
error
)
ParseNolintSuppressions
(
filename
,
raw_lines
[
endlinenum
]
,
endlinenum
,
error
)
error
(
filename
,
endlinenum
,
'readability/braces'
,
4
,
"You don't need a ; after a }"
)

Looks for redundant trailing semicolon .


def FindCheckMacro(line):
  """Find a replaceable CHECK-like macro.

  Args:
    line: line to search on.
  Returns:
    (macro name, start position), or (None, -1) if no replaceable
    macro is found.
  """
  for macro in _CHECK_MACROS:
    i = line.find(macro)
    if i >= 0:
      # Find opening parenthesis.  Do a regular expression match here
      # to make sure that we are matching the expected CHECK macro, as
      # opposed to some other macro that happens to contain the CHECK
      # substring.
      matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
      if not matched:
        continue
      return (macro, len(matched.group(1)))
  return (None, -1)

def FindCheckMacro ( line ) : for macro in _CHECK_MACROS : i = line . find ( macro ) if i >= 0 : matched = Match ( r'^(.*\b' + macro + r'\s*)\(' , line ) if not matched : continue return ( macro , len ( matched . group ( 1 ) ) ) return ( None , - 1 )


def CheckCheck(filename, clean_lines, linenum, error):
  """Checks the use of CHECK and EXPECT macros.

  Args:
    filename: The name of the current file.
    clean_lines: A CleansedLines instance containing the file.
    linenum: The number of the line to check.
    error: The function to call with any errors found.
  """

  # Decide the set of replacement macros that should be suggested
  lines = clean_lines.elided
  (check_macro, start_pos) = FindCheckMacro(lines[linenum])
  if not check_macro:
    return

  # Find end of the boolean expression by matching parentheses
  (last_line, end_line, end_pos) = CloseExpression(
      clean_lines, linenum, start_pos)
  if end_pos < 0:
    return

  # If the check macro is followed by something other than a
  # semicolon, assume users will log their own custom error messages
  # and don't suggest any replacements.
  if not Match(r'\s*;', last_line[end_pos:]):
    return

  if linenum == end_line:
    expression = lines[linenum][start_pos + 1:end_pos - 1]
  else:
    expression = lines[linenum][start_pos + 1:]
    for i in xrange(linenum + 1, end_line):
      expression += lines[i]
    expression += last_line[0:end_pos - 1]

  # Parse expression so that we can take parentheses into account.
  # This avoids false positives for inputs like "CHECK((a < 4) == b)",
  # which is not replaceable by CHECK_LE.
  lhs = ''
  rhs = ''
  operator = None
  while expression:
    matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
                    r'==|!=|>=|>|<=|<|\()(.*)$', expression)
    if matched:
      token = matched.group(1)
      if token == '(':
        # Parenthesized operand
        expression = matched.group(2)
        (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
        if end < 0:
          return  # Unmatched parenthesis
        lhs += '(' + expression[0:end]
        expression = expression[end:]
      elif token in ('&&', '||'):
        # Logical and/or operators.  This means the expression
        # contains more than one term, for example:
        #   CHECK(42 < a && a < b);
        #
        # These are not replaceable with CHECK_LE, so bail out early.
        return
      elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
        # Non-relational operator
        lhs += token
        expression = matched.group(2)
      else:
        # Relational operator
        operator = token
        rhs = matched.group(2)
        break
    else:
      # Unparenthesized operand.  Instead of appending to lhs one character
      # at a time, we do another regular expression match to consume several
      # characters at once if possible.  Trivial benchmark shows that this
      # is more efficient when the operands are longer than a single
      # character, which is generally the case.
      matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
      if not matched:
        matched = Match(r'^(\s*\S)(.*)$', expression)
        if not matched:
          break
      lhs += matched.group(1)
      expression = matched.group(2)

  # Only apply checks if we got all parts of the boolean expression
  if not (lhs and operator and rhs):
    return

  # Check that rhs do not contain logical operators.  We already know
  # that lhs is fine since the loop above parses out && and ||.
  if rhs.find('&&') > -1 or rhs.find('||') > -1:
    return

  # At least one of the operands must be a constant literal.  This is
  # to avoid suggesting replacements for unprintable things like
  # CHECK(variable != iterator)
  #
  # The following pattern matches decimal, hex integers, strings, and
  # characters (in that order).
  lhs = lhs.strip()
  rhs = rhs.strip()
  match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
  if Match(match_constant, lhs) or Match(match_constant, rhs):
    # Note: since we know both lhs and rhs, we can provide a more
    # descriptive error message like:
    #   Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
    # Instead of:
    #   Consider using CHECK_EQ instead of CHECK(a == b)
    #
    # We are still keeping the less descriptive message because if lhs
    # or rhs gets long, the error message might become unreadable.
    error(filename, linenum, 'readability/check', 2,
          'Consider using %s instead of %s(a %s b)' % (
              _CHECK_REPLACEMENT[check_macro][operator],
              check_macro, operator))

Checks the use of CHECK and EXPECT macros .


def CheckAltTokens(filename, clean_lines, linenum, error):
  """Check alternative keywords being used in boolean expressions.

  Args:
    filename: The name of the current file.
    clean_lines: A CleansedLines instance containing the file.
    linenum: The number of the line to check.
    error: The function to call with any errors found.
  """
  line = clean_lines.elided[linenum]

  # Avoid preprocessor lines
  if Match(r'^\s*#', line):
    return

  # Last ditch effort to avoid multi-line comments.  This will not help
  # if the comment started before the current line or ended after the
  # current line, but it catches most of the false positives.  At least,
  # it provides a way to workaround this warning for people who use
  # multi-line comments in preprocessor macros.
  #
  # TODO(unknown): remove this once cpplint has better support for
  # multi-line comments.
  if line.find('/*') >= 0 or line.find('*/') >= 0:
    return

  for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
    error(filename, linenum, 'readability/alt_tokens', 2,
          'Use operator %s instead of %s' % (
              _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))

def
CheckAltTokens
(
filename
,
clean_lines
,
linenum
,
error
)
:
line
=
clean_lines
.
elided
[
linenum
]
if
Match
(
r'^\s*#'
,
line
)
:
return
if
line
.
find
(
'/*'
)
>=
0
or
line
.
find
(
'*/'
)
>=
0
:
return
for
match
in
_ALT_TOKEN_REPLACEMENT_PATTERN
.
finditer
(
line
)
:
error
(
filename
,
linenum
,
'readability/alt_tokens'
,
2
,
'Use operator %s instead of %s'
%
(
_ALT_TOKEN_REPLACEMENT
[
match
.
group
(
1
)
]
,
match
.
group
(
1
)
)
)

Check alternative keywords being used in boolean expressions .


def GetLineWidth(line):
  """Determines the width of the line in column positions.

  Args:
    line: A string, which may be a Unicode string.

  Returns:
    The width of the line in column positions, accounting for Unicode
    combining characters and wide characters.
  """
  if isinstance(line, unicode):
    width = 0
    for uc in unicodedata.normalize('NFC', line):
      if unicodedata.east_asian_width(uc) in ('W', 'F'):
        width += 2
      elif not unicodedata.combining(uc):
        width += 1
    return width
  else:
    return len(line)

def GetLineWidth ( line ) : if isinstance ( line , unicode ) : width = 0 for uc in unicodedata . normalize ( 'NFC' , line ) : if unicodedata . east_asian_width ( uc ) in ( 'W' , 'F' ) : width += 2 elif not unicodedata . combining ( uc ) : width += 1 return width else : return len ( line )

Determines the width of the line in column positions .