Exemplo n.º 1
0
 def testLevel3(self):
     s1 = Scope.Scope()
     s2 = Scope.Scope(s1)
     s2['x'] = 2
     s3 = Scope.Scope(s2)
     self.assertEqual(s1['x'], None)
     self.assertEqual(s3['x'], 2)
Exemplo n.º 2
0
def emit_if(statement, function_name, old_scope):
    a = []
    # Copy old variables into new scope. If we define new variables in
    # this block, they die when the if ends
    if_scope = Scope.Scope(old_scope, "if", False)
    else_scope = Scope.Scope(old_scope, "else", False)

    # check how much stack space the if block takes
    # then how much stack space the else takes
    # return the maximum of the two
    else_clause = statement.iffalse is not None
    if else_clause:
        label_endif = util.reserve_label("%s_else" % function_name)
    else:
        label_endif = util.reserve_label("%s_skipif" % function_name)

    # We want to take the branch past the iftrue block if the condition
    # is *not* true. Therefore, we should invert the branch type, by passing
    # invert_sense=True. If it was 'zp' before, it is 'n' now.
    a += emit_cond(function_name, old_scope, statement.cond, label_endif, True)
    a += emit_block(statement.iftrue, function_name, if_scope)
    a += asm("%s" % label_endif)
    if else_clause:
        # If execution has reached this point,
        # the iftrue branch must have run.

        # Jump past the else clause
        label_endelse = util.reserve_label("%s_skipelse" % function_name)
        a += asm("BR %s" % label_endelse)
        a += emit_block(statement.iffalse, function_name, else_scope)
        a += asm("%s" % label_endelse)
    return a
Exemplo n.º 3
0
    def setUp(self):
        self.base = Scope.Scope()
        self.scope = Scope.Scope(self.base)

        self.base.assign('x1', 1)
        self.base['x2'] = 2
        self.scope.assign('y1', 11)
        self.scope['y2'] = 12
Exemplo n.º 4
0
 def compute(self, timeout):
     """Process the conversion."""
     Scope.compute(out_folder=self.outdir,
                   sink_file=self.sinkfile,
                   reaction_file=self.reacfile,
                   target=self.target,
                   minDepth=self.minDepth)
     self._check_output()
Exemplo n.º 5
0
 def testLevel3_2(self):
     s1 = Scope.Scope()
     s1['x'] = 2
     s2 = Scope.Scope(s1)
     s3 = Scope.Scope(s2)
     s3['x'] = 1
     self.assertEqual(s3.variables, {})
     self.assertEqual(s1['x'], 1)
     self.assertEqual(s3['x'], 1)
Exemplo n.º 6
0
	def testLocal(self):
		scope = Scope()

		self.player.beforescript.script = 'r = 1'
		self.player.p.beforescript.script = 'p  = 1'
		self.player.p.h1.beforescript.script = 'h1 = 1'
		self.player.p.h2.beforescript.script = 'h2 = 1'

		self.player.play(scope)

		self.assertEqual(sorted(scope.get_variables().keys()), ['__builtins__', 'r'])

		self.player.p.h2.afterscript.script = 'h2 = k'
		self.assertRaises(NameError, self.player.play)
Exemplo n.º 7
0
	def testExecuteScript(self):
		scope = Scope()

		self.scoped.script.script = 'i = 2'
		self.scoped.play(scope)

		script = Script('j = i')
		self.scoped.execute_script(script, scope)

		script = Script('j = k')
		self.assertRaises(NameError, lambda:self.scoped.execute_script(script, scope))

		scope = Scope()
		scope['k'] = 3
		self.scoped.execute_script(script, scope)
		self.assertEqual(scope['j'], 3)
Exemplo n.º 8
0
 def createBaseMatrix(self):     
     self.rootScope = Scope(-1)
     indentLevel(-1)
     self.rootScope.antiTranslator = translator.getBuiltInNames()
     self.rootScope.antiTranslator.update(translator.getKeywords())
     
     self.baseMatrix = []
     lastIndent = 0
     #print self.code
     for part in self.code.split('~'):
         for line in part.splitlines(1):
             thisLine = Line(line)
             
             if thisLine.line != '': 
                 thisLine.setDeltaIndent(lastIndent)
                 lastIndent = thisLine.indent             
                 self.baseMatrix.append(thisLine) 
Exemplo n.º 9
0
	def testConstructor(self):
		scope = Scope()
		script = Script('i = 2')
		script.execute(scope)
		script.script = 'j = i'
		script.execute(scope)

		script = Script('i = k')
		self.assertRaises(NameError, script.execute)
Exemplo n.º 10
0
	def testBefore(self):
		self.player.beforescript.script = 'i = 2'
		self.player.before()

		self.player.beforescript.script = 'i = 2 ; j = k'
		self.assertRaises(NameError, self.player.before)

		scope = Scope()
		scope['k'] = 2
		self.player.before(scope)
Exemplo n.º 11
0
def get_globals(ast):
    global_scope = Scope.GlobalScope()
    uses_globals = False
    for node in ast.ext:
        if type(node) == c_ast.Decl:
            global_scope.define_variable(node.name, node.type, node.init)
            uses_globals = True
    global_scope.pick_locations()
    Scope.global_scope = global_scope
    # represents whether the program uses any global variables
    return uses_globals
Exemplo n.º 12
0
    def testBase(self):
        self.assertEqual(self.life.eval('2'), 2)
        self.life.execute('i=2;j=3;k=5')
        # Now:
        # i = 2, j = 3, k = 5
        self.assertEqual(self.life['i'], 2)

        scope = Scope.Scope()
        scope['x'] = 77
        scope['j'] = 88
        self.life.push(scope)
        # Now:
        # i = 2, j = 3, k = 5
        # x = 77, j = 88
        self.assertEqual(self.life['x'], 77)
        self.assertEqual(self.life.eval('x'), 77)
        self.assertEqual(self.life['i'], 2)
        self.assertEqual(self.life['j'], 88)
        self.life.execute('i=100;j=100')
        # Now:
        # i = 100, j = 3, k = 5
        # x = 77, j = 100
        self.life.pop()
        # Now:
        # i = 100, j = 3, k = 5
        self.assertEqual(self.life['x'], None)
        self.assertEqual(self.life.eval('x'), None)
        self.assertEqual(self.life['i'], 100)
        self.assertEqual(self.life['j'], 3)
        self.assertEqual(self.life['k'], 5)

        s1 = Scope.Scope()
        s1['x'] = 2
        s2 = Scope.Scope()
        s2['y'] = 3
        self.life.push(s1)
        self.life.push(s2)
        self.life['x'] = 3
        self.life['z'] = 5
        self.assertEqual(s1['x'], 3)
        self.assertEqual(s2['z'], 5)
Exemplo n.º 13
0
	def testBasic(self):
		self.script.execute()

		self.script.script = 'i = 2'
		self.script.execute()

		# script has no local variables
		self.script.script = 'j = i'
		self.assertRaises(NameError, self.script.execute)

		scope = Scope()
		scope['k'] = 3
		self.script.script = 'i = k; assert i == 3'
		self.script.execute(scope)

		self.script.script = 'j = i'
		self.assertRaises(NameError, self.script.execute)

		scope = Scope()
		self.script.script = 'j = i'
		self.assertRaises(NameError, lambda:self.script.execute(scope))
Exemplo n.º 14
0
	def testBasic(self):
		scope = Scope()

		self.player.play(scope)

		self.player.beforescript.script = 'i = 2'
		self.player.afterscript.script = 'i = i'
		self.player.play(scope)

		self.player.p.beforescript.script = 'j = i'
		self.player.play(scope)

		self.assertEqual(scope['i'], 2)

		self.player.afterscript.script = 'i = j'
		self.assertRaises(NameError, self.player.play)
Exemplo n.º 15
0
def emit_all(ast):
    program = []
    uses_globals = get_globals(ast)
    program += program_begin(uses_globals)
    get_all_prototypes(ast)
    functions = []
    for node in ast.ext:
        typ = type(node)
        if typ == c_ast.FuncDef:
            # print(node)
            name = node.decl.name
            func_typ = node.decl.type
            args = []
            if node.decl.type.args is not None:
                args = [arg for arg in node.decl.type.args.params]
            scope = Scope.Scope(None, "function", False)
            scope._function_name = name
            if has_ret_value_slot(name):
                first_arg_offset = 3
            else:
                first_arg_offset = 2
            for i, arg in enumerate(args):
                location = first_arg_offset + i
                scope.define_variable(arg.name, arg.type.type, None, location)
            # generate code for body to find out
            # how much stack space we need
            body = emit_block(node.body, name, scope)
            frame_size = scope.get_frame_size()
            ret_value_slot = has_ret_value_slot(name)
            func = []
            func += function_prologue(name, func_typ, frame_size,
                                      ret_value_slot)
            func += body
            func += function_epilogue(name, frame_size)

            # move $DEFER statments to end
            func = process_deferrals(func)

            functions.append(func)
    for func in functions:
        program += func
    program += program_end(uses_globals)
    return program
Exemplo n.º 16
0
	def testExecuteChild(self):
		scope = Scope()
		self.scoped.script.script = 'i = 2'
		script = Script('j = 3')
		self.scoped.execute_child(script, scope)
		self.assertEquals(scope.get_names(), [])

		script = Script('j = k')
		self.assertRaises(NameError, lambda:self.scoped.execute_script(script))

		scope = Scope()
		scope['x'] = 11
		self.scoped.execute_child(Script('j = x; x = 22'), scope)
		self.assertEquals(scope.get_names(), ['x'])
		self.assertEquals(scope['x'], 22)

		self.assertRaises(NameError, lambda:self.scoped.execute_child(Script('j = k'), scope))
Exemplo n.º 17
0
def emit_loop(function_name, old_scope, init, cond, body, next_, \
        loop_type, check_cond_first_loop):
    # Loops are structured like this
    # Init code (optional)
    # Jump to start of condition test (optional)
    #  Body of loop
    #  Statement executed every time the loop runs
    #  Condition test
    # Branch back to top if condition still true
    statement = None  # don't use statment unintentionally
    a = []
    # Copy old variables into new scope. If we define new variables in
    # this block, they die when the if ends
    label_prefix = "%s_%s" % (function_name, loop_type)
    scope = Scope.Scope(old_scope, loop_type, True, "%s_break" % label_prefix)
    if init is not None:
        # start by initializing the loop variable
        a += emit_statement(init, function_name, scope)
    begin_label = util.reserve_label("%s_begin" % label_prefix)
    cond_label = util.reserve_label("%s_cond" % label_prefix)

    # The condition is at the bottom of the loop, so if we're running a for
    # or while loop, jump down to that condition.
    if check_cond_first_loop:
        a += asm("BR %s" % cond_label)
    a += asm("%s" % begin_label)
    a += emit_block(body, function_name, scope)
    if next_ is not None:
        a += emit_statement(next_, function_name, scope)
    if check_cond_first_loop:
        a += asm("%s" % cond_label)
    a += emit_cond(function_name, scope, cond, begin_label, invert_sense=False)
    if scope.break_prefix_used:
        # there was a break within the loop, we need to provide a label for it
        a += asm("%s" % scope.get_break_label())
    return a
Exemplo n.º 18
0
def gameplay(time_to_win=60,
             hp=5,
             weapon_1_time=2,
             weapon_2_time=10,
             level_of_difficulty=2):
    global weapon, launch_time, the_current_time, time_of_1_weapon, time_of_2_weapon, \
        count_hp, weapon_1_t, weapon_2_t, hearts, scope_weapon, screen
    pause_flag = False
    hearts = Hearts(hp)
    weapon_1_t = weapon_1_time
    weapon_2_t = weapon_2_time
    count_hp = hp
    secret = Secret()
    launch_time = new_time()
    all_sprites = pg.sprite.Group()
    cursor_sprite = pg.sprite.Group()
    laptops = return_laptop_sprite_group()
    cursor = Scope(cursor_sprite)
    lower_fon = return_lower_fon()
    #
    scope_weapon = pg.sprite.Sprite()
    scope_weapon.image = load_image("scope_weapon.png")
    scope_weapon.image = pg.transform.scale(scope_weapon.image, (50, 50))
    scope_weapon.rect = scope_weapon.image.get_rect()
    lower_fon.add(scope_weapon)
    scope_weapon.rect.x = 96
    scope_weapon.rect.y = 620
    #
    bot_interaction_flag = False
    background_fon = Fon()
    rivals = []
    esc = PauseButton(740, 740)
    opponent_1, opponent_2, opponent_3 = Enemy(all_sprites, level_of_difficulty, 50, 300), \
                                         Enemy(all_sprites, level_of_difficulty, 300, 300), \
                                         Enemy(all_sprites, level_of_difficulty, 550, 300)
    rivals.append(opponent_1)
    rivals.append(opponent_2)
    rivals.append(opponent_3)
    times = clock.tick() / FPS
    the_current_time = new_time() - launch_time

    while True:
        for event in pg.event.get():
            try:
                if not bot_interaction_flag:
                    n = event
                    bot_interaction_flag = True

                elif event.type == pg.QUIT:
                    pg.quit()
                    sys.exit()
                elif event.type == 768:
                    if event.unicode == '':
                        if not pause_flag:
                            pause_flag = True
                            pause_time = the_current_time

                        else:
                            pause_flag = False
                            launch_time += the_current_time - pause_time

                elif event.type == pg.KEYUP and int(
                        event.unicode) != weapon and not pause_flag:
                    if event.unicode == '1':
                        scope_weapon.rect.x = 96
                        scope_weapon.rect.y = 620
                        weapon = 1
                    elif event.unicode == '2':
                        scope_weapon.rect.x = 100
                        scope_weapon.rect.y = 730
                        weapon = 2

                elif event.type == pg.MOUSEMOTION:
                    if event.pos[1] >= 600:
                        cursor.change_image('cursor.png')
                    else:
                        cursor.change_image('scope.png')
                    cursor.moving_cursor(event.pos)
                elif event.type == pg.MOUSEBUTTONDOWN and not pause_flag:
                    if event.pos[1] < 600:
                        if weapon == 1:
                            if (int(weapon_1_t - the_current_time +
                                    time_of_1_weapon)
                                ) <= 0 and event.pos[1] < 300:
                                time_of_1_weapon = new_time() - launch_time
                                all_sprites.update(event, weapon=1)
                        else:
                            if (int(weapon_2_t - the_current_time +
                                    time_of_2_weapon)) <= 0:
                                time_of_2_weapon = new_time() - launch_time
                                all_sprites.update(event, weapon=2)
                    if event.pos[0] >= 745 and event.pos[1] >= 610 and (
                            event.pos[0] <= 777 and event.pos[1] <= 652):
                        hearts.add_hp()
                    else:
                        if event.pos[0] <= 170 and event.pos[1] < 700:
                            scope_weapon.rect.x = 96
                            scope_weapon.rect.y = 620
                            weapon = 1
                        elif event.pos[0] <= 170 and event.pos[1] >= 700:
                            scope_weapon.rect.x = 100
                            scope_weapon.rect.y = 730
                            weapon = 2

            except:
                pass
        secret.draw()
        times = clock.tick() / FPS
        if not pause_flag and times > 0:
            for i in rivals:
                i.add_time(times)
        background_fon.draw_1_fon()
        all_sprites.draw(screen)
        background_fon.draw_2_fon()
        laptops.draw(screen)
        lower_fon.draw(screen)
        the_current_time = new_time() - launch_time
        if not pause_flag:
            draw_time_to_win(int(time_to_win - the_current_time))
            draw_time_of_restarting_weapons(
                int(weapon_1_t - the_current_time + time_of_1_weapon),
                int(weapon_2_t - the_current_time + time_of_2_weapon))
        else:
            draw_time_to_win(int(time_to_win - pause_time))
            draw_time_of_restarting_weapons(
                int(weapon_1_t - pause_time + time_of_1_weapon),
                int(weapon_2_t - pause_time + time_of_2_weapon))

        hearts.draw_hearts()
        esc.draw()
        if pause_flag:
            esc.draw_pause()
        if pg.mouse.get_focused():
            pg.mouse.set_visible(False)
            cursor_sprite.draw(screen)
        else:
            pg.mouse.set_visible(True)
        pg.display.flip()
        clock.tick(FPS)
        if time_to_win - the_current_time < 0 and not pause_flag:
            # возвращаем победу
            pg.mouse.set_visible(True)
            return win.welcome_window(True)
        elif count_hp <= 0:
            # возвращаем порожение
            pg.mouse.set_visible(True)
            return win.welcome_window(False)
Exemplo n.º 19
0
class Line(object):

    def updateAllTranslators(self,word, value):

        if self.nextParent:
            scope = self.scope.parent
        else:
            scope = self.scope
         
        if word == value:
            translator = scope.antiTranslator
        else:
            translator = scope.translator
             
        translator[word] = value
        self.allTranslators[word] = value
        
    def updateTranslator(self):
        '''replace all names in this line by the names in the scope'''
        #return only the line of code
        preservenext = False
        loadTranslator = False
        self.nextParent = False
        self.waitForQuote = False
        self.surpresParentheses = False
        self.parentheses = 0
        lastword = ''
        replaceNextBy = ''
        #this should not be done for each line but once, maybe per scopechange?
        self.allTranslators = self.scope.getAllTranslators()
        #print self.allTranslators.keys() 
        self.skel = []   
        pivot = 0         
        for word in re.findall(r"[\w]+", self.line):
            #append symbols to skeleton
            for bone in self.line[pivot:self.line.find(word,pivot)]:
                if not bone in [' ','\t','\n']:
                    self.skel.append(bone)
#                 if bone in ['"']:
#                     if not self.waitForQuote:
#                         indentLevel(self.indent + self.parentheses + 1)
#                         self.scope = Scope(self.indent + self.parentheses + 1)
#                     else:
#                         indentLevel(self.indent + self.parentheses)
#                         self.scope = getCurrentScope()        
#                     self.waitForQuote = not self.waitForQuote
                if not self.surpresParentheses:
                    if bone in ['(','[','{']:
                        self.parentheses +=1
                        indentLevel(self.indent + self.parentheses)
                        self.scope = Scope(self.indent + self.parentheses)
                    if bone in [')',']','}']:
                        self.parentheses -=1
                        indentLevel(self.indent + self.parentheses)
                        self.scope = getCurrentScope()
                pivot +=1
            pivot += len(word)
            #=======================
            
            if replaceNextBy != '':
                if not word in self.scope.translator.keys():
                    self.updateAllTranslators(word, replaceNextBy)
                replaceNextBy = ''
            if word in translator.getKeywords().keys():
                preservenext = False
            if word in ["from", "with", "import"]:
                if not preservenext:
                    preservenext = True
                    loadTranslator = True
            if word == "as":
                replaceNextBy = lastword
            if word in ['def', 'class']:
                self.nextParent = True
                self.surpresParentheses = True
            if preservenext:
                if not word in self.allTranslators.keys():
                    self.updateAllTranslators(word, word)
                    if loadTranslator:
                        try:
                            moduleDict = translator.createModuleDict(word)
                            self.scope.antiTranslator.update(moduleDict)
                            self.allTranslators.update(moduleDict)
                        except:
                            pass
                        loadTranslator = False
            else:
                if not word in self.allTranslators.keys():
                    try:
                        if re.match(r"const[0-9]{4}", word):
                            self.updateAllTranslators(word, word)
                        else:
                            iets = float(word)
                            self.updateAllTranslators(word, word)
                    except:
                        if self.nextParent:
                            #! actually methods, classes and vars should have independant counters
                            self.scope.methods[word] = self.scope
                            self.updateAllTranslators(word, 'meth' + ('00000' + str(self.scope.parent.varCount))[-5:])
                            self.scope.parent.varCount += 1
                            self.nextParent = False
                        else:
                            if self.parentheses > 0 and self.line[pivot:].strip()[0] == '=':
                                #It's not correct to add this word to the antitranslater of the current scope
                                #let try to create a new scope for every ( and [ and switch back to it's parent after ] or )
                                methodScope = self.scope.parent.getScopeByMethode(self.scope.parent.lastword)
                                try:
                                    self.updateAllTranslators(word,methodScope.getScopeTranslators()[word])
                                except:
                                    self.updateAllTranslators(word,word)
                            else:
                                self.updateAllTranslators(word, 'name' + ('00000' + str(self.scope.varCount))[-5:])
                                self.scope.varCount += 1
            lastword = word
            self.scope.lastword = word
            #append translated word to skeleton
            if word in self.scope.getScopeTranslators().keys():
                self.skel.append(self.scope.getScopeTranslators()[word])
            else:
                self.skel.append(word)
        #append trailing symbols to skeleton
        for bone in self.line[pivot:]:
            if not bone in [' ','\t','\n']:
                self.skel.append(bone)
            pivot +=1

    
    def replaceStringLiterals(self):    
                    
        toReturn = ''
        for quote in ['"""',"'''",'"',"'"]:
            quoteCount = 0
            for part in self.line.split(quote):
                if quoteCount % 2 == 0:
                    toReturn += part 
                else:
                    if (len(part) == 9 and re.match(r"const[0-9]{4}", part)):
                        toReturn += '"' + part + '"'
                    else:    
                        if part in self.scope.translator.keys():
                            toReturn +=  self.scope.translator[part] 
                        else:
                            if len(part) == 1 or is_number(part):
                                self.scope.antiTranslator[part] = part
                                toReturn += '"' + part +'"'
                            else:
                                self.scope.constCount += 1
                                constname = '"const' + ('0000' + str(self.scope.constCount))[-4:] + '"'
                                self.scope.translator[part] = constname 
                                toReturn += constname
                quoteCount += 1
            self.line = toReturn
            toReturn = ''
            
    
    def updateOrCreateScope(self):
        indentLevel(self.indent)
        if self.line[0:self.line.find(' ')] in ['def', 'class']:
            self.scope = Scope(self.indent)
        else:
            self.scope = getCurrentScope()
    
    def removeComment(self):
        pos = self.line.find('#')
        if pos >= 0:
            self.line = self.line[0:pos]

    def setDeltaIndent(self, lastIndent):
        self.deltaIndent = self.indent - lastIndent     

    
    def trailingTabsToSpace(self):
        try:
            while self.line[0] in [' ', '\t']:
                if self.line[0] == '\t':
                    self.line = self.line [1:]
                else:
                    self.line = self.line [4:]
                self.indent += 1
        except IndexError:
            pass

    def __init__(self, line):
        collon = line.find(':')
        self.lineNumber = int(line[0:collon])
        self.line = line[collon + 1:]
        self.indent = 0 
        self.deltaIndent = 0
        self.removeComment()
        self.trailingTabsToSpace()
        self.line = self.line.strip()
        self.allTranslators = {}
        
        if self.line != '':
            self.updateOrCreateScope()
            self.replaceStringLiterals()
            self.updateTranslator()
            
            for key in self.scope.getScopeTranslators():
                self.line = re.sub(r'\b%s\b' % key, ' ' + self.allTranslators[key] + ' ', self.line)
            lenLine = len(self.line)
            self.line = self.line.replace('  ',' ')
            while len(self.line) < lenLine:
                lenLine = len(self.line)
                self.line = self.line.replace('  ',' ')
            for char in ':,.(){}[]+-*/&|%!=':
                self.line = self.line.replace(' ' + char, char)
                self.line = self.line.replace(char + ' ', char)
            self.line = self.line.strip()
Exemplo n.º 20
0
class Line(object):
    def updateAllTranslators(self, word, value):

        if self.nextParent:
            scope = self.scope.parent
        else:
            scope = self.scope

        if word == value:
            translator = scope.antiTranslator
        else:
            translator = scope.translator

        translator[word] = value
        self.allTranslators[word] = value

    def updateTranslator(self):
        '''replace all names in this line by the names in the scope'''
        #return only the line of code
        preservenext = False
        loadTranslator = False
        self.nextParent = False
        self.waitForQuote = False
        self.surpresParentheses = False
        self.parentheses = 0
        lastword = ''
        replaceNextBy = ''
        #this should not be done for each line but once, maybe per scopechange?
        self.allTranslators = self.scope.getAllTranslators()
        #print self.allTranslators.keys()
        self.skel = []
        pivot = 0
        for word in re.findall(r"[\w]+", self.line):
            #append symbols to skeleton
            for bone in self.line[pivot:self.line.find(word, pivot)]:
                if not bone in [' ', '\t', '\n']:
                    self.skel.append(bone)
#                 if bone in ['"']:
#                     if not self.waitForQuote:
#                         indentLevel(self.indent + self.parentheses + 1)
#                         self.scope = Scope(self.indent + self.parentheses + 1)
#                     else:
#                         indentLevel(self.indent + self.parentheses)
#                         self.scope = getCurrentScope()
#                     self.waitForQuote = not self.waitForQuote
                if not self.surpresParentheses:
                    if bone in ['(', '[', '{']:
                        self.parentheses += 1
                        indentLevel(self.indent + self.parentheses)
                        self.scope = Scope(self.indent + self.parentheses)
                    if bone in [')', ']', '}']:
                        self.parentheses -= 1
                        indentLevel(self.indent + self.parentheses)
                        self.scope = getCurrentScope()
                pivot += 1
            pivot += len(word)
            #=======================

            if replaceNextBy != '':
                if not word in self.scope.translator.keys():
                    self.updateAllTranslators(word, replaceNextBy)
                replaceNextBy = ''
            if word in translator.getKeywords().keys():
                preservenext = False
            if word in ["from", "with", "import"]:
                if not preservenext:
                    preservenext = True
                    loadTranslator = True
            if word == "as":
                replaceNextBy = lastword
            if word in ['def', 'class']:
                self.nextParent = True
                self.surpresParentheses = True
            if preservenext:
                if not word in self.allTranslators.keys():
                    self.updateAllTranslators(word, word)
                    if loadTranslator:
                        try:
                            moduleDict = translator.createModuleDict(word)
                            self.scope.antiTranslator.update(moduleDict)
                            self.allTranslators.update(moduleDict)
                        except:
                            pass
                        loadTranslator = False
            else:
                if not word in self.allTranslators.keys():
                    try:
                        if re.match(r"const[0-9]{4}", word):
                            self.updateAllTranslators(word, word)
                        else:
                            iets = float(word)
                            self.updateAllTranslators(word, word)
                    except:
                        if self.nextParent:
                            #! actually methods, classes and vars should have independant counters
                            self.scope.methods[word] = self.scope
                            self.updateAllTranslators(
                                word, 'meth' +
                                ('00000' +
                                 str(self.scope.parent.varCount))[-5:])
                            self.scope.parent.varCount += 1
                            self.nextParent = False
                        else:
                            if self.parentheses > 0 and self.line[
                                    pivot:].strip()[0] == '=':
                                #It's not correct to add this word to the antitranslater of the current scope
                                #let try to create a new scope for every ( and [ and switch back to it's parent after ] or )
                                methodScope = self.scope.parent.getScopeByMethode(
                                    self.scope.parent.lastword)
                                try:
                                    self.updateAllTranslators(
                                        word,
                                        methodScope.getScopeTranslators()
                                        [word])
                                except:
                                    self.updateAllTranslators(word, word)
                            else:
                                self.updateAllTranslators(
                                    word, 'name' +
                                    ('00000' + str(self.scope.varCount))[-5:])
                                self.scope.varCount += 1
            lastword = word
            self.scope.lastword = word
            #append translated word to skeleton
            if word in self.scope.getScopeTranslators().keys():
                self.skel.append(self.scope.getScopeTranslators()[word])
            else:
                self.skel.append(word)
        #append trailing symbols to skeleton
        for bone in self.line[pivot:]:
            if not bone in [' ', '\t', '\n']:
                self.skel.append(bone)
            pivot += 1

    def replaceStringLiterals(self):

        toReturn = ''
        for quote in ['"""', "'''", '"', "'"]:
            quoteCount = 0
            for part in self.line.split(quote):
                if quoteCount % 2 == 0:
                    toReturn += part
                else:
                    if (len(part) == 9 and re.match(r"const[0-9]{4}", part)):
                        toReturn += '"' + part + '"'
                    else:
                        if part in self.scope.translator.keys():
                            toReturn += self.scope.translator[part]
                        else:
                            if len(part) == 1 or is_number(part):
                                self.scope.antiTranslator[part] = part
                                toReturn += '"' + part + '"'
                            else:
                                self.scope.constCount += 1
                                constname = '"const' + ('0000' + str(
                                    self.scope.constCount))[-4:] + '"'
                                self.scope.translator[part] = constname
                                toReturn += constname
                quoteCount += 1
            self.line = toReturn
            toReturn = ''

    def updateOrCreateScope(self):
        indentLevel(self.indent)
        if self.line[0:self.line.find(' ')] in ['def', 'class']:
            self.scope = Scope(self.indent)
        else:
            self.scope = getCurrentScope()

    def removeComment(self):
        pos = self.line.find('#')
        if pos >= 0:
            self.line = self.line[0:pos]

    def setDeltaIndent(self, lastIndent):
        self.deltaIndent = self.indent - lastIndent

    def trailingTabsToSpace(self):
        try:
            while self.line[0] in [' ', '\t']:
                if self.line[0] == '\t':
                    self.line = self.line[1:]
                else:
                    self.line = self.line[4:]
                self.indent += 1
        except IndexError:
            pass

    def __init__(self, line):
        collon = line.find(':')
        self.lineNumber = int(line[0:collon])
        self.line = line[collon + 1:]
        self.indent = 0
        self.deltaIndent = 0
        self.removeComment()
        self.trailingTabsToSpace()
        self.line = self.line.strip()
        self.allTranslators = {}

        if self.line != '':
            self.updateOrCreateScope()
            self.replaceStringLiterals()
            self.updateTranslator()

            for key in self.scope.getScopeTranslators():
                self.line = re.sub(r'\b%s\b' % key,
                                   ' ' + self.allTranslators[key] + ' ',
                                   self.line)
            lenLine = len(self.line)
            self.line = self.line.replace('  ', ' ')
            while len(self.line) < lenLine:
                lenLine = len(self.line)
                self.line = self.line.replace('  ', ' ')
            for char in ':,.(){}[]+-*/&|%!=':
                self.line = self.line.replace(' ' + char, char)
                self.line = self.line.replace(char + ' ', char)
            self.line = self.line.strip()
Exemplo n.º 21
0
 def updateOrCreateScope(self):
     indentLevel(self.indent)
     if self.line[0:self.line.find(' ')] in ['def', 'class']:
         self.scope = Scope(self.indent)
     else:
         self.scope = getCurrentScope()
Exemplo n.º 22
0
 def updateOrCreateScope(self):
     indentLevel(self.indent)
     if self.line[0:self.line.find(' ')] in ['def', 'class']:
         self.scope = Scope(self.indent)
     else:
         self.scope = getCurrentScope()
Exemplo n.º 23
0
	def play(self, base = None):
		if base == None:
			base = Scope()
		self.script.execute(base)
		Player.play(self, base)
Exemplo n.º 24
0
 def setUp(self):
     self.life = Scope.Life()
Exemplo n.º 25
0
    def updateTranslator(self):
        '''replace all names in this line by the names in the scope'''
        #return only the line of code
        preservenext = False
        loadTranslator = False
        self.nextParent = False
        self.waitForQuote = False
        self.surpresParentheses = False
        self.parentheses = 0
        lastword = ''
        replaceNextBy = ''
        #this should not be done for each line but once, maybe per scopechange?
        self.allTranslators = self.scope.getAllTranslators()
        #print self.allTranslators.keys()
        self.skel = []
        pivot = 0
        for word in re.findall(r"[\w]+", self.line):
            #append symbols to skeleton
            for bone in self.line[pivot:self.line.find(word, pivot)]:
                if not bone in [' ', '\t', '\n']:
                    self.skel.append(bone)
#                 if bone in ['"']:
#                     if not self.waitForQuote:
#                         indentLevel(self.indent + self.parentheses + 1)
#                         self.scope = Scope(self.indent + self.parentheses + 1)
#                     else:
#                         indentLevel(self.indent + self.parentheses)
#                         self.scope = getCurrentScope()
#                     self.waitForQuote = not self.waitForQuote
                if not self.surpresParentheses:
                    if bone in ['(', '[', '{']:
                        self.parentheses += 1
                        indentLevel(self.indent + self.parentheses)
                        self.scope = Scope(self.indent + self.parentheses)
                    if bone in [')', ']', '}']:
                        self.parentheses -= 1
                        indentLevel(self.indent + self.parentheses)
                        self.scope = getCurrentScope()
                pivot += 1
            pivot += len(word)
            #=======================

            if replaceNextBy != '':
                if not word in self.scope.translator.keys():
                    self.updateAllTranslators(word, replaceNextBy)
                replaceNextBy = ''
            if word in translator.getKeywords().keys():
                preservenext = False
            if word in ["from", "with", "import"]:
                if not preservenext:
                    preservenext = True
                    loadTranslator = True
            if word == "as":
                replaceNextBy = lastword
            if word in ['def', 'class']:
                self.nextParent = True
                self.surpresParentheses = True
            if preservenext:
                if not word in self.allTranslators.keys():
                    self.updateAllTranslators(word, word)
                    if loadTranslator:
                        try:
                            moduleDict = translator.createModuleDict(word)
                            self.scope.antiTranslator.update(moduleDict)
                            self.allTranslators.update(moduleDict)
                        except:
                            pass
                        loadTranslator = False
            else:
                if not word in self.allTranslators.keys():
                    try:
                        if re.match(r"const[0-9]{4}", word):
                            self.updateAllTranslators(word, word)
                        else:
                            iets = float(word)
                            self.updateAllTranslators(word, word)
                    except:
                        if self.nextParent:
                            #! actually methods, classes and vars should have independant counters
                            self.scope.methods[word] = self.scope
                            self.updateAllTranslators(
                                word, 'meth' +
                                ('00000' +
                                 str(self.scope.parent.varCount))[-5:])
                            self.scope.parent.varCount += 1
                            self.nextParent = False
                        else:
                            if self.parentheses > 0 and self.line[
                                    pivot:].strip()[0] == '=':
                                #It's not correct to add this word to the antitranslater of the current scope
                                #let try to create a new scope for every ( and [ and switch back to it's parent after ] or )
                                methodScope = self.scope.parent.getScopeByMethode(
                                    self.scope.parent.lastword)
                                try:
                                    self.updateAllTranslators(
                                        word,
                                        methodScope.getScopeTranslators()
                                        [word])
                                except:
                                    self.updateAllTranslators(word, word)
                            else:
                                self.updateAllTranslators(
                                    word, 'name' +
                                    ('00000' + str(self.scope.varCount))[-5:])
                                self.scope.varCount += 1
            lastword = word
            self.scope.lastword = word
            #append translated word to skeleton
            if word in self.scope.getScopeTranslators().keys():
                self.skel.append(self.scope.getScopeTranslators()[word])
            else:
                self.skel.append(word)
        #append trailing symbols to skeleton
        for bone in self.line[pivot:]:
            if not bone in [' ', '\t', '\n']:
                self.skel.append(bone)
            pivot += 1
Exemplo n.º 26
0
    def updateTranslator(self):
        '''replace all names in this line by the names in the scope'''
        #return only the line of code
        preservenext = False
        loadTranslator = False
        self.nextParent = False
        self.waitForQuote = False
        self.surpresParentheses = False
        self.parentheses = 0
        lastword = ''
        replaceNextBy = ''
        #this should not be done for each line but once, maybe per scopechange?
        self.allTranslators = self.scope.getAllTranslators()
        #print self.allTranslators.keys() 
        self.skel = []   
        pivot = 0         
        for word in re.findall(r"[\w]+", self.line):
            #append symbols to skeleton
            for bone in self.line[pivot:self.line.find(word,pivot)]:
                if not bone in [' ','\t','\n']:
                    self.skel.append(bone)
#                 if bone in ['"']:
#                     if not self.waitForQuote:
#                         indentLevel(self.indent + self.parentheses + 1)
#                         self.scope = Scope(self.indent + self.parentheses + 1)
#                     else:
#                         indentLevel(self.indent + self.parentheses)
#                         self.scope = getCurrentScope()        
#                     self.waitForQuote = not self.waitForQuote
                if not self.surpresParentheses:
                    if bone in ['(','[','{']:
                        self.parentheses +=1
                        indentLevel(self.indent + self.parentheses)
                        self.scope = Scope(self.indent + self.parentheses)
                    if bone in [')',']','}']:
                        self.parentheses -=1
                        indentLevel(self.indent + self.parentheses)
                        self.scope = getCurrentScope()
                pivot +=1
            pivot += len(word)
            #=======================
            
            if replaceNextBy != '':
                if not word in self.scope.translator.keys():
                    self.updateAllTranslators(word, replaceNextBy)
                replaceNextBy = ''
            if word in translator.getKeywords().keys():
                preservenext = False
            if word in ["from", "with", "import"]:
                if not preservenext:
                    preservenext = True
                    loadTranslator = True
            if word == "as":
                replaceNextBy = lastword
            if word in ['def', 'class']:
                self.nextParent = True
                self.surpresParentheses = True
            if preservenext:
                if not word in self.allTranslators.keys():
                    self.updateAllTranslators(word, word)
                    if loadTranslator:
                        try:
                            moduleDict = translator.createModuleDict(word)
                            self.scope.antiTranslator.update(moduleDict)
                            self.allTranslators.update(moduleDict)
                        except:
                            pass
                        loadTranslator = False
            else:
                if not word in self.allTranslators.keys():
                    try:
                        if re.match(r"const[0-9]{4}", word):
                            self.updateAllTranslators(word, word)
                        else:
                            iets = float(word)
                            self.updateAllTranslators(word, word)
                    except:
                        if self.nextParent:
                            #! actually methods, classes and vars should have independant counters
                            self.scope.methods[word] = self.scope
                            self.updateAllTranslators(word, 'meth' + ('00000' + str(self.scope.parent.varCount))[-5:])
                            self.scope.parent.varCount += 1
                            self.nextParent = False
                        else:
                            if self.parentheses > 0 and self.line[pivot:].strip()[0] == '=':
                                #It's not correct to add this word to the antitranslater of the current scope
                                #let try to create a new scope for every ( and [ and switch back to it's parent after ] or )
                                methodScope = self.scope.parent.getScopeByMethode(self.scope.parent.lastword)
                                try:
                                    self.updateAllTranslators(word,methodScope.getScopeTranslators()[word])
                                except:
                                    self.updateAllTranslators(word,word)
                            else:
                                self.updateAllTranslators(word, 'name' + ('00000' + str(self.scope.varCount))[-5:])
                                self.scope.varCount += 1
            lastword = word
            self.scope.lastword = word
            #append translated word to skeleton
            if word in self.scope.getScopeTranslators().keys():
                self.skel.append(self.scope.getScopeTranslators()[word])
            else:
                self.skel.append(word)
        #append trailing symbols to skeleton
        for bone in self.line[pivot:]:
            if not bone in [' ','\t','\n']:
                self.skel.append(bone)
            pivot +=1
Exemplo n.º 27
0
	def testScope(self):
		scope = Scope()
		scope['x'] = 9
		self.scoped.script.script = 'i = x'
		self.scoped.play(scope)
		self.assertEqual(scope['i'], 9)
Exemplo n.º 28
0
class Code():
    
    def createBaseMatrix(self):     
        self.rootScope = Scope(-1)
        indentLevel(-1)
        self.rootScope.antiTranslator = translator.getBuiltInNames()
        self.rootScope.antiTranslator.update(translator.getKeywords())
        
        self.baseMatrix = []
        lastIndent = 0
        #print self.code
        for part in self.code.split('~'):
            for line in part.splitlines(1):
                thisLine = Line(line)
                
                if thisLine.line != '': 
                    thisLine.setDeltaIndent(lastIndent)
                    lastIndent = thisLine.indent             
                    self.baseMatrix.append(thisLine) 
    
    def replaceMultiLineFromCode(self,quote):
        quoteCount = 0
        toReturn = ''
        for part in self.code.split(quote):
            if quoteCount % 2 == 0:
                toReturn += part
            else:
                toReturn += quote + part.replace('\n', '~').replace('/n','~') + quote
                
            quoteCount += 1
        self.code = toReturn

    def addLineNumbers(self):
        newCode = '' 
        number = 1
        for line in self.code.splitlines(1):
            newCode += str(number) + ":" + line
            number += 1
        self.code = newCode  
    
        
    
    def corectMultiLineLiterals(self):
        self.replaceMultiLineFromCode('"""')
        self.replaceMultiLineFromCode("'''")
        self.replaceMultiLineFromCode('"')
        self.replaceMultiLineFromCode("'")
        

    def getWorkingCopy(self):
        newCode = ''
        aline = False
        for line in self.baseMatrix:
            newCode += '    ' * line.indent + line.line + "\n"
            aline = True
        if aline:
            return newCode[0:-1]
        else:
            return newCode
        
    def getHashCopy(self,salt=''):
        '''Return a string representation of the code.
        
        The hash will contain chunks of 4 characters representing a
            delta-indentation, constant, name or symbol.
            
        The hash will start with a line number 'lddddddd' where d is a digit.
        The next chunck will indicate the delta of indentation.
        md5(i500) means that the indentation has not changed.
            md5(i501) means 1 indentation md5(i498) means 2 indentations back 
        '''
        newCode = ''
        for line in self.baseMatrix:
            m = md5()
            m.update('i' + str(line.deltaIndent) + salt)
            newCode += 'l' + ('0000000' + str(line.lineNumber))[-7:] +  ' ' + m.hexdigest()[0:4] + ' '
            for bone in line.skel:
                m = md5()
                m.update(bone + salt)
                newCode += m.hexdigest()[0:4] + ' '
            newCode = newCode[0:-1] + '\n'
        return newCode 
    
    
    
    def getWinnow(self, guarantee, noise=1, salt=''):
        thisWindow = Window(guarantee, noise)
        for line in self.getHashCopy(salt=salt).split('\n'):
            if line.strip() != '':
                
                lineNumber = int(line[1:line.find(' ')])
                line = line[line.find(' ') + 1:]
                for chunk in line.split(' '):
                    thisWindow.addChunk(chunk, lineNumber)
        return thisWindow.fingerPrint   
    
    def winnow2dict(self, guarantee, noise=1, salt=''):
        toReturn = []
        for [chunk,line] in self.getWinnow(guarantee, noise, salt=salt):       
            toReturn.append(chunk)
        return toReturn

    def winnow2str(self, guarantee, noise=1, salt=''):
        toReturn = ''
        for [chunk,line] in self.getWinnow(guarantee, noise, salt=salt):       
            toReturn += chunk + ' '
        return toReturn
        
    def __init__(self, code):
        self.code = code
        self.rootScope = None
        self.original = code
        self.baseMatrix = []
        self.addLineNumbers()
        self.corectMultiLineLiterals()
        self.createBaseMatrix()

        

    def __del__(self):
        myList = self.rootScope.collectAllScopes()
        clearScopes(myList)