Best Python code snippet using lemoncheesecake
spi14ori.py
Source:spi14ori.py  
1# source-to-source compiler2from collections import OrderedDict3from spi import (4    Lexer,5    Parser,6    NodeVisitor,7    BuiltinTypeSymbol,8    VarSymbol,9    ProcedureSymbol10)11class ScopedSymbolTable(object):12    def __init__(self, scope_name, scope_level, enclosing_scope=None):13        self._symbols = OrderedDict()14        self.scope_name = scope_name15        self.scope_level = scope_level16        self.enclosing_scope = enclosing_scope17    def _init_builtins(self):18        self.insert(BuiltinTypeSymbol('INTEGER'))19        self.insert(BuiltinTypeSymbol('REAL'))20    def __str__(self):21        h1 = 'SCOPE (SCOPED SYMBOL TABLE)'22        lines = ['\n', h1, '=' * len(h1)]23        for header_name, header_value in (24            ('Scope name', self.scope_name),25            ('Scope level', self.scope_level),26            ('Enclosing scope',27             self.enclosing_scope.scope_name if self.enclosing_scope else None28            )29        ):30            lines.append('%-15s: %s' % (header_name, header_value))31        h2 = 'Scope (Scoped symbol table) contents'32        lines.extend([h2, '-' * len(h2)])33        lines.extend(34            ('%7s: %r' % (key, value))35            for key, value in self._symbols.items()36        )37        lines.append('\n')38        s = '\n'.join(lines)39        return s40    __repr__ = __str__41    def insert(self, symbol):42        self._symbols[symbol.name] = symbol43        # To output subscripts, we get symbols to store a reference44        # to their scope45        symbol.scope = self46    def lookup(self, name, current_scope_only=False):47        # 'symbol' is either an instance of the Symbol class or None48        symbol = self._symbols.get(name)49        if symbol is not None:50            return symbol51        if current_scope_only:52            return None53        # recursively go up the chain and lookup the name54        if self.enclosing_scope is not None:55            return self.enclosing_scope.lookup(name)56class SourceToSourceCompiler(NodeVisitor):57    def __init__(self):58        self.current_scope = None59        self.output = None60    def visit_Block(self, node):61        results = []62        for declaration in node.declarations:63            result = self.visit(declaration)64            results.append(result)65        results.append('\nbegin')66        result = self.visit(node.compound_statement)67        result = '   ' + result68        results.append(result)69        results.append('end')70        return '\n'.join(results)71    def visit_Program(self, node):72        program_name = node.name73        result_str = 'program %s0;\n' % program_name74        global_scope = ScopedSymbolTable(75            scope_name='global',76            scope_level=1,77            enclosing_scope=self.current_scope, # None78        )79        global_scope._init_builtins()80        self.current_scope = global_scope81        # visit subtree82        result_str += self.visit(node.block)83        result_str += '.'84        result_str += ' {END OF %s}' % program_name85        self.output = result_str86        self.current_scope = self.current_scope.enclosing_scope87    def visit_Compound(self, node):88        results = []89        for child in node.children:90            result = self.visit(child)91            if result is None:92                continue93            results.append(result)94        return '\n'.join(results)95    def visit_NoOp(self, node):96        pass97    def visit_BinOp(self, node):98        t1 = self.visit(node.left)99        t2 = self.visit(node.right)100        return '%s %s %s' % (t1, node.op.value, t2)101    def visit_ProcedureDecl(self, node):102        proc_name = node.proc_name103        proc_symbol = ProcedureSymbol(proc_name)104        self.current_scope.insert(proc_symbol)105        result_str = 'procedure %s%s' % (106            proc_name, self.current_scope.scope_level107        )108        # Scope for parameters and local variables109        procedure_scope = ScopedSymbolTable(110            scope_name=proc_name,111            scope_level=self.current_scope.scope_level + 1,112            enclosing_scope=self.current_scope113        )114        self.current_scope = procedure_scope115        if node.params:116            result_str += '('117        formal_params = []118        # Insert parameters into the procedure scope119        for param in node.params:120            param_type = self.current_scope.lookup(param.type_node.value)121            param_name = param.var_node.value122            var_symbol = VarSymbol(param_name, param_type)123            self.current_scope.insert(var_symbol)124            proc_symbol.params.append(var_symbol)125            scope_level = str(self.current_scope.scope_level)126            formal_params.append(127                '%s : %s' % (param_name + scope_level, param_type.name)128            )129        result_str += '; '.join(formal_params)130        if node.params:131            result_str += ')'132        result_str += ';'133        result_str += '\n'134        result_str += self.visit(node.block_node)135        result_str += '; {END OF %s}' % proc_name136        # indent procedure text137        result_str = '\n'.join('   ' + line for line in result_str.splitlines())138        self.current_scope = self.current_scope.enclosing_scope139        return result_str140    def visit_VarDecl(self, node):141        type_name = node.type_node.value142        type_symbol = self.current_scope.lookup(type_name)143        # We have all the information we need to create a variable symbol.144        # Create the symbol and insert it into the symbol table.145        var_name = node.var_node.value146        var_symbol = VarSymbol(var_name, type_symbol)147        # Signal an error if the table alrady has a symbol148        # with the same name149        if self.current_scope.lookup(var_name, current_scope_only=True):150            raise Exception(151                "Error: Duplicate identifier '%s' found" % var_name152            )153        self.current_scope.insert(var_symbol)154        scope_level = str(self.current_scope.scope_level)155        return '   var %s : %s;' % (var_name + scope_level , type_name)156    def visit_Assign(self, node):157        t2 = self.visit(node.right)158        t1 = self.visit(node.left)159        return '%s %s %s;' % (t1, ':=', t2)160    def visit_Var(self, node):161        var_name = node.value162        var_symbol = self.current_scope.lookup(var_name)163        if var_symbol is None:164            raise Exception(165                "Error: Symbol(identifier) not found '%s'" % var_name166            )167        scope_level = str(var_symbol.scope.scope_level)168        return '<%s:%s>' % (var_name + scope_level, var_symbol.type.name)169if __name__ == '__main__':170    import sys171    text = open(sys.argv[1], 'r').read()172    lexer = Lexer(text)173    parser = Parser(lexer)174    tree = parser.parse()175    source_compiler = SourceToSourceCompiler()176    source_compiler.visit(tree)...src2srccompiler.py
Source:src2srccompiler.py  
1# source-to-source compiler2from spi import (3    Lexer,4    Parser,5    NodeVisitor,6    BuiltinTypeSymbol,7    VarSymbol,8    ProcedureSymbol9)10class ScopedSymbolTable(object):11    def __init__(self, scope_name, scope_level, enclosing_scope=None):12        self._symbols = {}13        self.scope_name = scope_name14        self.scope_level = scope_level15        self.enclosing_scope = enclosing_scope16    def _init_builtins(self):17        self.insert(BuiltinTypeSymbol('INTEGER'))18        self.insert(BuiltinTypeSymbol('REAL'))19    def __str__(self):20        h1 = 'SCOPE (SCOPED SYMBOL TABLE)'21        lines = ['\n', h1, '=' * len(h1)]22        for header_name, header_value in (23            ('Scope name', self.scope_name),24            ('Scope level', self.scope_level),25            ('Enclosing scope',26             self.enclosing_scope.scope_name if self.enclosing_scope else None27            )28        ):29            lines.append('%-15s: %s' % (header_name, header_value))30        h2 = 'Scope (Scoped symbol table) contents'31        lines.extend([h2, '-' * len(h2)])32        lines.extend(33            ('%7s: %r' % (key, value))34            for key, value in self._symbols.items()35        )36        lines.append('\n')37        s = '\n'.join(lines)38        return s39    __repr__ = __str__40    def insert(self, symbol):41        self._symbols[symbol.name] = symbol42        # To output subscripts, we get symbols to store a reference43        # to their scope44        symbol.scope = self45    def lookup(self, name, current_scope_only=False):46        # 'symbol' is either an instance of the Symbol class or None47        symbol = self._symbols.get(name)48        if symbol is not None:49            return symbol50        if current_scope_only:51            return None52        # recursively go up the chain and lookup the name53        if self.enclosing_scope is not None:54            return self.enclosing_scope.lookup(name)55class SourceToSourceCompiler(NodeVisitor):56    def __init__(self):57        self.current_scope = None58        self.output = None59    def visit_Block(self, node):60        results = []61        for declaration in node.declarations:62            result = self.visit(declaration)63            results.append(result)64        results.append('\nbegin')65        result = self.visit(node.compound_statement)66        result = '   ' + result67        results.append(result)68        results.append('end')69        return '\n'.join(results)70    def visit_Program(self, node):71        program_name = node.name72        result_str = 'program %s0;\n' % program_name73        global_scope = ScopedSymbolTable(74            scope_name='global',75            scope_level=1,76            enclosing_scope=self.current_scope, # None77        )78        global_scope._init_builtins()79        self.current_scope = global_scope80        # visit subtree81        result_str += self.visit(node.block)82        result_str += '.'83        result_str += ' {END OF %s}' % program_name84        self.output = result_str85        self.current_scope = self.current_scope.enclosing_scope86    def visit_Compound(self, node):87        results = []88        for child in node.children:89            result = self.visit(child)90            if result is None:91                continue92            results.append(result)93        return '\n'.join(results)94    def visit_NoOp(self, node):95        pass96    def visit_BinOp(self, node):97        t1 = self.visit(node.left)98        t2 = self.visit(node.right)99        return '%s %s %s' % (t1, node.op.value, t2)100    def visit_ProcedureDecl(self, node):101        proc_name = node.proc_name102        proc_symbol = ProcedureSymbol(proc_name)103        self.current_scope.insert(proc_symbol)104        result_str = 'procedure %s%s' % (105            proc_name, self.current_scope.scope_level106        )107        # Scope for parameters and local variables108        procedure_scope = ScopedSymbolTable(109            scope_name=proc_name,110            scope_level=self.current_scope.scope_level + 1,111            enclosing_scope=self.current_scope112        )113        self.current_scope = procedure_scope114        if node.params:115            result_str += '('116        formal_params = []117        # Insert parameters into the procedure scope118        for param in node.params:119            param_type = self.current_scope.lookup(param.type_node.value)120            param_name = param.var_node.value121            var_symbol = VarSymbol(param_name, param_type)122            self.current_scope.insert(var_symbol)123            proc_symbol.params.append(var_symbol)124            scope_level = str(self.current_scope.scope_level)125            formal_params.append(126                '%s : %s' % (param_name + scope_level, param_type.name)127            )128        result_str += '; '.join(formal_params)129        if node.params:130            result_str += ')'131        result_str += ';'132        result_str += '\n'133        result_str += self.visit(node.block_node)134        result_str += '; {END OF %s}' % proc_name135        # indent procedure text136        result_str = '\n'.join('   ' + line for line in result_str.splitlines())137        self.current_scope = self.current_scope.enclosing_scope138        return result_str139    def visit_VarDecl(self, node):140        type_name = node.type_node.value141        type_symbol = self.current_scope.lookup(type_name)142        # We have all the information we need to create a variable symbol.143        # Create the symbol and insert it into the symbol table.144        var_name = node.var_node.value145        var_symbol = VarSymbol(var_name, type_symbol)146        # Signal an error if the table alrady has a symbol147        # with the same name148        if self.current_scope.lookup(var_name, current_scope_only=True):149            raise Exception(150                "Error: Duplicate identifier '%s' found" % var_name151            )152        self.current_scope.insert(var_symbol)153        scope_level = str(self.current_scope.scope_level)154        return '   var %s : %s;' % (var_name + scope_level , type_name)155    def visit_Assign(self, node):156        t2 = self.visit(node.right)157        t1 = self.visit(node.left)158        return '%s %s %s;' % (t1, ':=', t2)159    def visit_Var(self, node):160        var_name = node.value161        var_symbol = self.current_scope.lookup(var_name)162        if var_symbol is None:163            raise Exception(164                "Error: Symbol(identifier) not found '%s'" % var_name165            )166        scope_level = str(var_symbol.scope.scope_level)167        return '<%s:%s>' % (var_name + scope_level, var_symbol.type.name)168if __name__ == '__main__':169    import sys170    text = open(sys.argv[1], 'r').read()171    lexer = Lexer(text)172    parser = Parser(lexer)173    tree = parser.parse()174    source_compiler = SourceToSourceCompiler()175    source_compiler.visit(tree)...line-counter.py
Source:line-counter.py  
1import sys2import re3prog_lines = []4prog_count = 05prog_total = 06spec_lines = []7spec_count = 08spec_total = 09last_heading = ""10def print_counts(spec_count, prog_count):11    #print last_heading12    print(spec_count, "\t", prog_count, "\t", prog_count + spec_count)13    14def count(fname):15    global prog_total, spec_total, prog_count, spec_count, last_heading16    last_heading = "--- Beginning of " + fname + " ---"17    with open(fname, 'r') as fin:18        spec_context = False19        scope_level = 020        spec_level = 021        for line in fin:22            line = line.strip()23            if line == "" or line.startswith("//"):24                continue25            if line.startswith("/** {Spec} "):26                #print_counts(spec_count, prog_count)27                last_heading = line28                if spec_context:29                    spec_total += spec_count + prog_count30                else :31                    prog_total += prog_count32                    spec_total += spec_count33                prog_count, spec_count = 0, 034                spec_context = True35                scope_level = 136                continue37            if line.startswith("/**"):38                #print_counts(spec_count, prog_count)39                last_heading = line40                if spec_context:41                    spec_total += spec_count + prog_count42                else :43                    prog_total += prog_count44                    spec_total += spec_count45                prog_count, spec_count = 0, 046                spec_context = False47                scope_level = 048                continue49            spec_keywords = [50                "invariant", "requires", "ensures", "auto", "predicate", "function", "==>", "axiom", 51                "define", "split", "&&", "&*&", "||", "pure", "assert", "lemma", "forall", "exists", "ghost",52            ]53            if not spec_context and re.search("assert.*with\s\{", line):54                spec_context = True55                spec_level = scope_level56            scope_level = scope_level + line.count("{") - line.count("}")57            if spec_context or any(w in line for w in spec_keywords):58                #spec_lines.append(line)59                spec_count += 160            else:61                #prog_lines.append(line)62                prog_count += 163            if spec_context and scope_level <= spec_level:64                spec_context = False65    spec_total += spec_count66    prog_total += prog_count67    #print_counts(spec_count, prog_count)68    69for file in sys.argv[1:]:70    count(file)71last_heading = "--- End of File(s) ---"72print_counts(spec_total, prog_total)73#if len(sys.argv) > 2 and sys.argv[2] == "debug":74#    print "\nProg lines:"75#    for line in prog_lines:76#        print "  " + line77#78#    print "\n----------\n\nSpec lines:"79#    for line in spec_lines:...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!!
