def decryptionTeam(self): if self.team == Type().void: return "никому" if self.team == Type().redPlayer: return "красным" if self.team == Type().bluePlayer: return "синим" if self.team == Type().greenPlayer: return "зеленым" if self.team == Type().yellowPlayer: return "желтым" return "error"
def decryptionType(self): if self.type == Type().void: return "вода" if self.type == Type().ground: if self.subType == Type().forest: return "лес" if self.subType == Type().mountain: return "горы" if self.subType == Type().steppe: return "поле" return "error"
def mutations_competition(): a = Type('A', 10000, 10., 8.0) a.pos = (0, 0) b = Type('B', 0, 10., 5.0) b.pos = (1, 1) c = Type('C', 0, 10., 4.0) c.pos = (1, -1) a.add_mutation(b, 0.001) a.add_child(b) b.add_mutation(a, 0.001) b.add_parent(a) a.add_mutation(c, 0.001) a.add_child(c) c.add_mutation(a, 0.001) c.add_parent(a) sim = Simulation([a, b, c], max=10000, history=True, prints=True) sim.run(3.) data_plot.line_plot(sim, plt, do_reduce=False) plt.figure() data_plot.network(sim, nx=nx, plt=plt) plt.figure() data_plot.network_with_dominant(sim, sim.get_dominant_path(), nx=nx, plt=plt) plt.show()
def parse(str): index = 0 length = len(str) next_type_index = 0 previous_index = 0 current_type = None while index < len(str): next_colons = str.find("::", index) next_open_template = str.find("<", index) previous_index = index if next_colons == -1: next_type_index = length index = length else: index = next_colons + 2 next_type_index = next_colons if next_open_template < next_type_index and next_open_template != -1: open_count = 1 index = next_open_template + 1 first_open_template = next_open_template new_type = Type(str[previous_index:first_open_template]) type_start = first_open_template + 1 while open_count > 0: next_open_template = str.find("<", index) next_close_template = str.find(">", index) next_comma = str.find(",", index) if open_count == 1 and next_comma != -1: if next_comma < next_open_template or next_open_template == -1: if next_comma < next_close_template or next_close_template == -1: template_str = str[type_start:next_comma] new_type.templates.append(parse(template_str)) type_start = next_comma + 1 if next_open_template > next_close_template or next_open_template == -1: open_count -= 1 index = next_close_template + 1 if open_count == 0: template_str = str[type_start:index-1] new_type.templates.append(parse(template_str)) elif next_open_template != -1 and next_open_template < next_close_template: open_count += 1 index = next_open_template + 1 else: assert(False) else: new_type = Type(str[previous_index:next_type_index]) new_type.left = current_type current_type = new_type return current_type
def test_dump_statement(self): for statement in self.__statement1: t = Type(statement) self.assertEqual(t.dump_statement(), 'type name, attri1;') for statement in self.__statement2: t = Type(statement) self.assertEqual(t.dump_statement(), 'type name, attri1, attri2;') for statement in self.__statement3: t = Type(statement) self.assertEqual(t.dump_statement(), 'type name, attri1, attri2, attri3;')
def two_type_competition(): a = Type('A', 10000, 10., 8.0) b = Type('B', 100, 10., 5.0) sim = Simulation([a, b], max=10000, history=True, prints=True) sim.run(3.) data_plot.line_plot(sim, plt, do_reduce=False) plt.show()
def __init__(self, pokemon): self.pokemon = pokemon self.helpfulTypes = [] for weekness in [ type for type in Type.all() if type.effectiveAgainst(self.pokemon.types) ]: self.helpfulTypes.extend([ type.id for type in Type.all() if type.effectiveAgainst(weekness) ])
def attackTower(self): for y in range(self.size[1]): for x in range(self.size[0]): # башни бьют всех не своих в радиусе атаки if self.unit[x][y].type == Type().tower: # проходжим по радиусу атаки r = self.unit[x][y].attackRange() for _y in range(y - r, y + r + 1): for _x in range(x - r, x + r + 1): # башня башне башня if self.unit[_x][_y].type != Type().tower: self.attackUnit((x, y), (_x, _y))
def check_doubling_time(): # divide and times sizes by 10 to show doubling time is consistent a = Type('A', 500, 4., 2.) b = Type('Food Source', 2000 - a.size, 1., 1.) # stop point reduction if small simulation s = Simulation([a, b], max=2000, history=True, prints=True) s.run(10.0) data_plot.line_plot(s, plt, title='') plt.figure() data_plot.stacked_plot(s, plt, title='') plt.show()
def test_type(self): for statement in self.__statement1: t = Type(statement) self.assertEqual(t.getName(), 'name') self.assertEqual(t.getAttributes(), ['attri1']) for statement in self.__statement2: t = Type(statement) self.assertEqual(t.getName(), 'name') self.assertEqual(t.getAttributes(), ['attri1', 'attri2']) for statement in self.__statement3: t = Type(statement) self.assertEqual(t.getName(), 'name') self.assertEqual(t.getAttributes(), ['attri1', 'attri2', 'attri3'])
class Card: card1 = Type() card2 = Type() card3 = Type() card4 = Type() card5 = Type() card6 = Type() card7 = Type() card8 = Type() # card1.left = Infor() # card1.right = Infor() # card2.top = Infor() # card2.below = Infor() # card3.left = Infor() # card3.right = Infor() # card4.top = Infor() # card4.below = Infor() # card5.left = Infor() # card5.right = Infor() # card6.top = Infor() # card6.below = Infor() # card7.left = Infor() # card7.right = Infor() # card8.top = Infor() # card8.below = Infor() def __init__(self): # self.card1.left ='RX' # self.card1.right = 'WO' self.card1.left= ('RX','R','X',Card.card1) self.card1.right=('WO','W','O',Card.card1) # self.card2.top = 'RX' # self.card2.below = 'WO' self.card2.top = ('RX', 'R', 'X',Card.card2) self.card2.below = ('WO', 'W', 'O',Card.card2) # self.card3.left = 'WO' self.card3.left = ('WO', 'W', 'O',Card.card3) # self.card3.right = 'RX' self.card3.right = ('RX', 'R', 'X',Card.card3) # self.card4.top = 'WO' # self.card4.below = 'RX' self.card4.top = ('WO', 'W', 'O',Card.card4) self.card4.below = ('RX', 'R', 'X',Card.card4) # self.card5.left = "RO" # self.card5.right = 'WX' self.card5.left = ("RO",'R','O',Card.card5) self.card5.right = ('WX','W','X',Card.card5) # self.card6.top = 'RO' # self.card6.below = 'WX' self.card6.top = ("RO", 'R', 'O',Card.card6) self.card6.below = ('WX', 'W', 'X',Card.card6) # self.card7.left = 'WX' # self.card7.right ='RO' self.card7.left = ('WX', 'W', 'X',Card.card7) self.card7.right = ("RO", 'R', 'O',Card.card7) # self.card8.top = 'WX' # self.card8.below = 'RO' self.card8.top = ('WX', 'W', 'X',Card.card8) self.card8.below = ("RO", 'R', 'O',Card.card8)
class Card: card1 = Type() card2 = Type() card3 = Type() card4 = Type() card5 = Type() card6 = Type() card7 = Type() card8 = Type() def __init__(self): self.card5.left = "WO" self.card5.right = 'RX' self.card1.left = 'WO' self.card1.right = 'RX' self.card2.top = 'RX' self.card2.below = 'WO' self.card3.left = 'WO' self.card3.right = 'RX' self.card4.top = 'WO' self.card4.below = 'RX' self.card6.top = 'RO' self.card6.below = 'WX' self.card7.left = 'WX' self.card7.right = 'RO' self.card8.top = 'WX' self.card8.below = 'RO'
def set (self, value, atom = None): from myelin.module import MetaObject # convert python types if type(value) is bool: self.set_bool (value) # set the right integer type elif type(value) is int or type(value) is long: if atom is not None: if atom == Type.type_char(): self.set_char (value) elif atom == Type.type_uchar(): self.set_uchar (value) elif atom == Type.type_int(): self.set_int (value) elif atom == Type.type_uint(): self.set_uint (value) elif atom == Type.type_long(): self.set_long (value) elif atom == Type.type_ulong(): self.set_ulong (value) # for long only elif type(value) is long: if atom == Type.type_int64(): self.set_int64 (value) elif atom == Type.type_uint64(): self.set_uint64 (value) else: if type(value) is int: self.set_long (value) else: self.set_int64 (value) elif type(value) is float: if atom is not None: if atom == Type.type_float(): self.set_float (value) elif atom == Type.type_double(): self.set_double (value) else: self.set_double (value) elif type(value) is str: self.set_string (value) # set meta object instance elif isinstance(value, MetaObject): val = value._object.get_instance() self.set_pointer (val.get_type(), val.as_pointer()) else: raise TypeError ("Cannot determine an equivalent type for the " \ "value type '%s'. Conversion failed." % type(value))
def postfix_expression(self) -> Node: postfix = self.primary_expression() while True: if self.consume('['): exp = self.expression() self.consume_must(']') if not postfix.type.is_ptr and not exp.type.is_ptr: TypeError('ポインタ以外を配列参照しています') node = self.sub_add(postfix, exp) postfix = Node(ND.REF, type=node.type.ptr_to, lhs=node) continue if self.consume('('): if postfix.type.ty == '.unknown': warning(postfix.val, '関数の暗黙的宣言(返り値をlongにします)') postfix.type = Type('.func', func_call_to=Type('long', signed=True)) args = self.sep_repeat(self.assignment_expression, ',', True) self.consume_must(')') if not postfix.type.is_func: raise TypeError('関数以外を呼び出そうとしています') postfix = Node(ND.CALL, type=postfix.type.func_call_to, call=postfix, call_args=args) continue if self.consume('++'): if not postfix.type.is_real_num(): raise TypeError('後置++に実数型以外が指定されています') if postfix.type.const: raise TypeError('後置++にconst変数が指定されています') postfix = Node('++', type=postfix.type, lhs=postfix) continue if self.consume('--'): if not postfix.type.is_real_num(): raise TypeError('後置--に実数型以外が指定されています') if postfix.type.const: raise TypeError('後置--にconst変数が指定されています') postfix = Node('--', type=postfix.type, lhs=postfix) continue break if postfix.type.ty == '.unknown': raise TypeError('変数が宣言されていません') return postfix
def spawnBuilding(self, building, To): x = To[0] y = To[1] # если место свободно if self.unit[x][y].type == Type( ).void and self.building[x][y].type == Type().void: # если пренадлежит игроку if self.cell[x][y].team == self.player.thisPlayer(): self.building[x][y] = building elif self.cell[x][y].type == Type().void and building.type == Type( ).road: self.building[x][y] = building self.loadToStepBuffer()
def load_from_file(cls, type_file): data = open(type_file).read() data = data.split('\n') mime_types = Types() for index, line in enumerate(data): item = line.strip() if not item: continue try: ret = TEXT_FORMAT_RE.match(item).groups() except Exception as e: __parsing_error(type_file, index, line, e) (unregistered, obsolete, platform, mediatype, subtype, extensions, encoding, urls, docs, comment) = ret if mediatype is None: if comment is None: __parsing_error(type_file, index, line, RuntimeError) continue extensions = extensions and extensions.split(',') or [] urls = urls and urls.split(',') or [] mime_type = Type('%s/%s' % (mediatype, subtype)) mime_type.extensions = extensions mime_type.encoding = encoding mime_type.system = platform mime_type.is_obsolete = bool(obsolete) mime_type.registered = (not unregistered) mime_type.docs = docs mime_type.url = urls mime_types.add(mime_type) return mime_types
def __repr__ (self): virtual = "virtual" if self.is_virtual() else "" constant = "const" if self.is_constant() else "" params = "" for param in self.get_type().get_param_types(): type = Type.from_pointer (param.as_pointer()) if len(params) > 0: params = params + ", " + type.get_name() else: params = type.get_name() prototype = ("%s %s %s (%s) %s" % (virtual, self.get_type().get_return_type().get_name(), self.get_name(), params, constant)) prototype = prototype.strip() return ("<%s.%s object at %#x with a function object instance at %#x " \ "implementing the prototype %s>" % (self.__module__, self.__class__.__name__, id(self), self._ptr, prototype))
def getParameters(aParams, aTypes, aOffset): if aParams == []: return [] if aParams[0] in aTypes: t = aTypes[aParams[0]] elif aParams[0][0] == '@' and aParams[0][1:] in aTypes: t = aTypes[aParams[0][1:]] else: # Type not known, assume TDesC8 t = aTypes.get( aParams[1], Type(aParams[0], 'TDesC8', 'TPtrC8', 'TPtrC8', aParams[1], 'AsString', 'PutString', 'PutString', '', True, False, False, '_L8("\\x0")', '_L8("\\xff")', 'UnknownType_instance', '', '')) newOffset = aOffset if t.iSize != 'n': # Not of 'infinite' size newOffset += int(t.iSize) if len(aParams) > 2 and aParams[ 2] == '*': # Is 'array', delimited by other parameter. return [Parameter(t, aParams[0], aOffset, aParams[3])] + getParameters( aParams[4:], aTypes, newOffset) else: return [Parameter(t, aParams[0], aOffset)] + getParameters( aParams[2:], aTypes, newOffset)
def __translate_define_expr(self, expr, end=True): ''' Get a single parsed DEFINE expression and return the equivalent C++ and CUDA code. If 'end' is false, then the final characters of the expression, like semi-colons and newlines, are not added. ''' cpp = '' cuda = '' return_type = Type.enum_to_c_type(expr.loc, expr.type) cpp = f'{return_type} {expr.name}(' # Add the parameters. for (arg_type, arg_name) in expr.args[:-1]: cpp += f'{Type.enum_to_c_type(expr.loc, arg_type)} {arg_name}, ' # The last parameter is a little different. if len(expr.args) > 0: (arg_type, arg_name) = expr.args[-1] cpp += f'{Type.enum_to_c_type(expr.loc, arg_type)} {arg_name}' cpp += ')' # Add this prototype for use in a header file. self.cpp_prototypes.append(cpp + ';\n') cpp += ' {\n' # Add the body of the function. body_cpp = '' for e in expr.body[:-1]: (c, cu) = self.__translate_expr(e, True) body_cpp += c cuda += cu # The last expression should be returned. if len(expr.body) == 0: error_str = 'expected one or more body expressions' raise error.Syntax(expr.loc, error_str) e = expr.body[-1] if e.exprClass != ExprEnum.LITERAL and \ e.exprClass != ExprEnum.GET_VAR and \ e.exprClass != ExprEnum.CALL: error_str = 'expected literal, get, or call as last body expression' raise error.Syntax(expr.loc, error_str) (c, cu) = self.__translate_expr(e, False) body_cpp += f'return {c};\n' cuda += cu self._increase_indent() body_cpp = self._make_indented(body_cpp) self._decrease_indent() cpp = self._make_indented(cpp) cpp = cpp + body_cpp + self._make_indented('}\n\n') return (cpp, cuda)
def __init__(self, dex=None, pid=None): if dex is not None: self.dex = dex else: self.dex = DexLoader().pokedex self.pokemon = self.dex.get(str(pid)) self.name = self.pokemon.get("name") self.types = [Type(DexLoader().typedex, type) for type in self.pokemon.get("types")] self.weight = self.pokemon.get("weight") / 10 self.stats = { "base": self.pokemon.get("stats"), "stage": { "attack": 0, "defense": 0, "spattack": 0, "spdefense": 0, "speed": 0 } } self.maxHp = 141 + 2 * self.pokemon.get("stats").get("hp") self.hp = self.maxHp self.conditions = {} self.ailment = None self.faintObservers = [] self.strategy = Strategy(self) self.move = None self.moves = self.strategy.chooseBuild([Move(mid=move) for move in self.pokemon.get("moves")]) self.trainer = None self.score = 0
def renderUnitInfo(self, screen): # информация о ините AboutCell = pygame.font.Font(None, 25) text = list() if self.unit[self.selectedPos[0]][ self.selectedPos[1]].type != Type().void: text.append(" ___ПЕШКА___") text.append(" Тип : {}".format(self.unit[ self.selectedPos[0]][self.selectedPos[1]].decryptionType())) text.append(" Уровень: {}".format(self.unit[ self.selectedPos[0]][self.selectedPos[1]].decryptionLevel())) text.append(" Принадлежит: {}".format(self.unit[ self.selectedPos[0]][self.selectedPos[1]].decryptionTeam())) text.append(" Урон: {}".format( self.unit[self.selectedPos[0]][self.selectedPos[1]].damage())) text.append(" Защита: {}".format( self.unit[self.selectedPos[0]][self.selectedPos[1]].health())) text.append(" Радиус атаки: {}".format(self.unit[ self.selectedPos[0]][self.selectedPos[1]].attackRange())) text.append(" Радиус перемещения: {}".format(self.unit[ self.selectedPos[0]][self.selectedPos[1]].moveRange())) for i in range(len(text)): screen.blit(AboutCell.render(text[i], False, (0, 0, 0)), (0, 210 + i * 35))
def function_definition(self): decl_specs = self.declaration_specifiers() t = self.make_type(decl_specs) declarator, pointer = self.declarator() if isinstance(declarator, str) or declarator.ty != 'func': raise TypeError('関数宣言には()が必要です') name = declarator.name parameter_list: List[Tuple[Type, Optional[Union[str, InnerNode]]]]\ = declarator.list self.variables.new_scope() for t, (n, p) in parameter_list: if not isinstance(n, str): raise TypeError('引数はスカラ変数にしてください(非対応)') self.variables.set_var(n, t) args = self.variables.pop_scope() self.variables.push_scope(copy(args)) block = self.compound_statement() block.args = args self.variables.set_var(name, Type('.func', func_call_to=t)) return Node(ND.DEF, val=name, block=block)
def createBg(self): image = Image.open("source\pattern\pattern.png") pixel = image.load() # переносим изменения на поле for x in range(0, self.size[0]): for y in range(0, self.size[1]): if pixel[x, y][0] == 0: self.cell[x][y] = Cell(Type().ground, Type().forest) elif pixel[x, y][0] == 50: self.cell[x][y] = Cell(Type().ground, Type().steppe) elif pixel[x, y][0] == 100: self.cell[x][y] = Cell(Type().ground, Type().mountain) elif pixel[x, y][0] == 255: self.cell[x][y] = Cell(Type().void) self.unit[x][y].type = Type().void self.building[x][y].type = Type().void image = Image.new("RGBA", (self.plates_size[0] * self.size[0], self.plates_size[1] * self.size[1]), (255, 255, 255)) pixel = image.load() for x in range(0, self.size[0]): for y in range(0, self.size[1]): cell_l = self.cell[x][y] for _x in range( x * self.plates_size[0], min((x + 1) * self.plates_size[0], image.size[0])): for _y in range( y * self.plates_size[1], min((y + 1) * self.plates_size[1], image.size[1])): if cell_l.type == Type().void: clr = self.imageVoid[0].get_at( (_x % self.plates_size[0], _y % self.plates_size[1])) else: clr = self.imageGround[cell_l.subType].get_at( (_x % self.plates_size[0], _y % self.plates_size[1])) pixel[_x, _y] = (clr[0], clr[1], clr[2], clr[3]) image.save("source/pattern/bg.png") self.background = pygame.image.load("source/pattern/bg.png") self.clearStepBuffer()
def test_hasAttribute(self): for statement in self.__statement1: t = Type(statement) self.assertTrue(t.hasAttribute('attri1')) self.assertFalse(t.hasAttribute('attri2')) self.assertFalse(t.hasAttribute('attri3')) for statement in self.__statement2: t = Type(statement) self.assertTrue(t.hasAttribute('attri1')) self.assertTrue(t.hasAttribute('attri2')) self.assertFalse(t.hasAttribute('attri3')) for statement in self.__statement3: t = Type(statement) self.assertTrue(t.hasAttribute('attri1')) self.assertTrue(t.hasAttribute('attri2')) self.assertTrue(t.hasAttribute('attri3')) self.assertFalse(t.hasAttribute('attri4'))
def moveUnit(self, From, To): x0, y0 = From[0], From[1] x1, y1 = To[0], To[1] if 0 <= x1 < self.size[0] and 0 <= y1 < self.size[1]: if self.unit[x0][y0].type != Type( ).void and self.unit[x0][y0].move == False: # если выбран чужой юнит - скип if self.unit[x0][y0].team != self.player.thisPlayer(): return # если ходим на слишком далекое расстояние if abs(x1 - x0) > self.unit[x0][y0].moveRange() or abs( y1 - y0) > self.unit[x0][y0].moveRange(): return # если ходим под себя, то не ходим if From == To: return # если ходим в воду, при этом на воде нет дороги if self.cell[x1][y1].type == Type( ).void and self.building[x1][y1].type != Type().road: return # если ходим на пустую клетку, то ходим и занимаем клетку if self.unit[x1][y1].type == Type().void and ( self.building[x1][y1].type == Type().void or self.building[x1][y1].type == Type().road): self.unit[x0][y0], self.unit[x1][y1] = Unit( ), self.unit[x0][y0] self.cell[x0][y0].isSelected, self.cell[x1][ y1].isSelected = False, True self.selectedPos = (x1, y1) self.unit[x1][y1].move = True if self.cell[x1][y1].type != Type().void: self.cell[x1][y1].team = self.unit[x1][y1].team self.loadToStepBuffer()
def __parse_literal(self, start_point_loc): ''' Private function to parse a single LITERAL expression. The _file variable should be in a state starting with (without quotes): '<val>)' That is, the '(lit ' section has alread been read. Returns an instance of Literal() ''' lit_val = self.__parse_word() loc = start_point_loc.span(self.__get_point_loc()) # Convert the value to the correct type. lit_type = Type.get_type_from_string_val(loc, lit_val) lit_val = Type.convert_type(loc, lit_type, lit_val) return Literal(loc, lit_type, lit_val)
def renderArea(self, screen): # области игроков for y in range(self.size[1]): for x in range(self.size[0]): if self.cell[x][y].team != Type().void: rect = (int(x * self.plates_size[0]) + self.sideShift, int(y * self.plates_size[1])) screen.blit(self.imageArea[0][self.cell[x][y].team - 1], rect)
def p(g: InnerNode): a = Type('.ptr') if g.to is None: a.ptr_to = t return a a.ptr_to = p(g.to) return a
def equality_expression(self) -> Node: equality = self.relational_expression() while True: if self.consume('=='): rhs = self.relational_expression() if not Type.both_arithmetic(equality.type, rhs.type): raise TypeError('比較演算子==に算術型以外が指定されています') equality = Node('==', type=t_signed_int, lhs=equality, rhs=rhs) continue if self.consume('!='): rhs = self.relational_expression() if not Type.both_arithmetic(equality.type, rhs.type): raise TypeError('比較演算子!=に算術型以外が指定されています') equality = Node('!=', type=t_signed_int, lhs=equality, rhs=rhs) continue break return equality
def relational_expression(self) -> Node: relational = self.shift_expression() while True: # todo: http://port70.net/~nsz/c/c11/n1570.html#6.5.8p2 2番目の制約 if self.consume('<'): rhs = self.shift_expression() if not Type.both_real_num(relational.type, rhs.type): raise TypeError('比較演算子<に実数型以外が指定されています') relational = Node('<', type=t_signed_int, lhs=relational, rhs=rhs) continue if self.consume('>'): rhs = self.shift_expression() if not Type.both_real_num(relational.type, rhs.type): raise TypeError('比較演算子>に実数型以外が指定されています') relational = Node('<', type=t_signed_int, rhs=relational, lhs=rhs) continue if self.consume('<='): rhs = self.shift_expression() if not Type.both_real_num(relational.type, rhs.type): raise TypeError('比較演算子<=に実数型以外が指定されています') relational = Node('<=', type=t_signed_int, lhs=relational, rhs=rhs) continue if self.consume('>='): rhs = self.shift_expression() if not Type.both_real_num(relational.type, rhs.type): raise TypeError('比較演算子>=に実数型以外が指定されています') relational = Node('<=', type=t_signed_int, rhs=relational, lhs=rhs) continue break return relational
def renderUnit(self, screen): # отрисовка окружения поля for y in range(self.size[1]): for x in range(self.size[0]): if self.unit[x][y].type != Type().void: rect = (int(x * self.plates_size[0]) + self.sideShift, int(y * self.plates_size[1])) image = self.imageUnit[self.unit[x][y].type - 1][self.unit[x][y].team - 1] screen.blit(image, rect)
def shift_expression(self) -> Node: shift = self.additive_expression() while True: if self.consume('>>'): rhs = self.additive_expression() if not Type.both_integer(shift.type, rhs.type): raise TypeError('右シフト演算子>>に整数型以外が指定されています') shift = Node('>>', type=shift.type, lhs=shift, rhs=rhs) continue if self.consume('<<'): rhs = self.additive_expression() if not Type.both_integer(shift.type, rhs.type): raise TypeError('左シフト演算子<<に整数型以外が指定されています') shift = Node('<<', type=shift.type, lhs=shift, rhs=rhs) continue break return shift
def check_param_types (types, params): # check param size if params.get_size() <> types.get_size(): raise ValueError ("Parameter list must have '%d' matching values, " \ "'%d' was given" % (types.get_size(), params.get_size())) # check param types for i in range(0, len(params)): # get types param_type = params[i].get_type() expected_type = Type.from_pointer (types[i].get_pointer().get_raw()) # get real pointer type from generic pointer if param_type.get_atom() == Type.type_pointer(): param_type = params[i].get_pointer().get_type() # make sure we have the same type atom if param_type.get_atom() != expected_type.get_atom(): raise TypeError ("Parameter '%d' does not match the appropriate " \ "type. Expected '%s', got '%s'" % (i + 1, expected_type.get_name(), param_type.get_name())) # reference parameter types must be a pointer if expected_type.is_reference() and not param_type.is_pointer(): raise TypeError ("Parameter '%d' is a reference type '%s' but " \ "the expected type is not a pointer, " \ "instead '%s' was given" % (i + 1, expected_type.get_name(), param_type.get_name()))
def _get_variables_info(self, var_descriptions): """ Returns the given variable names as a list of gdb.Values. var_descriptions: list of tuples in the form (name, value) of visible variables """ vars = [] for var in var_descriptions: gdb_val = gdb.parse_and_eval(var[0]) basic_var = Variable(str(gdb_val), Type.from_gdb_type(gdb_val.type), var[0], gdb_val.address) vars.append(basic_var) return vars
def __repr__ (self): params = "" for param in self.get_param_types(): type = Type.from_pointer (param.as_pointer()) if len(params) > 0: params = params + ", " + type.get_name() else: params = type.get_name() if (len(params) > 0): params = "requiring the parameters (%s)" % params else: params = "requiring no parameters" return ("<%s.%s object at %#x with a constructor object instance at " \ "%#x %s>" % (self.__module__, self.__class__.__name__, id(self), self._ptr, params))
def get (self): # empty value if self.is_empty(): return None # get value type type = self.get_type() atom = type.get_atom() # convert value types if not type.is_pointer() and not type.is_reference(): # fundamental types if atom == Type.type_bool (): return self.get_bool () elif atom == Type.type_char (): return self.get_char () elif atom == Type.type_uchar (): return self.get_uchar () elif atom == Type.type_int (): return self.get_int () elif atom == Type.type_uint (): return self.get_uint () elif atom == Type.type_long (): return self.get_long () elif atom == Type.type_ulong (): return self.get_ulong () elif atom == Type.type_int64 (): return self.get_int64 () elif atom == Type.type_uint64 (): return self.get_uint64 () elif atom == Type.type_float (): return self.get_float () elif atom == Type.type_double (): return self.get_double () # elif atom == Type.type_string (): return self.get_string () # convert value to meta class instance class_type = get_type (type) if class_type is not None: return class_type (instance = self) # dont know how to convert value so just return it as is else: return self
def get_type (self): type = _lib.myelin_value_get_type (self) return Type.from_pointer (type)
def get_param_type (self, index): type = _lib.myelin_function_type_get_param_type (self, index) return Type.from_pointer (type)
def get_return_type (self): type = _lib.myelin_function_type_get_return_type (self) return Type.from_pointer (type)
def get_param_type (self, index): type = _lib.myelin_constructor_get_param_type (self, index) return Type.from_pointer (type)
def get_output_type(self): type = _lib.myelin_converter_get_output_type(self) return Type.from_pointer(type)
def get_type (self): return Type.from_pointer (_lib.myelin_class_get_type (self))