Best Python code snippet using autotest_python
compiler.py
Source:compiler.py  
1#===----------------------------------------------------------------------===##2#3#                     The LLVM Compiler Infrastructure4#5# This file is dual licensed under the MIT and the University of Illinois Open6# Source Licenses. See LICENSE.TXT for details.7#8#===----------------------------------------------------------------------===##9import os10import lit.util11import libcxx.util12class CXXCompiler(object):13    CM_Default = 014    CM_PreProcess = 115    CM_Compile = 216    CM_Link = 317    def __init__(self, path, flags=None, compile_flags=None, link_flags=None,18                 use_ccache=False):19        self.path = path20        self.flags = list(flags or [])21        self.compile_flags = list(compile_flags or [])22        self.warning_flags = []23        self.link_flags = list(link_flags or [])24        self.use_ccache = use_ccache25        self.type = None26        self.version = None27        self._initTypeAndVersion()28    def _initTypeAndVersion(self):29        # Get compiler type and version30        macros = self.dumpMacros()31        if macros is None:32            return33        compiler_type = None34        major_ver = minor_ver = patchlevel = None35        if '__clang__' in macros.keys():36            compiler_type = 'clang'37            # Treat apple's llvm fork differently.38            if '__apple_build_version__' in macros.keys():39                compiler_type = 'apple-clang'40            major_ver = macros['__clang_major__']41            minor_ver = macros['__clang_minor__']42            patchlevel = macros['__clang_patchlevel__']43        elif '__GNUC__' in macros.keys():44            compiler_type = 'gcc'45            major_ver = macros['__GNUC__']46            minor_ver = macros['__GNUC_MINOR__']47            patchlevel = macros['__GNUC_PATCHLEVEL__']48        self.type = compiler_type49        self.version = (major_ver, minor_ver, patchlevel)50    def _basicCmd(self, source_files, out, mode=CM_Default, flags=[],51                  input_is_cxx=False,52                  enable_warnings=True, disable_ccache=False):53        cmd = []54        if self.use_ccache and not disable_ccache \55                and not mode == self.CM_Link \56                and not mode == self.CM_PreProcess:57            cmd += ['ccache']58        cmd += [self.path]59        if out is not None:60            cmd += ['-o', out]61        if input_is_cxx:62            cmd += ['-x', 'c++']63        if isinstance(source_files, list):64            cmd += source_files65        elif isinstance(source_files, str):66            cmd += [source_files]67        else:68            raise TypeError('source_files must be a string or list')69        if mode == self.CM_PreProcess:70            cmd += ['-E']71        elif mode == self.CM_Compile:72            cmd += ['-c']73        cmd += self.flags74        if mode != self.CM_Link:75            cmd += self.compile_flags76            if enable_warnings:77                cmd += self.warning_flags78        if mode != self.CM_PreProcess and mode != self.CM_Compile:79            cmd += self.link_flags80        cmd += flags81        return cmd82    def _getWarningFlags(self, enable_warnings=True):83        return self.warning_flags if enable_warnings else []84    def preprocessCmd(self, source_files, out=None, flags=[],85                      enable_warnings=True):86        return self._basicCmd(source_files, out, flags=flags,87                             mode=self.CM_PreProcess,88                             enable_warnings=enable_warnings,89                             input_is_cxx=True)90    def compileCmd(self, source_files, out=None, flags=[],91                   disable_ccache=False, enable_warnings=True):92        return self._basicCmd(source_files, out, flags=flags,93                             mode=self.CM_Compile,94                             input_is_cxx=True,95                             enable_warnings=enable_warnings,96                             disable_ccache=disable_ccache) + ['-c']97    def linkCmd(self, source_files, out=None, flags=[]):98        return self._basicCmd(source_files, out, mode=self.CM_Link)99    def compileLinkCmd(self, source_files, out=None, flags=[],100                       enable_warnings=True):101        return self._basicCmd(source_files, out, flags=flags,102                              enable_warnings=enable_warnings)103    def preprocess(self, source_files, out=None, flags=[], env=None, cwd=None):104        cmd = self.preprocessCmd(source_files, out, flags)105        out, err, rc = lit.util.executeCommand(cmd, env=env, cwd=cwd)106        return cmd, out, err, rc107    def compile(self, source_files, out=None, flags=[], env=None, cwd=None,108                disable_ccache=False, enable_warnings=True):109        cmd = self.compileCmd(source_files, out, flags,110                              disable_ccache=disable_ccache,111                              enable_warnings=enable_warnings)112        out, err, rc = lit.util.executeCommand(cmd, env=env, cwd=cwd)113        return cmd, out, err, rc114    def link(self, source_files, out=None, flags=[], env=None, cwd=None):115        cmd = self.linkCmd(source_files, out, flags)116        out, err, rc = lit.util.executeCommand(cmd, env=env, cwd=cwd)117        return cmd, out, err, rc118    def compileLink(self, source_files, out=None, flags=[], env=None,119                    cwd=None):120        cmd = self.compileLinkCmd(source_files, out, flags)121        out, err, rc = lit.util.executeCommand(cmd, env=env, cwd=cwd)122        return cmd, out, err, rc123    def compileLinkTwoSteps(self, source_file, out=None, object_file=None,124                            flags=[], env=None, cwd=None,125                            disable_ccache=False):126        if not isinstance(source_file, str):127            raise TypeError('This function only accepts a single input file')128        if object_file is None:129            # Create, use and delete a temporary object file if none is given.130            with_fn = lambda: libcxx.util.guardedTempFilename(suffix='.o')131        else:132            # Otherwise wrap the filename in a context manager function.133            with_fn = lambda: libcxx.util.nullContext(object_file)134        with with_fn() as object_file:135            cc_cmd, cc_stdout, cc_stderr, rc = self.compile(136                    source_file, object_file, flags=flags, env=env, cwd=cwd,137                    disable_ccache=disable_ccache)138            if rc != 0:139                return cc_cmd, cc_stdout, cc_stderr, rc140            link_cmd, link_stdout, link_stderr, rc = self.link(141                    object_file, out=out, flags=flags, env=env, cwd=cwd)142            return (cc_cmd + ['&&'] + link_cmd, cc_stdout + link_stdout,143                    cc_stderr + link_stderr, rc)144    def dumpMacros(self, source_files=None, flags=[], env=None, cwd=None):145        if source_files is None:146            source_files = os.devnull147        flags = ['-dM'] + flags148        cmd, out, err, rc = self.preprocess(source_files, flags=flags, env=env,149                                            cwd=cwd)150        if rc != 0:151            return None152        parsed_macros = {}153        lines = [l.strip() for l in out.split('\n') if l.strip()]154        for l in lines:155            assert l.startswith('#define ')156            l = l[len('#define '):]157            macro, _, value = l.partition(' ')158            parsed_macros[macro] = value159        return parsed_macros160    def getTriple(self):161        cmd = [self.path] + self.flags + ['-dumpmachine']162        return lit.util.capture(cmd).strip()163    def hasCompileFlag(self, flag):164        if isinstance(flag, list):165            flags = list(flag)166        else:167            flags = [flag]168        # Add -Werror to ensure that an unrecognized flag causes a non-zero169        # exit code. -Werror is supported on all known compiler types.170        if self.type is not None:171            flags += ['-Werror', '-fsyntax-only']172        cmd, out, err, rc = self.compile(os.devnull, out=os.devnull,173                                         flags=flags)174        return rc == 0175    def addCompileFlagIfSupported(self, flag):176        if isinstance(flag, list):177            flags = list(flag)178        else:179            flags = [flag]180        if self.hasCompileFlag(flags):181            self.compile_flags += flags182            return True183        else:184            return False185    def addWarningFlagIfSupported(self, flag):186        """187        addWarningFlagIfSupported - Add a warning flag if the compiler188        supports it. Unlike addCompileFlagIfSupported, this function detects189        when "-Wno-<warning>" flags are unsupported. If flag is a190        "-Wno-<warning>" GCC will not emit an unknown option diagnostic unless191        another error is triggered during compilation.192        """193        assert isinstance(flag, str)194        if not flag.startswith('-Wno-'):195            if self.hasCompileFlag(flag):196                self.warning_flags += [flag]197                return True198            return False199        flags = ['-Werror', flag]200        cmd = self.compileCmd('-', os.devnull, flags, enable_warnings=False)201        # Remove '-v' because it will cause the command line invocation202        # to be printed as part of the error output.203        # TODO(EricWF): Are there other flags we need to worry about?204        if '-v' in cmd:205            cmd.remove('-v')206        out, err, rc = lit.util.executeCommand(cmd, input='#error\n')207        assert rc != 0208        if flag in err:209            return False210        self.warning_flags += [flag]...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
