# -*- coding: utf-8 -*-
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
""" This module implements the 'scan-build' command API.

To run the static analyzer against a build is done in multiple steps:

 -- Intercept: capture the compilation command during the build,
 -- Analyze:   run the analyzer against the captured commands,
 -- Report:    create a cover report from the analyzer outputs.  """

import re
import os
import os.path
import json
import logging
import multiprocessing
import tempfile
import functools
import subprocess
import contextlib
import datetime
import shutil
import glob
from collections import defaultdict

from libscanbuild import command_entry_point, compiler_wrapper, \
    wrapper_environment, run_build, run_command, CtuConfig
from libscanbuild.arguments import parse_args_for_scan_build, \
    parse_args_for_analyze_build
from libscanbuild.intercept import capture
from libscanbuild.report import document
from libscanbuild.compilation import split_command, classify_source, \
    compiler_language
from libscanbuild.clang import get_version, get_arguments, get_triple_arch, \
    ClangErrorException
from libscanbuild.shell import decode

__all__ = ['scan_build', 'analyze_build', 'analyze_compiler_wrapper']

COMPILER_WRAPPER_CC = 'analyze-cc'
COMPILER_WRAPPER_CXX = 'analyze-c++'

CTU_EXTDEF_MAP_FILENAME = 'externalDefMap.txt'
CTU_TEMP_DEFMAP_FOLDER = 'tmpExternalDefMaps'


@command_entry_point
def scan_build():
    """ Entry point for scan-build command. """

    args = parse_args_for_scan_build()
    # will re-assign the report directory as new output
    with report_directory(
            args.output, args.keep_empty, args.output_format) as args.output:
        # Run against a build command. there are cases, when analyzer run
        # is not required. But we need to set up everything for the
        # wrappers, because 'configure' needs to capture the CC/CXX values
        # for the Makefile.
        if args.intercept_first:
            # Run build command with intercept module.
            exit_code = capture(args)
            # Run the analyzer against the captured commands.
            if need_analyzer(args.build):
                govern_analyzer_runs(args)
        else:
            # Run build command and analyzer with compiler wrappers.
            environment = setup_environment(args)
            exit_code = run_build(args.build, env=environment)
        # Cover report generation and bug counting.
        number_of_bugs = document(args)
        # Set exit status as it was requested.
        return number_of_bugs if args.status_bugs else exit_code


@command_entry_point
def analyze_build():
    """ Entry point for analyze-build command. """

    args = parse_args_for_analyze_build()
    # will re-assign the report directory as new output
    with report_directory(args.output, args.keep_empty, args.output_format) as args.output:
        # Run the analyzer against a compilation db.
        govern_analyzer_runs(args)
        # Cover report generation and bug counting.
        number_of_bugs = document(args)
        # Set exit status as it was requested.
        return number_of_bugs if args.status_bugs else 0


def need_analyzer(args):
    """ Check the intent of the build command.

    When static analyzer run against project configure step, it should be
    silent and no need to run the analyzer or generate report.

    To run `scan-build` against the configure step might be necessary,
    when compiler wrappers are used. That's the moment when build setup
    check the compiler and capture the location for the build process. """

    return len(args) and not re.search(r'configure|autogen', args[0])


def prefix_with(constant, pieces):
    """ From a sequence create another sequence where every second element
    is from the original sequence and the odd elements are the prefix.

    eg.: prefix_with(0, [1,2,3]) creates [0, 1, 0, 2, 0, 3] """

    return [elem for piece in pieces for elem in [constant, piece]]


def get_ctu_config_from_args(args):
    """ CTU configuration is created from the chosen phases and dir. """

    return (
        CtuConfig(collect=args.ctu_phases.collect,
                  analyze=args.ctu_phases.analyze,
                  dir=args.ctu_dir,
                  extdef_map_cmd=args.extdef_map_cmd)
        if hasattr(args, 'ctu_phases') and hasattr(args.ctu_phases, 'dir')
        else CtuConfig(collect=False, analyze=False, dir='', extdef_map_cmd=''))


def get_ctu_config_from_json(ctu_conf_json):
    """ CTU configuration is created from the chosen phases and dir. """

    ctu_config = json.loads(ctu_conf_json)
    # Recover namedtuple from json when coming from analyze-cc or analyze-c++
    return CtuConfig(collect=ctu_config[0],
                     analyze=ctu_config[1],
                     dir=ctu_config[2],
                     extdef_map_cmd=ctu_config[3])


def create_global_ctu_extdef_map(extdef_map_lines):
    """ Takes iterator of individual external definition maps and creates a
    global map keeping only unique names. We leave conflicting names out of
    CTU.

    :param extdef_map_lines: Contains the id of a definition (mangled name) and
    the originating source (the corresponding AST file) name.
    :type extdef_map_lines: Iterator of str.
    :returns: Mangled name - AST file pairs.
    :rtype: List of (str, str) tuples.
    """

    mangled_to_asts = defaultdict(set)

    for line in extdef_map_lines:
        mangled_name, ast_file = line.strip().split(' ', 1)
        mangled_to_asts[mangled_name].add(ast_file)

    mangled_ast_pairs = []

    for mangled_name, ast_files in mangled_to_asts.items():
        if len(ast_files) == 1:
            mangled_ast_pairs.append((mangled_name, next(iter(ast_files))))

    return mangled_ast_pairs


def merge_ctu_extdef_maps(ctudir):
    """ Merge individual external definition maps into a global one.

    As the collect phase runs parallel on multiple threads, all compilation
    units are separately mapped into a temporary file in CTU_TEMP_DEFMAP_FOLDER.
    These definition maps contain the mangled names and the source
    (AST generated from the source) which had their definition.
    These files should be merged at the end into a global map file:
    CTU_EXTDEF_MAP_FILENAME."""

    def generate_extdef_map_lines(extdefmap_dir):
        """ Iterate over all lines of input files in a determined order. """

        files = glob.glob(os.path.join(extdefmap_dir, '*'))
        files.sort()
        for filename in files:
            with open(filename, 'r') as in_file:
                for line in in_file:
                    yield line

    def write_global_map(arch, mangled_ast_pairs):
        """ Write (mangled name, ast file) pairs into final file. """

        extern_defs_map_file = os.path.join(ctudir, arch,
                                           CTU_EXTDEF_MAP_FILENAME)
        with open(extern_defs_map_file, 'w') as out_file:
            for mangled_name, ast_file in mangled_ast_pairs:
                out_file.write('%s %s\n' % (mangled_name, ast_file))

    triple_arches = glob.glob(os.path.join(ctudir, '*'))
    for triple_path in triple_arches:
        if os.path.isdir(triple_path):
            triple_arch = os.path.basename(triple_path)
            extdefmap_dir = os.path.join(ctudir, triple_arch,
                                     CTU_TEMP_DEFMAP_FOLDER)

            extdef_map_lines = generate_extdef_map_lines(extdefmap_dir)
            mangled_ast_pairs = create_global_ctu_extdef_map(extdef_map_lines)
            write_global_map(triple_arch, mangled_ast_pairs)

            # Remove all temporary files
            shutil.rmtree(extdefmap_dir, ignore_errors=True)


def run_analyzer_parallel(args):
    """ Runs the analyzer against the given compilation database. """

    def exclude(filename, directory):
        """ Return true when any excluded directory prefix the filename. """
        if not os.path.isabs(filename):
            # filename is either absolute or relative to directory. Need to turn
            # it to absolute since 'args.excludes' are absolute paths.
            filename = os.path.normpath(os.path.join(directory, filename))
        return any(re.match(r'^' + exclude_directory, filename)
                   for exclude_directory in args.excludes)

    consts = {
        'clang': args.clang,
        'output_dir': args.output,
        'output_format': args.output_format,
        'output_failures': args.output_failures,
        'direct_args': analyzer_params(args),
        'force_debug': args.force_debug,
        'ctu': get_ctu_config_from_args(args)
    }

    logging.debug('run analyzer against compilation database')
    with open(args.cdb, 'r') as handle:
        generator = (dict(cmd, **consts)
                     for cmd in json.load(handle) if not exclude(
                            cmd['file'], cmd['directory']))
        # when verbose output requested execute sequentially
        pool = multiprocessing.Pool(1 if args.verbose > 2 else None)
        for current in pool.imap_unordered(run, generator):
            if current is not None:
                # display error message from the static analyzer
                for line in current['error_output']:
                    logging.info(line.rstrip())
        pool.close()
        pool.join()


def govern_analyzer_runs(args):
    """ Governs multiple runs in CTU mode or runs once in normal mode. """

    ctu_config = get_ctu_config_from_args(args)
    # If we do a CTU collect (1st phase) we remove all previous collection
    # data first.
    if ctu_config.collect:
        shutil.rmtree(ctu_config.dir, ignore_errors=True)

    # If the user asked for a collect (1st) and analyze (2nd) phase, we do an
    # all-in-one run where we deliberately remove collection data before and
    # also after the run. If the user asks only for a single phase data is
    # left so multiple analyze runs can use the same data gathered by a single
    # collection run.
    if ctu_config.collect and ctu_config.analyze:
        # CTU strings are coming from args.ctu_dir and extdef_map_cmd,
        # so we can leave it empty
        args.ctu_phases = CtuConfig(collect=True, analyze=False,
                                    dir='', extdef_map_cmd='')
        run_analyzer_parallel(args)
        merge_ctu_extdef_maps(ctu_config.dir)
        args.ctu_phases = CtuConfig(collect=False, analyze=True,
                                    dir='', extdef_map_cmd='')
        run_analyzer_parallel(args)
        shutil.rmtree(ctu_config.dir, ignore_errors=True)
    else:
        # Single runs (collect or analyze) are launched from here.
        run_analyzer_parallel(args)
        if ctu_config.collect:
            merge_ctu_extdef_maps(ctu_config.dir)


def setup_environment(args):
    """ Set up environment for build command to interpose compiler wrapper. """

    environment = dict(os.environ)
    environment.update(wrapper_environment(args))
    environment.update({
        'CC': COMPILER_WRAPPER_CC,
        'CXX': COMPILER_WRAPPER_CXX,
        'ANALYZE_BUILD_CLANG': args.clang if need_analyzer(args.build) else '',
        'ANALYZE_BUILD_REPORT_DIR': args.output,
        'ANALYZE_BUILD_REPORT_FORMAT': args.output_format,
        'ANALYZE_BUILD_REPORT_FAILURES': 'yes' if args.output_failures else '',
        'ANALYZE_BUILD_PARAMETERS': ' '.join(analyzer_params(args)),
        'ANALYZE_BUILD_FORCE_DEBUG': 'yes' if args.force_debug else '',
        'ANALYZE_BUILD_CTU': json.dumps(get_ctu_config_from_args(args))
    })
    return environment


@command_entry_point
def analyze_compiler_wrapper():
    """ Entry point for `analyze-cc` and `analyze-c++` compiler wrappers. """

    return compiler_wrapper(analyze_compiler_wrapper_impl)


def analyze_compiler_wrapper_impl(result, execution):
    """ Implements analyzer compiler wrapper functionality. """

    # don't run analyzer when compilation fails. or when it's not requested.
    if result or not os.getenv('ANALYZE_BUILD_CLANG'):
        return

    # check is it a compilation?
    compilation = split_command(execution.cmd)
    if compilation is None:
        return
    # collect the needed parameters from environment, crash when missing
    parameters = {
        'clang': os.getenv('ANALYZE_BUILD_CLANG'),
        'output_dir': os.getenv('ANALYZE_BUILD_REPORT_DIR'),
        'output_format': os.getenv('ANALYZE_BUILD_REPORT_FORMAT'),
        'output_failures': os.getenv('ANALYZE_BUILD_REPORT_FAILURES'),
        'direct_args': os.getenv('ANALYZE_BUILD_PARAMETERS',
                                 '').split(' '),
        'force_debug': os.getenv('ANALYZE_BUILD_FORCE_DEBUG'),
        'directory': execution.cwd,
        'command': [execution.cmd[0], '-c'] + compilation.flags,
        'ctu': get_ctu_config_from_json(os.getenv('ANALYZE_BUILD_CTU'))
    }
    # call static analyzer against the compilation
    for source in compilation.files:
        parameters.update({'file': source})
        logging.debug('analyzer parameters %s', parameters)
        current = run(parameters)
        # display error message from the static analyzer
        if current is not None:
            for line in current['error_output']:
                logging.info(line.rstrip())


@contextlib.contextmanager
def report_directory(hint, keep, output_format):
    """ Responsible for the report directory.

    hint -- could specify the parent directory of the output directory.
    keep -- a boolean value to keep or delete the empty report directory. """

    stamp_format = 'scan-build-%Y-%m-%d-%H-%M-%S-%f-'
    stamp = datetime.datetime.now().strftime(stamp_format)
    parent_dir = os.path.abspath(hint)
    if not os.path.exists(parent_dir):
        os.makedirs(parent_dir)
    name = tempfile.mkdtemp(prefix=stamp, dir=parent_dir)

    logging.info('Report directory created: %s', name)

    try:
        yield name
    finally:
        if os.listdir(name):
            if output_format != 'sarif':
                # 'scan-view' currently does not support sarif format.
                msg = "Run 'scan-view %s' to examine bug reports."
            else:
                msg = "View result at %s/results-merged.sarif."
            keep = True
        else:
            if keep:
                msg = "Report directory '%s' contains no report, but kept."
            else:
                msg = "Removing directory '%s' because it contains no report."
        logging.warning(msg, name)

        if not keep:
            os.rmdir(name)


def analyzer_params(args):
    """ A group of command line arguments can mapped to command
    line arguments of the analyzer. This method generates those. """

    result = []

    if args.store_model:
        result.append('-analyzer-store={0}'.format(args.store_model))
    if args.constraints_model:
        result.append('-analyzer-constraints={0}'.format(
            args.constraints_model))
    if args.internal_stats:
        result.append('-analyzer-stats')
    if args.analyze_headers:
        result.append('-analyzer-opt-analyze-headers')
    if args.stats:
        result.append('-analyzer-checker=debug.Stats')
    if args.maxloop:
        result.extend(['-analyzer-max-loop', str(args.maxloop)])
    if args.output_format:
        result.append('-analyzer-output={0}'.format(args.output_format))
    if args.analyzer_config:
        result.extend(['-analyzer-config', args.analyzer_config])
    if args.verbose >= 4:
        result.append('-analyzer-display-progress')
    if args.plugins:
        result.extend(prefix_with('-load', args.plugins))
    if args.enable_checker:
        checkers = ','.join(args.enable_checker)
        result.extend(['-analyzer-checker', checkers])
    if args.disable_checker:
        checkers = ','.join(args.disable_checker)
        result.extend(['-analyzer-disable-checker', checkers])

    return prefix_with('-Xclang', result)


def require(required):
    """ Decorator for checking the required values in state.

    It checks the required attributes in the passed state and stop when
    any of those is missing. """

    def decorator(function):
        @functools.wraps(function)
        def wrapper(*args, **kwargs):
            for key in required:
                if key not in args[0]:
                    raise KeyError('{0} not passed to {1}'.format(
                        key, function.__name__))

            return function(*args, **kwargs)

        return wrapper

    return decorator


@require(['command',  # entry from compilation database
          'directory',  # entry from compilation database
          'file',  # entry from compilation database
          'clang',  # clang executable name (and path)
          'direct_args',  # arguments from command line
          'force_debug',  # kill non debug macros
          'output_dir',  # where generated report files shall go
          'output_format',  # it's 'plist', 'html', 'plist-html', 'plist-multi-file', or 'sarif'
          'output_failures',  # generate crash reports or not
          'ctu'])  # ctu control options
def run(opts):
    """ Entry point to run (or not) static analyzer against a single entry
    of the compilation database.

    This complex task is decomposed into smaller methods which are calling
    each other in chain. If the analysis is not possible the given method
    just return and break the chain.

    The passed parameter is a python dictionary. Each method first check
    that the needed parameters received. (This is done by the 'require'
    decorator. It's like an 'assert' to check the contract between the
    caller and the called method.) """

    try:
        command = opts.pop('command')
        command = command if isinstance(command, list) else decode(command)
        logging.debug("Run analyzer against '%s'", command)
        opts.update(classify_parameters(command))

        return arch_check(opts)
    except Exception:
        logging.error("Problem occurred during analysis.", exc_info=1)
        return None


@require(['clang', 'directory', 'flags', 'file', 'output_dir', 'language',
          'error_output', 'exit_code'])
def report_failure(opts):
    """ Create report when analyzer failed.

    The major report is the preprocessor output. The output filename generated
    randomly. The compiler output also captured into '.stderr.txt' file.
    And some more execution context also saved into '.info.txt' file. """

    def extension():
        """ Generate preprocessor file extension. """

        mapping = {'objective-c++': '.mii', 'objective-c': '.mi', 'c++': '.ii'}
        return mapping.get(opts['language'], '.i')

    def destination():
        """ Creates failures directory if not exits yet. """

        failures_dir = os.path.join(opts['output_dir'], 'failures')
        if not os.path.isdir(failures_dir):
            os.makedirs(failures_dir)
        return failures_dir

    # Classify error type: when Clang terminated by a signal it's a 'Crash'.
    # (python subprocess Popen.returncode is negative when child terminated
    # by signal.) Everything else is 'Other Error'.
    error = 'crash' if opts['exit_code'] < 0 else 'other_error'
    # Create preprocessor output file name. (This is blindly following the
    # Perl implementation.)
    (handle, name) = tempfile.mkstemp(suffix=extension(),
                                      prefix='clang_' + error + '_',
                                      dir=destination())
    os.close(handle)
    # Execute Clang again, but run the syntax check only.
    cwd = opts['directory']
    cmd = [opts['clang'], '-fsyntax-only', '-E'] + opts['flags'] + \
        [opts['file'], '-o', name]
    try:
        cmd = get_arguments(cmd, cwd)
        run_command(cmd, cwd=cwd)
    except subprocess.CalledProcessError:
        pass
    except ClangErrorException:
        pass
    # write general information about the crash
    with open(name + '.info.txt', 'w') as handle:
        handle.write(opts['file'] + os.linesep)
        handle.write(error.title().replace('_', ' ') + os.linesep)
        handle.write(' '.join(cmd) + os.linesep)
        handle.write(' '.join(os.uname()) + os.linesep)
        handle.write(get_version(opts['clang']))
        handle.close()
    # write the captured output too
    with open(name + '.stderr.txt', 'w') as handle:
        handle.writelines(opts['error_output'])
        handle.close()


@require(['clang', 'directory', 'flags', 'direct_args', 'file', 'output_dir',
          'output_format'])
def run_analyzer(opts, continuation=report_failure):
    """ It assembles the analysis command line and executes it. Capture the
    output of the analysis and returns with it. If failure reports are
    requested, it calls the continuation to generate it. """

    def target():
        """ Creates output file name for reports. """
        if opts['output_format'] in {
                'plist',
                'plist-html',
                'plist-multi-file'}:
            (handle, name) = tempfile.mkstemp(prefix='report-',
                                              suffix='.plist',
                                              dir=opts['output_dir'])
            os.close(handle)
            return name
        elif opts['output_format'] == 'sarif':
            (handle, name) = tempfile.mkstemp(prefix='result-',
                                              suffix='.sarif',
                                              dir=opts['output_dir'])
            os.close(handle)
            return name
        return opts['output_dir']

    try:
        cwd = opts['directory']
        cmd = get_arguments([opts['clang'], '--analyze'] +
                            opts['direct_args'] + opts['flags'] +
                            [opts['file'], '-o', target()],
                            cwd)
        output = run_command(cmd, cwd=cwd)
        return {'error_output': output, 'exit_code': 0}
    except subprocess.CalledProcessError as ex:
        result = {'error_output': ex.output, 'exit_code': ex.returncode}
        if opts.get('output_failures', False):
            opts.update(result)
            continuation(opts)
        return result
    except ClangErrorException as ex:
        result = {'error_output': ex.error, 'exit_code': 0}
        if opts.get('output_failures', False):
            opts.update(result)
            continuation(opts)
        return result


def extdef_map_list_src_to_ast(extdef_src_list):
    """ Turns textual external definition map list with source files into an
    external definition map list with ast files. """

    extdef_ast_list = []
    for extdef_src_txt in extdef_src_list:
        mangled_name, path = extdef_src_txt.split(" ", 1)
        # Normalize path on windows as well
        path = os.path.splitdrive(path)[1]
        # Make relative path out of absolute
        path = path[1:] if path[0] == os.sep else path
        ast_path = os.path.join("ast", path + ".ast")
        extdef_ast_list.append(mangled_name + " " + ast_path)
    return extdef_ast_list


@require(['clang', 'directory', 'flags', 'direct_args', 'file', 'ctu'])
def ctu_collect_phase(opts):
    """ Preprocess source by generating all data needed by CTU analysis. """

    def generate_ast(triple_arch):
        """ Generates ASTs for the current compilation command. """

        args = opts['direct_args'] + opts['flags']
        ast_joined_path = os.path.join(opts['ctu'].dir, triple_arch, 'ast',
                                       os.path.realpath(opts['file'])[1:] +
                                       '.ast')
        ast_path = os.path.abspath(ast_joined_path)
        ast_dir = os.path.dirname(ast_path)
        if not os.path.isdir(ast_dir):
            try:
                os.makedirs(ast_dir)
            except OSError:
                # In case an other process already created it.
                pass
        ast_command = [opts['clang'], '-emit-ast']
        ast_command.extend(args)
        ast_command.append('-w')
        ast_command.append(opts['file'])
        ast_command.append('-o')
        ast_command.append(ast_path)
        logging.debug("Generating AST using '%s'", ast_command)
        run_command(ast_command, cwd=opts['directory'])

    def map_extdefs(triple_arch):
        """ Generate external definition map file for the current source. """

        args = opts['direct_args'] + opts['flags']
        extdefmap_command = [opts['ctu'].extdef_map_cmd]
        extdefmap_command.append(opts['file'])
        extdefmap_command.append('--')
        extdefmap_command.extend(args)
        logging.debug("Generating external definition map using '%s'",
                      extdefmap_command)
        extdef_src_list = run_command(extdefmap_command, cwd=opts['directory'])
        extdef_ast_list = extdef_map_list_src_to_ast(extdef_src_list)
        extern_defs_map_folder = os.path.join(opts['ctu'].dir, triple_arch,
                                             CTU_TEMP_DEFMAP_FOLDER)
        if not os.path.isdir(extern_defs_map_folder):
            try:
                os.makedirs(extern_defs_map_folder)
            except OSError:
                # In case an other process already created it.
                pass
        if extdef_ast_list:
            with tempfile.NamedTemporaryFile(mode='w',
                                             dir=extern_defs_map_folder,
                                             delete=False) as out_file:
                out_file.write("\n".join(extdef_ast_list) + "\n")

    cwd = opts['directory']
    cmd = [opts['clang'], '--analyze'] + opts['direct_args'] + opts['flags'] \
        + [opts['file']]
    triple_arch = get_triple_arch(cmd, cwd)
    generate_ast(triple_arch)
    map_extdefs(triple_arch)


@require(['ctu'])
def dispatch_ctu(opts, continuation=run_analyzer):
    """ Execute only one phase of 2 phases of CTU if needed. """

    ctu_config = opts['ctu']

    if ctu_config.collect or ctu_config.analyze:
        assert ctu_config.collect != ctu_config.analyze
        if ctu_config.collect:
            return ctu_collect_phase(opts)
        if ctu_config.analyze:
            cwd = opts['directory']
            cmd = [opts['clang'], '--analyze'] + opts['direct_args'] \
                + opts['flags'] + [opts['file']]
            triarch = get_triple_arch(cmd, cwd)
            ctu_options = ['ctu-dir=' + os.path.join(ctu_config.dir, triarch),
                           'experimental-enable-naive-ctu-analysis=true']
            analyzer_options = prefix_with('-analyzer-config', ctu_options)
            direct_options = prefix_with('-Xanalyzer', analyzer_options)
            opts['direct_args'].extend(direct_options)

    return continuation(opts)


@require(['flags', 'force_debug'])
def filter_debug_flags(opts, continuation=dispatch_ctu):
    """ Filter out nondebug macros when requested. """

    if opts.pop('force_debug'):
        # lazy implementation just append an undefine macro at the end
        opts.update({'flags': opts['flags'] + ['-UNDEBUG']})

    return continuation(opts)


@require(['language', 'compiler', 'file', 'flags'])
def language_check(opts, continuation=filter_debug_flags):
    """ Find out the language from command line parameters or file name
    extension. The decision also influenced by the compiler invocation. """

    accepted = frozenset({
        'c', 'c++', 'objective-c', 'objective-c++', 'c-cpp-output',
        'c++-cpp-output', 'objective-c-cpp-output'
    })

    # language can be given as a parameter...
    language = opts.pop('language')
    compiler = opts.pop('compiler')
    # ... or find out from source file extension
    if language is None and compiler is not None:
        language = classify_source(opts['file'], compiler == 'c')

    if language is None:
        logging.debug('skip analysis, language not known')
        return None
    elif language not in accepted:
        logging.debug('skip analysis, language not supported')
        return None
    else:
        logging.debug('analysis, language: %s', language)
        opts.update({'language': language,
                     'flags': ['-x', language] + opts['flags']})
        return continuation(opts)


@require(['arch_list', 'flags'])
def arch_check(opts, continuation=language_check):
    """ Do run analyzer through one of the given architectures. """

    disabled = frozenset({'ppc', 'ppc64'})

    received_list = opts.pop('arch_list')
    if received_list:
        # filter out disabled architectures and -arch switches
        filtered_list = [a for a in received_list if a not in disabled]
        if filtered_list:
            # There should be only one arch given (or the same multiple
            # times). If there are multiple arch are given and are not
            # the same, those should not change the pre-processing step.
            # But that's the only pass we have before run the analyzer.
            current = filtered_list.pop()
            logging.debug('analysis, on arch: %s', current)

            opts.update({'flags': ['-arch', current] + opts['flags']})
            return continuation(opts)
        else:
            logging.debug('skip analysis, found not supported arch')
            return None
    else:
        logging.debug('analysis, on default arch')
        return continuation(opts)


# To have good results from static analyzer certain compiler options shall be
# omitted. The compiler flag filtering only affects the static analyzer run.
#
# Keys are the option name, value number of options to skip
IGNORED_FLAGS = {
    '-c': 0,  # compile option will be overwritten
    '-fsyntax-only': 0,  # static analyzer option will be overwritten
    '-o': 1,  # will set up own output file
    # flags below are inherited from the perl implementation.
    '-g': 0,
    '-save-temps': 0,
    '-install_name': 1,
    '-exported_symbols_list': 1,
    '-current_version': 1,
    '-compatibility_version': 1,
    '-init': 1,
    '-e': 1,
    '-seg1addr': 1,
    '-bundle_loader': 1,
    '-multiply_defined': 1,
    '-sectorder': 3,
    '--param': 1,
    '--serialize-diagnostics': 1
}


def classify_parameters(command):
    """ Prepare compiler flags (filters some and add others) and take out
    language (-x) and architecture (-arch) flags for future processing. """

    result = {
        'flags': [],  # the filtered compiler flags
        'arch_list': [],  # list of architecture flags
        'language': None,  # compilation language, None, if not specified
        'compiler': compiler_language(command)  # 'c' or 'c++'
    }

    # iterate on the compile options
    args = iter(command[1:])
    for arg in args:
        # take arch flags into a separate basket
        if arg == '-arch':
            result['arch_list'].append(next(args))
        # take language
        elif arg == '-x':
            result['language'] = next(args)
        # parameters which looks source file are not flags
        elif re.match(r'^[^-].+', arg) and classify_source(arg):
            pass
        # ignore some flags
        elif arg in IGNORED_FLAGS:
            count = IGNORED_FLAGS[arg]
            for _ in range(count):
                next(args)
        # we don't care about extra warnings, but we should suppress ones
        # that we don't want to see.
        elif re.match(r'^-W.+', arg) and not re.match(r'^-Wno-.+', arg):
            pass
        # and consider everything else as compilation flag.
        else:
            result['flags'].append(arg)

    return result

[((53, 11, 53, 38), 'libscanbuild.arguments.parse_args_for_scan_build', 'parse_args_for_scan_build', ({}, {}), '()', False, 'from libscanbuild.arguments import parse_args_for_scan_build, parse_args_for_analyze_build\n'), ((81, 11, 81, 41), 'libscanbuild.arguments.parse_args_for_analyze_build', 'parse_args_for_analyze_build', ({}, {}), '()', False, 'from libscanbuild.arguments import parse_args_for_scan_build, parse_args_for_analyze_build\n'), ((129, 17, 129, 42), 'json.loads', 'json.loads', ({(129, 28, 129, 41): 'ctu_conf_json'}, {}), '(ctu_conf_json)', False, 'import json\n'), ((131, 11, 134, 50), 'libscanbuild.CtuConfig', 'CtuConfig', (), '', False, 'from libscanbuild import command_entry_point, compiler_wrapper, wrapper_environment, run_build, run_command, CtuConfig\n'), ((149, 22, 149, 38), 'collections.defaultdict', 'defaultdict', ({(149, 34, 149, 37): 'set'}, {}), '(set)', False, 'from collections import defaultdict\n'), ((230, 4, 230, 62), 'logging.debug', 'logging.debug', ({(230, 18, 230, 61): '"""run analyzer against compilation database"""'}, {}), "('run analyzer against compilation database')", False, 'import logging\n'), ((301, 11, 301, 58), 'libscanbuild.compiler_wrapper', 'compiler_wrapper', ({(301, 28, 301, 57): 'analyze_compiler_wrapper_impl'}, {}), '(analyze_compiler_wrapper_impl)', False, 'from libscanbuild import command_entry_point, compiler_wrapper, wrapper_environment, run_build, run_command, CtuConfig\n'), ((312, 18, 312, 46), 'libscanbuild.compilation.split_command', 'split_command', ({(312, 32, 312, 45): 'execution.cmd'}, {}), '(execution.cmd)', False, 'from libscanbuild.compilation import split_command, classify_source, compiler_language\n'), ((348, 17, 348, 38), 'os.path.abspath', 'os.path.abspath', ({(348, 33, 348, 37): 'hint'}, {}), '(hint)', False, 'import os\n'), ((351, 11, 351, 57), 'tempfile.mkdtemp', 'tempfile.mkdtemp', (), '', False, 'import tempfile\n'), ((353, 4, 353, 54), 'logging.info', 'logging.info', ({(353, 17, 353, 47): '"""Report directory created: %s"""', (353, 49, 353, 53): 'name'}, {}), "('Report directory created: %s', name)", False, 'import logging\n'), ((501, 4, 501, 20), 'os.close', 'os.close', ({(501, 13, 501, 19): 'handle'}, {}), '(handle)', False, 'import os\n'), ((648, 18, 648, 43), 'libscanbuild.clang.get_triple_arch', 'get_triple_arch', ({(648, 34, 648, 37): 'cmd', (648, 39, 648, 42): 'cwd'}, {}), '(cmd, cwd)', False, 'from libscanbuild.clang import get_version, get_arguments, get_triple_arch, ClangErrorException\n'), ((72, 25, 72, 39), 'libscanbuild.report.document', 'document', ({(72, 34, 72, 38): 'args'}, {}), '(args)', False, 'from libscanbuild.report import document\n'), ((87, 25, 87, 39), 'libscanbuild.report.document', 'document', ({(87, 34, 87, 38): 'args'}, {}), '(args)', False, 'from libscanbuild.report import document\n'), ((118, 8, 121, 53), 'libscanbuild.CtuConfig', 'CtuConfig', (), '', False, 'from libscanbuild import command_entry_point, compiler_wrapper, wrapper_environment, run_build, run_command, CtuConfig\n'), ((123, 13, 123, 79), 'libscanbuild.CtuConfig', 'CtuConfig', (), '', False, 'from libscanbuild import command_entry_point, compiler_wrapper, wrapper_environment, run_build, run_command, CtuConfig\n'), ((187, 31, 188, 67), 'os.path.join', 'os.path.join', ({(187, 44, 187, 50): 'ctudir', (187, 52, 187, 56): 'arch', (188, 43, 188, 66): 'CTU_EXTDEF_MAP_FILENAME'}, {}), '(ctudir, arch, CTU_EXTDEF_MAP_FILENAME)', False, 'import os\n'), ((193, 30, 193, 55), 'os.path.join', 'os.path.join', ({(193, 43, 193, 49): 'ctudir', (193, 51, 193, 54): '"""*"""'}, {}), "(ctudir, '*')", False, 'import os\n'), ((195, 11, 195, 37), 'os.path.isdir', 'os.path.isdir', ({(195, 25, 195, 36): 'triple_path'}, {}), '(triple_path)', False, 'import os\n'), ((236, 15, 236, 68), 'multiprocessing.Pool', 'multiprocessing.Pool', ({(236, 36, 236, 67): '1 if args.verbose > 2 else None'}, {}), '(1 if args.verbose > 2 else None)', False, 'import multiprocessing\n'), ((253, 8, 253, 57), 'shutil.rmtree', 'shutil.rmtree', (), '', False, 'import shutil\n'), ((263, 26, 264, 62), 'libscanbuild.CtuConfig', 'CtuConfig', (), '', False, 'from libscanbuild import command_entry_point, compiler_wrapper, wrapper_environment, run_build, run_command, CtuConfig\n'), ((267, 26, 268, 62), 'libscanbuild.CtuConfig', 'CtuConfig', (), '', False, 'from libscanbuild import command_entry_point, compiler_wrapper, wrapper_environment, run_build, run_command, CtuConfig\n'), ((270, 8, 270, 57), 'shutil.rmtree', 'shutil.rmtree', (), '', False, 'import shutil\n'), ((282, 23, 282, 48), 'libscanbuild.wrapper_environment', 'wrapper_environment', ({(282, 43, 282, 47): 'args'}, {}), '(args)', False, 'from libscanbuild import command_entry_point, compiler_wrapper, wrapper_environment, run_build, run_command, CtuConfig\n'), ((317, 17, 317, 49), 'os.getenv', 'os.getenv', ({(317, 27, 317, 48): '"""ANALYZE_BUILD_CLANG"""'}, {}), "('ANALYZE_BUILD_CLANG')", False, 'import os\n'), ((318, 22, 318, 59), 'os.getenv', 'os.getenv', ({(318, 32, 318, 58): '"""ANALYZE_BUILD_REPORT_DIR"""'}, {}), "('ANALYZE_BUILD_REPORT_DIR')", False, 'import os\n'), ((319, 25, 319, 65), 'os.getenv', 'os.getenv', ({(319, 35, 319, 64): '"""ANALYZE_BUILD_REPORT_FORMAT"""'}, {}), "('ANALYZE_BUILD_REPORT_FORMAT')", False, 'import os\n'), ((320, 27, 320, 69), 'os.getenv', 'os.getenv', ({(320, 37, 320, 68): '"""ANALYZE_BUILD_REPORT_FAILURES"""'}, {}), "('ANALYZE_BUILD_REPORT_FAILURES')", False, 'import os\n'), ((323, 23, 323, 61), 'os.getenv', 'os.getenv', ({(323, 33, 323, 60): '"""ANALYZE_BUILD_FORCE_DEBUG"""'}, {}), "('ANALYZE_BUILD_FORCE_DEBUG')", False, 'import os\n'), ((331, 8, 331, 59), 'logging.debug', 'logging.debug', ({(331, 22, 331, 46): '"""analyzer parameters %s"""', (331, 48, 331, 58): 'parameters'}, {}), "('analyzer parameters %s', parameters)", False, 'import logging\n'), ((349, 11, 349, 37), 'os.path.exists', 'os.path.exists', ({(349, 26, 349, 36): 'parent_dir'}, {}), '(parent_dir)', False, 'import os\n'), ((350, 8, 350, 31), 'os.makedirs', 'os.makedirs', ({(350, 20, 350, 30): 'parent_dir'}, {}), '(parent_dir)', False, 'import os\n'), ((358, 11, 358, 27), 'os.listdir', 'os.listdir', ({(358, 22, 358, 26): 'name'}, {}), '(name)', False, 'import os\n'), ((370, 8, 370, 34), 'logging.warning', 'logging.warning', ({(370, 24, 370, 27): 'msg', (370, 29, 370, 33): 'name'}, {}), '(msg, name)', False, 'import logging\n'), ((420, 9, 420, 34), 'functools.wraps', 'functools.wraps', ({(420, 25, 420, 33): 'function'}, {}), '(function)', False, 'import functools\n'), ((460, 8, 460, 59), 'logging.debug', 'logging.debug', ({(460, 22, 460, 49): '"""Run analyzer against \'%s\'"""', (460, 51, 460, 58): 'command'}, {}), '("Run analyzer against \'%s\'", command)', False, 'import logging\n'), ((487, 23, 487, 67), 'os.path.join', 'os.path.join', ({(487, 36, 487, 54): "opts['output_dir']", (487, 56, 487, 66): '"""failures"""'}, {}), "(opts['output_dir'], 'failures')", False, 'import os\n'), ((507, 14, 507, 37), 'libscanbuild.clang.get_arguments', 'get_arguments', ({(507, 28, 507, 31): 'cmd', (507, 33, 507, 36): 'cwd'}, {}), '(cmd, cwd)', False, 'from libscanbuild.clang import get_version, get_arguments, get_triple_arch, ClangErrorException\n'), ((508, 8, 508, 33), 'libscanbuild.run_command', 'run_command', (), '', False, 'from libscanbuild import command_entry_point, compiler_wrapper, wrapper_environment, run_build, run_command, CtuConfig\n'), ((559, 17, 559, 42), 'libscanbuild.run_command', 'run_command', (), '', False, 'from libscanbuild import command_entry_point, compiler_wrapper, wrapper_environment, run_build, run_command, CtuConfig\n'), ((586, 19, 586, 53), 'os.path.join', 'os.path.join', ({(586, 32, 586, 37): '"""ast"""', (586, 39, 586, 52): "path + '.ast'"}, {}), "('ast', path + '.ast')", False, 'import os\n'), ((602, 19, 602, 51), 'os.path.abspath', 'os.path.abspath', ({(602, 35, 602, 50): 'ast_joined_path'}, {}), '(ast_joined_path)', False, 'import os\n'), ((603, 18, 603, 43), 'os.path.dirname', 'os.path.dirname', ({(603, 34, 603, 42): 'ast_path'}, {}), '(ast_path)', False, 'import os\n'), ((616, 8, 616, 63), 'logging.debug', 'logging.debug', ({(616, 22, 616, 49): '"""Generating AST using \'%s\'"""', (616, 51, 616, 62): 'ast_command'}, {}), '("Generating AST using \'%s\'", ast_command)', False, 'import logging\n'), ((617, 8, 617, 55), 'libscanbuild.run_command', 'run_command', (), '', False, 'from libscanbuild import command_entry_point, compiler_wrapper, wrapper_environment, run_build, run_command, CtuConfig\n'), ((627, 8, 628, 40), 'logging.debug', 'logging.debug', ({(627, 22, 627, 69): '"""Generating external definition map using \'%s\'"""', (628, 22, 628, 39): 'extdefmap_command'}, {}), '("Generating external definition map using \'%s\'",\n    extdefmap_command)', False, 'import logging\n'), ((629, 26, 629, 79), 'libscanbuild.run_command', 'run_command', (), '', False, 'from libscanbuild import command_entry_point, compiler_wrapper, wrapper_environment, run_build, run_command, CtuConfig\n'), ((631, 33, 632, 68), 'os.path.join', 'os.path.join', ({(631, 46, 631, 61): "opts['ctu'].dir", (631, 63, 631, 74): 'triple_arch', (632, 45, 632, 67): 'CTU_TEMP_DEFMAP_FOLDER'}, {}), "(opts['ctu'].dir, triple_arch, CTU_TEMP_DEFMAP_FOLDER)", False, 'import os\n'), ((703, 19, 703, 65), 'libscanbuild.compilation.classify_source', 'classify_source', ({(703, 35, 703, 47): "opts['file']", (703, 49, 703, 64): "compiler == 'c'"}, {}), "(opts['file'], compiler == 'c')", False, 'from libscanbuild.compilation import split_command, classify_source, compiler_language\n'), ((706, 8, 706, 58), 'logging.debug', 'logging.debug', ({(706, 22, 706, 57): '"""skip analysis, language not known"""'}, {}), "('skip analysis, language not known')", False, 'import logging\n'), ((742, 8, 742, 50), 'logging.debug', 'logging.debug', ({(742, 22, 742, 49): '"""analysis, on default arch"""'}, {}), "('analysis, on default arch')", False, 'import logging\n'), ((780, 20, 780, 46), 'libscanbuild.compilation.compiler_language', 'compiler_language', ({(780, 38, 780, 45): 'command'}, {}), '(command)', False, 'from libscanbuild.compilation import split_command, classify_source, compiler_language\n'), ((63, 24, 63, 37), 'libscanbuild.intercept.capture', 'capture', ({(63, 32, 63, 36): 'args'}, {}), '(args)', False, 'from libscanbuild.intercept import capture\n'), ((70, 24, 70, 62), 'libscanbuild.run_build', 'run_build', (), '', False, 'from libscanbuild import command_entry_point, compiler_wrapper, wrapper_environment, run_build, run_command, CtuConfig\n'), ((102, 29, 102, 69), 're.search', 're.search', ({(102, 39, 102, 59): '"""configure|autogen"""', (102, 61, 102, 68): 'args[0]'}, {}), "('configure|autogen', args[0])", False, 'import re\n'), ((177, 26, 177, 58), 'os.path.join', 'os.path.join', ({(177, 39, 177, 52): 'extdefmap_dir', (177, 54, 177, 57): '"""*"""'}, {}), "(extdefmap_dir, '*')", False, 'import os\n'), ((196, 26, 196, 55), 'os.path.basename', 'os.path.basename', ({(196, 43, 196, 54): 'triple_path'}, {}), '(triple_path)', False, 'import os\n'), ((197, 28, 198, 60), 'os.path.join', 'os.path.join', ({(197, 41, 197, 47): 'ctudir', (197, 49, 197, 60): 'triple_arch', (198, 37, 198, 59): 'CTU_TEMP_DEFMAP_FOLDER'}, {}), '(ctudir, triple_arch, CTU_TEMP_DEFMAP_FOLDER)', False, 'import os\n'), ((205, 12, 205, 60), 'shutil.rmtree', 'shutil.rmtree', (), '', False, 'import shutil\n'), ((213, 15, 213, 38), 'os.path.isabs', 'os.path.isabs', ({(213, 29, 213, 37): 'filename'}, {}), '(filename)', False, 'import os\n'), ((308, 21, 308, 53), 'os.getenv', 'os.getenv', ({(308, 31, 308, 52): '"""ANALYZE_BUILD_CLANG"""'}, {}), "('ANALYZE_BUILD_CLANG')", False, 'import os\n'), ((326, 40, 326, 70), 'os.getenv', 'os.getenv', ({(326, 50, 326, 69): '"""ANALYZE_BUILD_CTU"""'}, {}), "('ANALYZE_BUILD_CTU')", False, 'import os\n'), ((347, 12, 347, 35), 'datetime.datetime.now', 'datetime.datetime.now', ({}, {}), '()', False, 'import datetime\n'), ((373, 12, 373, 26), 'os.rmdir', 'os.rmdir', ({(373, 21, 373, 25): 'name'}, {}), '(name)', False, 'import os\n'), ((459, 60, 459, 75), 'libscanbuild.shell.decode', 'decode', ({(459, 67, 459, 74): 'command'}, {}), '(command)', False, 'from libscanbuild.shell import decode\n'), ((465, 8, 465, 70), 'logging.error', 'logging.error', (), '', False, 'import logging\n'), ((488, 15, 488, 42), 'os.path.isdir', 'os.path.isdir', ({(488, 29, 488, 41): 'failures_dir'}, {}), '(failures_dir)', False, 'import os\n'), ((489, 12, 489, 37), 'os.makedirs', 'os.makedirs', ({(489, 24, 489, 36): 'failures_dir'}, {}), '(failures_dir)', False, 'import os\n'), ((519, 21, 519, 47), 'libscanbuild.clang.get_version', 'get_version', ({(519, 33, 519, 46): "opts['clang']"}, {}), "(opts['clang'])", False, 'from libscanbuild.clang import get_version, get_arguments, get_triple_arch, ClangErrorException\n'), ((540, 29, 542, 69), 'tempfile.mkstemp', 'tempfile.mkstemp', (), '', False, 'import tempfile\n'), ((543, 12, 543, 28), 'os.close', 'os.close', ({(543, 21, 543, 27): 'handle'}, {}), '(handle)', False, 'import os\n'), ((583, 15, 583, 39), 'os.path.splitdrive', 'os.path.splitdrive', ({(583, 34, 583, 38): 'path'}, {}), '(path)', False, 'import os\n'), ((604, 15, 604, 37), 'os.path.isdir', 'os.path.isdir', ({(604, 29, 604, 36): 'ast_dir'}, {}), '(ast_dir)', False, 'import os\n'), ((633, 15, 633, 52), 'os.path.isdir', 'os.path.isdir', ({(633, 29, 633, 51): 'extern_defs_map_folder'}, {}), '(extern_defs_map_folder)', False, 'import os\n'), ((667, 22, 667, 47), 'libscanbuild.clang.get_triple_arch', 'get_triple_arch', ({(667, 38, 667, 41): 'cmd', (667, 43, 667, 46): 'cwd'}, {}), '(cmd, cwd)', False, 'from libscanbuild.clang import get_version, get_arguments, get_triple_arch, ClangErrorException\n'), ((709, 8, 709, 62), 'logging.debug', 'logging.debug', ({(709, 22, 709, 61): '"""skip analysis, language not supported"""'}, {}), "('skip analysis, language not supported')", False, 'import logging\n'), ((712, 8, 712, 57), 'logging.debug', 'logging.debug', ({(712, 22, 712, 46): '"""analysis, language: %s"""', (712, 48, 712, 56): 'language'}, {}), "('analysis, language: %s', language)", False, 'import logging\n'), ((734, 12, 734, 59), 'logging.debug', 'logging.debug', ({(734, 26, 734, 49): '"""analysis, on arch: %s"""', (734, 51, 734, 58): 'current'}, {}), "('analysis, on arch: %s', current)", False, 'import logging\n'), ((739, 12, 739, 68), 'logging.debug', 'logging.debug', ({(739, 26, 739, 67): '"""skip analysis, found not supported arch"""'}, {}), "('skip analysis, found not supported arch')", False, 'import logging\n'), ((216, 40, 216, 73), 'os.path.join', 'os.path.join', ({(216, 53, 216, 62): 'directory', (216, 64, 216, 72): 'filename'}, {}), '(directory, filename)', False, 'import os\n'), ((217, 19, 217, 63), 're.match', 're.match', ({(217, 28, 217, 52): "('^' + exclude_directory)", (217, 54, 217, 62): 'filename'}, {}), "('^' + exclude_directory, filename)", False, 'import re\n'), ((233, 32, 233, 49), 'json.load', 'json.load', ({(233, 42, 233, 48): 'handle'}, {}), '(handle)', False, 'import json\n'), ((321, 23, 322, 36), 'os.getenv', 'os.getenv', ({(321, 33, 321, 59): '"""ANALYZE_BUILD_PARAMETERS"""', (322, 33, 322, 35): '""""""'}, {}), "('ANALYZE_BUILD_PARAMETERS', '')", False, 'import os\n'), ((546, 29, 548, 69), 'tempfile.mkstemp', 'tempfile.mkstemp', (), '', False, 'import tempfile\n'), ((549, 12, 549, 28), 'os.close', 'os.close', ({(549, 21, 549, 27): 'handle'}, {}), '(handle)', False, 'import os\n'), ((606, 16, 606, 36), 'os.makedirs', 'os.makedirs', ({(606, 28, 606, 35): 'ast_dir'}, {}), '(ast_dir)', False, 'import os\n'), ((635, 16, 635, 51), 'os.makedirs', 'os.makedirs', ({(635, 28, 635, 50): 'extern_defs_map_folder'}, {}), '(extern_defs_map_folder)', False, 'import os\n'), ((640, 17, 642, 58), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', (), '', False, 'import tempfile\n'), ((518, 30, 518, 40), 'os.uname', 'os.uname', ({}, {}), '()', False, 'import os\n'), ((600, 39, 600, 69), 'os.path.realpath', 'os.path.realpath', ({(600, 56, 600, 68): "opts['file']"}, {}), "(opts['file'])", False, 'import os\n'), ((668, 40, 668, 77), 'os.path.join', 'os.path.join', ({(668, 53, 668, 67): 'ctu_config.dir', (668, 69, 668, 76): 'triarch'}, {}), '(ctu_config.dir, triarch)', False, 'import os\n'), ((793, 13, 793, 38), 're.match', 're.match', ({(793, 22, 793, 32): '"""^[^-].+"""', (793, 34, 793, 37): 'arg'}, {}), "('^[^-].+', arg)", False, 'import re\n'), ((793, 43, 793, 63), 'libscanbuild.compilation.classify_source', 'classify_source', ({(793, 59, 793, 62): 'arg'}, {}), '(arg)', False, 'from libscanbuild.compilation import split_command, classify_source, compiler_language\n'), ((802, 13, 802, 36), 're.match', 're.match', ({(802, 22, 802, 30): '"""^-W.+"""', (802, 32, 802, 35): 'arg'}, {}), "('^-W.+', arg)", False, 'import re\n'), ((802, 45, 802, 71), 're.match', 're.match', ({(802, 54, 802, 65): '"""^-Wno-.+"""', (802, 67, 802, 70): 'arg'}, {}), "('^-Wno-.+', arg)", False, 'import re\n')]