code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
output = [] output.extend(AT_END) if REQUIRES.intersection(MEMINITS) or '__MEM_INIT' in INITS: output.append(OPTIONS.heap_start_label.value + ':') output.append('; Defines DATA END\n' + 'ZXBASIC_USER_DATA_END EQU ZXBASIC_MEM_HEAP + ZXBASIC_HEAP_SIZE') else: output.append('; Defines DATA END --> HEAP size is 0\n' + 'ZXBASIC_USER_DATA_END EQU ZXBASIC_MEM_HEAP') output.append('; Defines USER DATA Length in bytes\n' + 'ZXBASIC_USER_DATA_LEN EQU ZXBASIC_USER_DATA_END - ZXBASIC_USER_DATA') if OPTIONS.autorun.value: output.append('END %s' % START_LABEL) else: output.append('END') return output
def emit_end(MEMORY=None)
This special ending autoinitializes required inits (mainly alloc.asm) and changes the MEMORY initial address if it is ORG XXXX to ORG XXXX + heap size
8.584157
8.01028
1.071643
r'[\\_]\r?\n' t.lexer.lineno += 1 t.value = t.value[1:] return t
def t_asm_CONTINUE(self, t)
r'[\\_]\r?\n
8.235835
3.862551
2.132227
r'\r?\n' # New line => remove whatever state in top of the stack and replace it with INITIAL t.lexer.lineno += 1 t.lexer.pop_state() return t
def t_asmcomment_NEWLINE(self, t)
r'\r?\n
17.541508
15.359183
1.142086
r'\r?\n' t.lexer.lineno += 1 t.lexer.pop_state() return t
def t_prepro_define_defargs_defargsopt_defexpr_pragma_if_NEWLINE(self, t)
r'\r?\n
7.838169
4.698984
1.668056
r'\r?\n' t.lexer.pop_state() # Back to initial t.lexer.lineno += 1 return t
def t_singlecomment_NEWLINE(self, t)
r'\r?\n
8.327891
6.554449
1.270571
r"'/" self.__COMMENT_LEVEL -= 1 if not self.__COMMENT_LEVEL: t.lexer.begin('INITIAL')
def t_comment_endBlock(self, t)
r"'/
8.971621
6.282987
1.427923
r'.*\n' t.lexer.lineno += 1 t.lexer.begin('INITIAL') t.value = t.value.strip() # remove newline an spaces return t
def t_msg_STRING(self, t)
r'.*\n
6.44362
4.093778
1.574003
r'[\\_]\r?\n' t.lexer.lineno += 1 t.value = t.value[1:] return t
def t_defexpr_CONTINUE(self, t)
r'[\\_]\r?\n
8.41167
3.901433
2.156046
r'[_a-zA-Z][_a-zA-Z0-9]*' # preprocessor directives t.type = reserved_directives.get(t.value.lower(), 'ID') states_ = { 'DEFINE': 'define', 'PRAGMA': 'pragma', 'IF': 'if', 'ERROR': 'msg', 'WARNING': 'msg' } if t.type in states_: t.lexer.begin(states_[t.type]) elif t.type == 'ID' and self.expectingDirective: self.error("invalid directive #%s" % t.value) self.expectingDirective = False return t
def t_prepro_ID(self, t)
r'[_a-zA-Z][_a-zA-Z0-9]*
4.098841
3.950412
1.037573
r'[_a-zA-Z][_a-zA-Z0-9]*' # pragma directives if t.value.upper() in ('PUSH', 'POP'): t.type = t.value.upper() return t
def t_pragma_ID(self, t)
r'[_a-zA-Z][_a-zA-Z0-9]*
4.183187
3.861463
1.083317
r'[ \t]*\#' # Only matches if at beginning of line and "#" if self.find_column(t) == 1: t.lexer.push_state('prepro') # Start preprocessor self.expectingDirective = True
def t_INITIAL_asm_sharp(self, t)
r'[ \t]*\#
17.198643
13.752782
1.250557
return '%s#line %i "%s"%s' % (prefix, self.lex.lineno, self.filestack[-1][0], suffix)
def put_current_line(self, prefix='', suffix='')
Returns line and file for include / end of include sequences.
8.241282
6.346108
1.298636
self.lex = self.filestack[-1][2] self.input_data = self.filestack[-1][3] self.filestack.pop() if not self.filestack: # End of input? return self.filestack[-1][1] += 1 # Increment line counter of previous file result = lex.LexToken() result.value = self.put_current_line(suffix='\n') result.type = '_ENDFILE_' result.lineno = self.lex.lineno result.lexpos = self.lex.lexpos return result
def include_end(self)
Performs and end of include.
5.123925
4.909488
1.043678
self.filestack.append([filename, 1, self.lex, self.input_data]) self.input_data = str self.lex = lex.lex(object=self) self.lex.input(self.input_data)
def input(self, str, filename='')
Defines input string, removing current lexer.
4.891066
4.019836
1.216733
tok = None if self.next_token is not None: tok = lex.LexToken() tok.value = '' tok.lineno = self.lex.lineno tok.lexpos = self.lex.lexpos tok.type = self.next_token self.next_token = None while self.lex is not None and tok is None: tok = self.lex.token() if tok is not None: break tok = self.include_end() return tok
def token(self)
Returns a token from the current input. If tok is None from the current input, it means we are at end of current input (e.g. at end of include file). If so, closes the current input and discards it; then pops the previous input and lexer from the input stack, and gets another token. If new token is again None, repeat the process described above until the token is either not None, or self.lex is None, wich means we must effectively return None, because parsing has ended.
3.310986
2.934369
1.128347
i = token.lexpos while i > 0: if self.input_data[i - 1] == '\n': break i -= 1 column = token.lexpos - i + 1 return column
def find_column(self, token)
Compute column: - token is a token instance
2.746037
3.054154
0.899115
intPitch = int(pitch) fractPitch = pitch - intPitch # Gets fractional part tmp = 1 + 0.0577622606 * fractPitch if not -60 <= intPitch <= 127: raise BeepError('Pitch out of range: must be between [-60, 127]') if duration < 0 or duration > 10: raise BeepError('Invalid duration: must be between [0, 10]') A = intPitch + 60 B = -5 + int(A / 12) # -5 <= B <= 10 A %= 0xC # Semitones above C frec = TABLE[A] tmp2 = tmp * frec f = tmp2 * 2.0 ** B DE = int(0.5 + f * duration - 1) HL = int(0.5 + 437500.0 / f - 30.125) return DE, HL
def getDEHL(duration, pitch)
Converts duration,pitch to a pair of unsigned 16 bit integers, to be loaded in DE,HL, following the ROM listing. Returns a t-uple with the DE, HL values.
6.212722
6.321786
0.982748
new_args = [] args = [x for x in args if not is_null(x)] for x in args: assert isinstance(x, Symbol) if x.token == 'BLOCK': new_args.extend(SymbolBLOCK.make_node(*x.children).children) else: new_args.append(x) result = SymbolBLOCK(*new_args) return result
def make_node(cls, *args)
Creates a chain of code blocks.
4.975408
4.589476
1.084091
r'__[a-zA-Z]+__' if t.value in macros: t.type = t.value return t syntax_error(t.lexer.lineno, "unknown macro '%s'" % t.value)
def t_MACROS(t)
r'__[a-zA-Z]+__
4.03264
3.344396
1.20579
r"\\[ '.:][ '.:]" global __STRING P = {' ': 0, "'": 2, '.': 8, ':': 10} N = {' ': 0, "'": 1, '.': 4, ':': 5} __STRING += chr(128 + P[t.value[1]] + N[t.value[2]])
def t_string_NGRAPH(t)
r"\\[ '.:][ '.:]
7.3287
4.741789
1.545556
r'"' global __STRING t.lexer.begin('INITIAL') t.value = __STRING __STRING = '' return t
def t_string_STRC(t)
r'"
12.227478
10.244493
1.193566
r'\b[aA][sS][mM]\b' global ASM, ASMLINENO, IN_STATE t.lexer.begin('asm') ASM = '' ASMLINENO = t.lexer.lineno IN_STATE = True
def t_asm(t)
r'\b[aA][sS][mM]\b
7.200228
6.100118
1.180342
r'\b[eE][nN][dD][ \t]+[aA][sS][mM]\b' global IN_STATE t.lexer.begin('INITIAL') t.value = ASM t.lineno = ASMLINENO - 1 IN_STATE = False return t
def t_asm_ASM(t)
r'\b[eE][nN][dD][ \t]+[aA][sS][mM]\b
8.639963
5.949934
1.452111
r"([']|[Rr][Ee][Mm])\r?\n" t.lexer.begin('INITIAL') t.lexer.lineno += 1 t.value = '\n' t.type = 'NEWLINE' return t
def t_EmptyRem(t)
r"([']|[Rr][Ee][Mm])\r?\n
6.660796
3.294185
2.021986
r'[_A-Za-z]+' t.value = t.value.strip() t.type = preprocessor.get(t.value.lower(), 'ID') return t
def t_preproc_ID(t)
r'[_A-Za-z]+
5.188431
3.993825
1.299113
r'[a-zA-Z][a-zA-Z0-9]*[$%]?' t.type = reserved.get(t.value.lower(), 'ID') callables = { api.constants.CLASS.array: 'ARRAY_ID', } if t.type != 'ID': t.value = t.type else: entry = api.global_.SYMBOL_TABLE.get_entry(t.value) if api.global_.SYMBOL_TABLE is not None else None if entry: t.type = callables.get(entry.class_, t.type) if t.type == 'BIN': t.lexer.begin('bin') return None return t
def t_ID(t)
r'[a-zA-Z][a-zA-Z0-9]*[$%]?
5.103189
4.590076
1.111787
r'([0-9][0-9a-fA-F]*[hH])|(\$[0-9a-fA-F]+)|(0x[0-9a-fA-F]+)' if t.value[0] == '$': t.value = t.value[1:] # Remove initial '$' elif t.value[:2] == '0x': t.value = t.value[2:] # Remove initial '0x' else: t.value = t.value[:-1] # Remove last 'h' t.value = int(t.value, 16) # Convert to decimal t.type = 'NUMBER' return t
def t_HEXA(t)
r'([0-9][0-9a-fA-F]*[hH])|(\$[0-9a-fA-F]+)|(0x[0-9a-fA-F]+)
2.311027
1.90997
1.209981
r'[0-7]+[oO]' t.value = t.value[:-1] t.type = 'NUMBER' t.value = int(t.value, 8) return t
def t_OCTAL(t)
r'[0-7]+[oO]
3.779563
3.198129
1.181804
r'[01]+' # A binary integer t.value = int(t.value, 2) t.lexer.begin('INITIAL') return t
def t_bin_NUMBER(t)
r'[01]+
5.688571
4.938716
1.151832
# This pattern must come AFTER t_HEXA and t_BIN r'(([0-9]+(\.[0-9]+)?)|(\.[0-9]+))([eE][-+]?[0-9]+)?' t.text = t.value t.value = float(t.value) if t.value == int(t.value) and is_label(t): t.value = int(t.value) t.type = 'LABEL' return t
def t_NUMBER(t)
r'(([0-9]+(\.[0-9]+)?)|(\.[0-9]+))([eE][-+]?[0-9]+)?
3.328182
3.506674
0.949099
r'[^01]' t.lexer.begin('INITIAL') t.type = 'NUMBER' t.value = 0 t.lexer.lexpos -= 1 return t
def t_bin_ZERO(t)
r'[^01]
4.667359
3.755972
1.24265
r'\r?\n' global LABELS_ALLOWED t.lexer.lineno += 1 t.value = '\n' LABELS_ALLOWED = True return t
def t_INITIAL_bin_NEWLINE(t)
r'\r?\n
8.030794
7.511007
1.069203
i = token.lexpos input = token.lexer.lexdata while i > 0: if input[i - 1] == '\n': break i -= 1 column = token.lexpos - i + 1 return column
def find_column(token)
Compute column: input is the input text string token is a token instance
2.78327
3.147599
0.884252
if not LABELS_ALLOWED: return False c = i = token.lexpos input = token.lexer.lexdata c -= 1 while c > 0 and input[c] in (' ', '\t'): c -= 1 while i > 0: if input[i] == '\n': break i -= 1 column = c - i if column == 0: column += 1 return column == 1
def is_label(token)
Return whether the token is a label (an integer number or id at the beginning of a line. To do so, we compute find_column() and moves back to the beginning of the line if previous chars are spaces or tabs. If column 0 is reached, it's a label.
4.185185
4.070615
1.028146
assert isinstance(other, (numbers.Number, SymbolNUMBER, SymbolCONST)) if isinstance(other, SymbolNUMBER): return other.value if isinstance(other, SymbolCONST): return other.expr.value return other
def _get_val(other)
Given a Number, a Numeric Constant or a python number return its value
5.16048
4.126312
1.250627
for x in table.table.keys(): sys.stdout.write("{0}\t<--- {1} {2}".format(x, table[x], type(table[x]))) if isinstance(table[x], ID): sys.stdout(" {0}".format(table[x].value)), sys.stdout.write("\n")
def __dumptable(self, table)
Dumps table on screen for debugging purposes
5.298439
4.940851
1.072374
if len(node.children) == 2: node.children[1] = (yield ToVisit(node.children[1])) yield node
def visit_RETURN(self, node)
Visits only children[1], since children[0] points to the current function being returned from (if any), and might cause infinite recursion.
6.905019
5.460577
1.264522
return functools.reduce(lambda x, y: x * y, (x.count for x in self.bounds))
def count(self)
Total number of array cells
7.374332
7.058147
1.044797
return self.size + 1 + TYPE.size(gl.BOUND_TYPE) * len(self.bounds)
def memsize(self)
Total array cell + indexes size
30.732401
23.428814
1.311735
assert isinstance(new_type, SymbolTYPE) # None (null) means the given AST node is empty (usually an error) if node is None: return None # Do nothing. Return None assert isinstance(node, Symbol), '<%s> is not a Symbol' % node # The source and dest types are the same if new_type == node.type_: return node # Do nothing. Return as is STRTYPE = TYPE.string # Typecasting, at the moment, only for number if node.type_ == STRTYPE: syntax_error(lineno, 'Cannot convert string to a value. ' 'Use VAL() function') return None # Converting from string to number is done by STR if new_type == STRTYPE: syntax_error(lineno, 'Cannot convert value to string. ' 'Use STR() function') return None # If the given operand is a constant, perform a static typecast if is_CONST(node): node.expr = cls(new_type, node.expr, lineno) return node if not is_number(node) and not is_const(node): return cls(new_type, node, lineno) # It's a number. So let's convert it directly if is_const(node): node = SymbolNUMBER(node.value, node.lineno, node.type_) if new_type.is_basic and not TYPE.is_integral(new_type): # not an integer node.value = float(node.value) else: # It's an integer new_val = (int(node.value) & ((1 << (8 * new_type.size)) - 1)) # Mask it if node.value >= 0 and node.value != new_val: errmsg.warning_conversion_lose_digits(node.lineno) node.value = new_val elif node.value < 0 and (1 << (new_type.size * 8)) + \ node.value != new_val: # Test for positive to negative coercion errmsg.warning_conversion_lose_digits(node.lineno) node.value = new_val - (1 << (new_type.size * 8)) node.type_ = new_type return node
def make_node(cls, new_type, node, lineno)
Creates a node containing the type cast of the given one. If new_type == node.type, then nothing is done, and the same node is returned. Returns None on failure (and calls syntax_error)
4.79962
4.740016
1.012575
namespace = (DOT + DOT.join(RE_DOTS.split(namespace))).rstrip(DOT) + DOT return namespace
def normalize_namespace(namespace)
Given a namespace (e.g. '.' or 'mynamespace'), returns it in normalized form. That is: - always prefixed with a dot - no trailing dots - any double dots are converted to single dot (..my..namespace => .my.namespace) - one or more dots (e.g. '.', '..', '...') are converted to '.' (Global namespace)
11.094426
18.538685
0.598447
global ORG global LEXER global MEMORY global INITS global AUTORUN_ADDR global NAMESPACE ORG = 0 # Origin of CODE INITS = [] MEMORY = None # Memory for instructions (Will be initialized with a Memory() instance) AUTORUN_ADDR = None # Where to start the execution automatically NAMESPACE = GLOBAL_NAMESPACE # Current namespace (defaults to ''). It's a prefix added to each global label gl.has_errors = 0 gl.error_msg_cache.clear()
def init()
Initializes this module
13.760198
14.376406
0.957138
if p[1] is not None: [MEMORY.add_instruction(x) for x in p[1] if isinstance(x, Asm)]
def p_program(p)
program : line
8.292068
7.893667
1.050471
if p[2] is not None: [MEMORY.add_instruction(x) for x in p[2] if isinstance(x, Asm)]
def p_program_line(p)
program : program line
9.255764
8.256156
1.121074
p[0] = None __DEBUG__("Declaring '%s%s' in %i" % (NAMESPACE, p[1], p.lineno(1))) MEMORY.declare_label(p[1], p.lineno(1), p[3])
def p_def_label(p)
line : ID EQU expr NEWLINE | ID EQU pexpr NEWLINE
6.53792
6.680948
0.978592
p[0] = p[2] __DEBUG__("Declaring '%s%s' (value %04Xh) in %i" % (NAMESPACE, p[1], MEMORY.org, p.lineno(1))) MEMORY.declare_label(p[1], p.lineno(1))
def p_line_label_asm(p)
line : LABEL asms NEWLINE
9.360318
8.316343
1.125533
if p[2] in ('H', 'L') and p[4] in ('IXH', 'IXL', 'IYH', 'IYL'): p[0] = None error(p.lineno(0), "Unexpected token '%s'" % p[4]) else: p[0] = Asm(p.lineno(1), 'LD %s,%s' % (p[2], p[4]))
def p_asm_ld8(p)
asm : LD reg8 COMMA reg8_hl | LD reg8_hl COMMA reg8 | LD reg8 COMMA reg8 | LD SP COMMA HL | LD SP COMMA reg16i | LD A COMMA reg8 | LD reg8 COMMA A | LD reg8_hl COMMA A | LD A COMMA reg8_hl | LD A COMMA A | LD A COMMA I | LD I COMMA A | LD A COMMA R | LD R COMMA A | LD A COMMA reg8i | LD reg8i COMMA A | LD reg8 COMMA reg8i | LD reg8i COMMA regBCDE | LD reg8i COMMA reg8i
3.58716
3.629295
0.98839
p[0] = None for label, line in p[2]: __DEBUG__("Setting label '%s' as local at line %i" % (label, line)) MEMORY.set_label(label, line, local=True)
def p_LOCAL(p)
asm : LOCAL id_list
7.88978
7.053269
1.118599
error(p.lineno(1), "too many arguments for DEFS") if len(p[2]) < 2: num = Expr.makenode(Container(0, p.lineno(1))) # Defaults to 0 p[2] = p[2] + (num,) p[0] = Asm(p.lineno(1), 'DEFS', p[2])
def p_DEFS(p): # Define bytes if len(p[2]) > 2
asm : DEFS number_list
6.057636
5.476167
1.106182
expr = p[4] if p[3] == '-': expr = Expr.makenode(Container('-', p.lineno(3)), expr) p[0] = ('(%s+N)' % p[2], expr)
def p_ind8_I(p)
reg8_I : LP IX PLUS expr RP | LP IX MINUS expr RP | LP IY PLUS expr RP | LP IY MINUS expr RP | LP IX PLUS pexpr RP | LP IX MINUS pexpr RP | LP IY PLUS pexpr RP | LP IY MINUS pexpr RP
11.07066
10.595041
1.044891
global NAMESPACE NAMESPACE = normalize_namespace(p[2]) __DEBUG__('Setting namespace to ' + (NAMESPACE.rstrip(DOT) or DOT), level=1)
def p_namespace(p)
asm : NAMESPACE ID
18.82749
18.138466
1.037987
align = p[2].eval() if align < 2: error(p.lineno(1), "ALIGN value must be greater than 1") return MEMORY.set_org(MEMORY.org + (align - MEMORY.org % align) % align, p.lineno(1))
def p_align(p)
asm : ALIGN expr | ALIGN pexpr
6.441348
5.870121
1.097311
try: fname = zxbpp.search_filename(p[2], p.lineno(2), local_first=True) if not fname: p[0] = None return with api.utils.open_file(fname, 'rb') as f: filecontent = f.read() except IOError: error(p.lineno(2), "cannot read file '%s'" % p[2]) p[0] = None return p[0] = Asm(p.lineno(1), 'DEFB', filecontent)
def p_incbin(p)
asm : INCBIN STRING
5.219055
4.823781
1.081943
s = 'LD %s,N' % p[2] if p[2] in REGS16: s += 'N' p[0] = Asm(p.lineno(1), s, p[4])
def p_LD_reg_val(p)
asm : LD reg8 COMMA expr | LD reg8 COMMA pexpr | LD reg16 COMMA expr | LD reg8_hl COMMA expr | LD A COMMA expr | LD SP COMMA expr | LD reg8i COMMA expr
7.190919
6.936251
1.036715
s = 'JP ' if p[2] == '(HL)': s += p[2] else: s += '(%s)' % p[3] p[0] = Asm(p.lineno(1), s)
def p_JP_hl(p)
asm : JP reg8_hl | JP LP reg16i RP
4.500324
4.59757
0.978848
bit = p[2].eval() if bit < 0 or bit > 7: error(p.lineno(3), 'Invalid bit position %i. Must be in [0..7]' % bit) p[0] = None return p[0] = Asm(p.lineno(3), '%s %i,%s' % (p[1], bit, p[4]))
def p_BIT(p)
asm : bitop expr COMMA A | bitop pexpr COMMA A | bitop expr COMMA reg8 | bitop pexpr COMMA reg8 | bitop expr COMMA reg8_hl | bitop pexpr COMMA reg8_hl
4.262664
4.407153
0.967215
bit = p[2].eval() if bit < 0 or bit > 7: error(p.lineno(3), 'Invalid bit position %i. Must be in [0..7]' % bit) p[0] = None return p[0] = Asm(p.lineno(3), '%s %i,%s' % (p[1], bit, p[4][0]), p[4][1])
def p_BIT_ix(p)
asm : bitop expr COMMA reg8_I | bitop pexpr COMMA reg8_I
4.168921
4.22616
0.986456
p[4] = Expr.makenode(Container('-', p.lineno(3)), p[4], Expr.makenode(Container(MEMORY.org + 2, p.lineno(1)))) p[0] = Asm(p.lineno(1), 'JR %s,N' % p[2], p[4])
def p_jr(p)
asm : JR jr_flags COMMA expr | JR jr_flags COMMA pexpr
11.186686
10.999342
1.017032
if p[1] in ('JR', 'DJNZ'): op = 'N' p[2] = Expr.makenode(Container('-', p.lineno(1)), p[2], Expr.makenode(Container(MEMORY.org + 2, p.lineno(1)))) else: op = 'NN' p[0] = Asm(p.lineno(1), p[1] + ' ' + op, p[2])
def p_jrjp(p)
asm : JP expr | JR expr | CALL expr | DJNZ expr | JP pexpr | JR pexpr | CALL pexpr | DJNZ pexpr
7.926878
6.521864
1.215431
val = p[2].eval() if val not in (0, 8, 16, 24, 32, 40, 48, 56): error(p.lineno(1), 'Invalid RST number %i' % val) p[0] = None return p[0] = Asm(p.lineno(1), 'RST %XH' % val)
def p_rst(p)
asm : RST expr
4.043171
3.312476
1.220589
val = p[2].eval() if val not in (0, 1, 2): error(p.lineno(1), 'Invalid IM number %i' % val) p[0] = None return p[0] = Asm(p.lineno(1), 'IM %i' % val)
def p_im(p)
asm : IM expr
4.751253
3.652824
1.300707
p[0] = Expr.makenode(Container(p[2], p.lineno(2)), p[1], p[3])
def p_expr_div_expr(p)
expr : expr BAND expr | expr BOR expr | expr BXOR expr | expr PLUS expr | expr MINUS expr | expr MUL expr | expr DIV expr | expr MOD expr | expr POW expr | expr LSHIFT expr | expr RSHIFT expr | pexpr BAND expr | pexpr BOR expr | pexpr BXOR expr | pexpr PLUS expr | pexpr MINUS expr | pexpr MUL expr | pexpr DIV expr | pexpr MOD expr | pexpr POW expr | pexpr LSHIFT expr | pexpr RSHIFT expr | expr BAND pexpr | expr BOR pexpr | expr BXOR pexpr | expr PLUS pexpr | expr MINUS pexpr | expr MUL pexpr | expr DIV pexpr | expr MOD pexpr | expr POW pexpr | expr LSHIFT pexpr | expr RSHIFT pexpr | pexpr BAND pexpr | pexpr BOR pexpr | pexpr BXOR pexpr | pexpr PLUS pexpr | pexpr MINUS pexpr | pexpr MUL pexpr | pexpr DIV pexpr | pexpr MOD pexpr | pexpr POW pexpr | pexpr LSHIFT pexpr | pexpr RSHIFT pexpr
10.757346
9.196785
1.169686
p[0] = Expr.makenode(Container(int(p[1]), p.lineno(1)))
def p_expr_int(p)
expr : INTEGER
14.060744
11.193052
1.256203
p[0] = Expr.makenode(Container(MEMORY.get_label(p[1], p.lineno(1)), p.lineno(1)))
def p_expr_label(p)
expr : ID
12.459661
9.346313
1.33311
# The current instruction address p[0] = Expr.makenode(Container(MEMORY.org, p.lineno(1)))
def p_expr_addr(p)
expr : ADDR
34.728619
29.668684
1.170548
p.lexer.lineno = int(p[2]) + p.lexer.lineno - p.lineno(2)
def p_preprocessor_line_line(p)
preproc_line : _LINE INTEGER
7.148358
5.110878
1.398655
p.lexer.lineno = int(p[2]) + p.lexer.lineno - p.lineno(3) - 1 gl.FILENAME = p[3]
def p_preprocessor_line_line_file(p)
preproc_line : _LINE INTEGER STRING
9.049275
7.196752
1.257411
global MEMORY if MEMORY is None: MEMORY = Memory() parser.parse(input_, lexer=LEXER, debug=OPTIONS.Debug.value > 2) if len(MEMORY.scopes): error(MEMORY.scopes[-1], 'Missing ENDP to close this scope') return gl.has_errors
def assemble(input_)
Assembles input string, and leave the result in the MEMORY global object
13.981738
11.852637
1.179631
global AUTORUN_ADDR org, binary = MEMORY.dump() if gl.has_errors: return if binary_files is None: binary_files = [] if headless_binary_files is None: headless_binary_files = [] bin_blocks = [] for fname in binary_files: with api.utils.open_file(fname) as f: bin_blocks.append((os.path.basename(fname), f.read())) headless_bin_blocks = [] for fname in headless_binary_files: with api.utils.open_file(fname) as f: headless_bin_blocks.append(f.read()) if AUTORUN_ADDR is None: AUTORUN_ADDR = org if not progname: progname = os.path.basename(outputfname)[:10] if OPTIONS.use_loader.value: import basic # Minimalist basic tokenizer program = basic.Basic() if org > 16383: # Only for zx48k: CLEAR if below 16383 program.add_line([['CLEAR', org - 1]]) program.add_line([['LOAD', '""', program.token('CODE')]]) if OPTIONS.autorun.value: program.add_line([['RANDOMIZE', program.token('USR'), AUTORUN_ADDR]]) else: program.add_line([['REM'], ['RANDOMIZE', program.token('USR'), AUTORUN_ADDR]]) if format_ in ('tap', 'tzx'): t = {'tap': outfmt.TAP, 'tzx': outfmt.TZX}[format_]() if OPTIONS.use_loader.value: t.save_program('loader', program.bytes, line=1) # Put line 0 to protect against MERGE t.save_code(progname, org, binary) for name, block in bin_blocks: t.save_code(name, 0, block) for block in headless_bin_blocks: t.standard_block(block) t.dump(outputfname) else: with open(outputfname, 'wb') as f: f.write(bytearray(binary))
def generate_binary(outputfname, format_, progname='', binary_files=None, headless_binary_files=None)
Outputs the memory binary to the output filename using one of the given formats: tap, tzx or bin
4.625014
4.311113
1.072812
init() if OPTIONS.StdErrFileName.value: OPTIONS.stderr.value = open('wt', OPTIONS.StdErrFileName.value) asmlex.FILENAME = OPTIONS.inputFileName.value = argv[0] input_ = open(OPTIONS.inputFileName.value, 'rt').read() assemble(input_) generate_binary(OPTIONS.outputFileName.value, OPTIONS.output_file_type)
def main(argv)
This is a test and will assemble the file in argv[0]
10.248568
10.191468
1.005603
if self.asm not in ('DEFB', 'DEFS', 'DEFW'): if self.pending: tmp = self.arg # Saves current arg temporarily self.arg = tuple([0] * self.arg_num) result = super(Asm, self).bytes() self.arg = tmp # And recovers it return result return super(Asm, self).bytes() if self.asm == 'DEFB': if self.pending: return tuple([0] * self.arg_num) return tuple([x & 0xFF for x in self.argval()]) if self.asm == 'DEFS': if self.pending: N = self.arg[0] if isinstance(N, Expr): N = N.eval() return tuple([0] * N) # ?? args = self.argval() num = args[1] & 0xFF return tuple([num] * args[0]) if self.pending: # DEFW return tuple([0] * 2 * self.arg_num) result = () for i in self.argval(): x = i & 0xFFFF result += (x & 0xFF, x >> 8) return result
def bytes(self)
Returns opcodes
4.081871
3.967101
1.02893
if gl.has_errors: return [None] if self.asm in ('DEFB', 'DEFS', 'DEFW'): return tuple([x.eval() if isinstance(x, Expr) else x for x in self.arg]) self.arg = tuple([x if not isinstance(x, Expr) else x.eval() for x in self.arg]) if gl.has_errors: return [None] if self.asm.split(' ')[0] in ('JR', 'DJNZ'): # A relative jump? if self.arg[0] < -128 or self.arg[0] > 127: error(self.lineno, 'Relative jump out of range') return [None] return super(Asm, self).argval()
def argval(self)
Solve args values or raise errors if not defined yet
4.646924
4.553472
1.020523
Expr.ignore = False result = self.try_eval() Expr.ignore = True return result
def eval(self)
Recursively evals the node. Exits with an error if not resolved.
13.611155
12.331362
1.103784
item = self.symbol.item if isinstance(item, int): return item if isinstance(item, Label): if item.defined: if isinstance(item.value, Expr): return item.value.try_eval() else: return item.value else: if Expr.ignore: return None # Try to resolve into the global namespace error(self.symbol.lineno, "Undefined label '%s'" % item.name) return None try: if isinstance(item, tuple): return tuple([x.try_eval() for x in item]) if isinstance(item, list): return [x.try_eval() for x in item] if item == '-' and len(self.children) == 1: return -self.left.try_eval() try: return self.funct[item](self.left.try_eval(), self.right.try_eval()) except ZeroDivisionError: error(self.symbol.lineno, 'Division by 0') except KeyError: pass except TypeError: pass return None
def try_eval(self)
Recursively evals the node. Returns None if it is still unresolved.
3.137306
3.083608
1.017414
if self.defined: error(lineno, "label '%s' already defined at line %i" % (self.name, self.lineno)) self.value = value self.lineno = lineno self.namespace = NAMESPACE if namespace is None else namespace
def define(self, value, lineno, namespace=None)
Defines label value. It can be anything. Even an AST
3.928601
3.709082
1.059184
if not self.defined: error(lineno, "Undeclared label '%s'" % self.name) if isinstance(self.value, Expr): return self.value.eval() return self.value
def resolve(self, lineno)
Evaluates label value. Exits with error (unresolved) if value is none
4.483068
3.800873
1.179484
self.local_labels.append({}) # Add a new context self.scopes.append(lineno) __DEBUG__('Entering scope level %i at line %i' % (len(self.scopes), lineno))
def enter_proc(self, lineno)
Enters (pushes) a new context
10.433462
9.163051
1.138645
if value < 0 or value > MAX_MEM: error(lineno, "Memory ORG out of range [0 .. 65535]. Current value: %i" % value) self.index = self.ORG = value
def set_org(self, value, lineno)
Sets a new ORG value
8.155023
7.356266
1.108582
if not label.startswith(DOT): if namespace is None: namespace = NAMESPACE ex_label = namespace + label # The mangled namespace.labelname label else: if namespace is None: namespace = GLOBAL_NAMESPACE # Global namespace ex_label = label return ex_label, namespace
def id_name(label, namespace=None)
Given a name and a namespace, resolves returns the name as namespace + '.' + name. If namespace is none, the current NAMESPACE is used
6.912838
6.366064
1.085889
if byte < 0 or byte > 255: error(lineno, 'Invalid byte value %i' % byte) self.memory_bytes[self.org] = byte self.index += 1
def __set_byte(self, byte, lineno)
Sets a byte at the current location, and increments org in one. Raises an error if org > MAX_MEMORY
5.144458
3.577382
1.438051
__DEBUG__('Exiting current scope from lineno %i' % lineno) if len(self.local_labels) <= 1: error(lineno, 'ENDP in global scope (with no PROC)') return for label in self.local_labels[-1].values(): if label.local: if not label.defined: error(lineno, "Undefined LOCAL label '%s'" % label.name) return continue name = label.name _lineno = label.lineno value = label.value if name not in self.global_labels.keys(): self.global_labels[name] = label else: self.global_labels[name].define(value, _lineno) self.local_labels.pop() # Removes current context self.scopes.pop()
def exit_proc(self, lineno)
Exits current procedure. Local labels are transferred to global scope unless they have been marked as local ones. Raises an error if no current local context (stack underflow)
5.344193
4.820886
1.10855
if gl.has_errors: return __DEBUG__('%04Xh [%04Xh] ASM: %s' % (self.org, self.org - self.ORG, instr.asm)) self.set_memory_slot() self.orgs[self.org] += (instr,) for byte in instr.bytes(): self.__set_byte(byte, instr.lineno)
def add_instruction(self, instr)
This will insert an asm instruction at the current memory position in a t-uple as (mnemonic, params). It will also insert the opcodes at the memory_bytes
13.728464
13.993641
0.98105
org = min(self.memory_bytes.keys()) # Org is the lowest one OUTPUT = [] align = [] for i in range(org, max(self.memory_bytes.keys()) + 1): if gl.has_errors: return org, OUTPUT try: try: a = [x for x in self.orgs[i] if isinstance(x, Asm)] # search for asm instructions if not a: align.append(0) # Fill with ZEROes not used memory regions continue OUTPUT += align align = [] a = a[0] if a.pending: a.arg = a.argval() a.pending = False tmp = a.bytes() for r in range(len(tmp)): self.memory_bytes[i + r] = tmp[r] except KeyError: pass OUTPUT.append(self.memory_bytes[i]) except KeyError: OUTPUT.append(0) # Fill with ZEROes not used memory regions return org, OUTPUT
def dump(self)
Returns a tuple containing code ORG, and a list of OUTPUT
6.433179
5.620631
1.144565
ex_label, namespace = Memory.id_name(label, namespace) is_address = value is None if value is None: value = self.org if ex_label in self.local_labels[-1].keys(): self.local_labels[-1][ex_label].define(value, lineno) self.local_labels[-1][ex_label].is_address = is_address else: self.local_labels[-1][ex_label] = Label(ex_label, lineno, value, local, namespace, is_address) self.set_memory_slot() return self.local_labels[-1][ex_label]
def declare_label(self, label, lineno, value=None, local=False, namespace=None)
Sets a label with the given value or with the current address (org) if no value is passed. Exits with error if label already set, otherwise return the label object
3.766573
3.643061
1.033904
global NAMESPACE ex_label, namespace = Memory.id_name(label) for i in range(len(self.local_labels) - 1, -1, -1): # Downstep result = self.local_labels[i].get(ex_label, None) if result is not None: return result result = Label(ex_label, lineno, namespace=namespace) self.local_labels[-1][ex_label] = result # HINT: no namespace return result
def get_label(self, label, lineno)
Returns a label in the current context or in the global one. If the label does not exists, creates a new one and returns it.
5.354544
4.864126
1.100823
ex_label, namespace = Memory.id_name(label) if ex_label in self.local_labels[-1].keys(): result = self.local_labels[-1][ex_label] result.lineno = lineno else: result = self.local_labels[-1][ex_label] = Label(ex_label, lineno, namespace=NAMESPACE) if result.local == local: warning(lineno, "label '%s' already declared as LOCAL" % label) result.local = local return result
def set_label(self, label, lineno, local=False)
Sets a label, lineno and local flag in the current scope (even if it exist in previous scopes). If the label exist in the current scope, changes it flags. The resulting label is returned.
4.847195
4.895729
0.990086
return '\n'.join(sorted("%04X: %s" % (x.value, x.name) for x in self.global_labels.values() if x.is_address))
def memory_map(self)
Returns a (very long) string containing a memory map hex address: label
7.063956
6.064599
1.164785
''' Common subroutine for emitting array address ''' output = [] try: indirect = False if value[0] == '*': indirect = True value = value[1:] value = int(value) & 0xFFFF if indirect: output.append('ld hl, (%s)' % str(value)) else: output.append('ld hl, %s' % str(value)) except ValueError: if value[0] == '_': output.append('ld hl, %s' % str(value)) if indirect: output.append('ld c, (hl)') output.append('inc hl') output.append('ld h, (hl)') output.append('ld l, c') else: output.append('pop hl') if indirect: output.append('ld c, (hl)') output.append('inc hl') output.append('ld h, (hl)') output.append('ld l, c') output.append('call __ARRAY') REQUIRES.add('array.asm') return output
def _addr(value)
Common subroutine for emitting array address
3.282613
3.052027
1.075552
''' Loads an 8 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value. ''' output = _addr(ins.quad[2]) output.append('ld a, (hl)') output.append('push af') return output
def _aload8(ins)
Loads an 8 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value.
18.878336
6.330642
2.982057
''' Loads a 16 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value. ''' output = _addr(ins.quad[2]) output.append('ld e, (hl)') output.append('inc hl') output.append('ld d, (hl)') output.append('ex de, hl') output.append('push hl') return output
def _aload16(ins)
Loads a 16 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value.
10.800972
5.145689
2.099033
''' Load a 32 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value. ''' output = _addr(ins.quad[2]) output.append('call __ILOAD32') output.append('push de') output.append('push hl') REQUIRES.add('iload32.asm') return output
def _aload32(ins)
Load a 32 bit value from a memory address If 2nd arg. start with '*', it is always treated as an indirect value.
17.134199
7.801067
2.196392
''' Loads a floating point value from a memory address. If 2nd arg. start with '*', it is always treated as an indirect value. ''' output = _addr(ins.quad[2]) output.append('call __LOADF') output.extend(_fpush()) REQUIRES.add('iloadf.asm') return output
def _aloadf(ins)
Loads a floating point value from a memory address. If 2nd arg. start with '*', it is always treated as an indirect value.
25.860853
10.036909
2.576575
''' Loads a string value from a memory address. ''' output = _addr(ins.quad[2]) output.append('call __ILOADSTR') output.append('push hl') REQUIRES.add('loadstr.asm') return output
def _aloadstr(ins)
Loads a string value from a memory address.
18.925484
18.4589
1.025277
''' Stores 2º operand content into address of 1st operand. 1st operand is an array element. Dimensions are pushed into the stack. Use '*' for indirect store on 1st operand (A pointer to an array) ''' output = _addr(ins.quad[1]) op = ins.quad[2] indirect = op[0] == '*' if indirect: op = op[1:] immediate = op[0] == '#' if immediate: op = op[1:] if is_int(op): if indirect: if immediate: op = str(int(op) & 0xFFFF) # Truncate to 16bit pointer output.append('ld a, (%s)' % op) else: output.append('ld de, (%s)' % op) output.append('ld a, (de)') else: op = str(int(op) & 0xFF) # Truncate to byte output.append('ld (hl), %s' % op) return output elif op[0] == '_': if indirect: if immediate: output.append('ld a, (%s)' % op) # Redundant: *#_id == _id else: output.append('ld de, (%s)' % op) # *_id output.append('ld a, (de)') else: if immediate: output.append('ld a, %s' % op) # #_id else: output.append('ld a, (%s)' % op) # _id else: output.append('pop af') # tn output.append('ld (hl), a') return output
def _astore8(ins)
Stores 2º operand content into address of 1st operand. 1st operand is an array element. Dimensions are pushed into the stack. Use '*' for indirect store on 1st operand (A pointer to an array)
4.348918
3.027097
1.436663
''' Stores 2º operand content into address of 1st operand. store16 a, x => *(&a) = x Use '*' for indirect store on 1st operand. ''' output = _addr(ins.quad[1]) op = ins.quad[2] indirect = op[0] == '*' if indirect: op = op[1:] immediate = op[0] == '#' if immediate: op = op[1:] if is_int(op): op = str(int(op) & 0xFFFF) # Truncate to 16bit pointer if indirect: if immediate: output.append('ld de, (%s)' % op) else: output.append('ld de, (%s)' % op) output.append('call __LOAD_DE_DE') REQUIRES.add('lddede.asm') else: H = int(op) >> 8 L = int(op) & 0xFF output.append('ld (hl), %i' % L) output.append('inc hl') output.append('ld (hl), %i' % H) return output elif op[0] == '_': if indirect: if immediate: output.append('ld de, (%s)' % op) # redundant: *#_id == _id else: output.append('ld de, (%s)' % op) # *_id output.append('call __LOAD_DE_DE') REQUIRES.add('lddede.asm') else: if immediate: output.append('ld de, %s' % op) else: output.append('ld de, (%s)' % op) else: output.append('pop de') output.append('ld (hl), e') output.append('inc hl') output.append('ld (hl), d') return output
def _astore16(ins)
Stores 2º operand content into address of 1st operand. store16 a, x => *(&a) = x Use '*' for indirect store on 1st operand.
4.111012
3.152003
1.304254
''' Stores 2º operand content into address of 1st operand. store16 a, x => *(&a) = x ''' output = _addr(ins.quad[1]) value = ins.quad[2] if value[0] == '*': value = value[1:] indirect = True else: indirect = False try: value = int(ins.quad[2]) & 0xFFFFFFFF # Immediate? if indirect: output.append('push hl') output.append('ld hl, %i' % (value & 0xFFFF)) output.append('call __ILOAD32') output.append('ld b, h') output.append('ld c, l') # BC = Lower 16 bits output.append('pop hl') REQUIRES.add('iload32.asm') else: output.append('ld de, %i' % (value >> 16)) output.append('ld bc, %i' % (value & 0xFFFF)) except ValueError: output.append('pop bc') output.append('pop de') output.append('call __STORE32') REQUIRES.add('store32.asm') return output
def _astore32(ins)
Stores 2º operand content into address of 1st operand. store16 a, x => *(&a) = x
5.422353
4.095523
1.323971
''' Stores 2º operand content into address of 1st operand. storef16 a, x => *(&a) = x ''' output = _addr(ins.quad[1]) value = ins.quad[2] if value[0] == '*': value = value[1:] indirect = True else: indirect = False if indirect: output.append('push hl') output.extend(_f16_oper(ins.quad[2], useBC=True)) output.append('pop hl') REQUIRES.add('iload32.asm') else: output.extend(_f16_oper(ins.quad[2], useBC=True)) output.append('call __STORE32') REQUIRES.add('store32.asm') return output
def _astoref16(ins)
Stores 2º operand content into address of 1st operand. storef16 a, x => *(&a) = x
7.701566
4.937061
1.559949
''' Stores a floating point value into a memory address. ''' output = _addr(ins.quad[1]) value = ins.quad[2] if value[0] == '*': value = value[1:] indirect = True else: indirect = False if indirect: output.append('push hl') output.extend(_float_oper(ins.quad[2])) output.append('pop hl') else: output.extend(_float_oper(ins.quad[2])) output.append('call __STOREF') REQUIRES.add('storef.asm') return output
def _astoref(ins)
Stores a floating point value into a memory address.
6.074746
5.482772
1.10797
''' Stores a string value into a memory address. It copies content of 2nd operand (string), into 1st, reallocating dynamic memory for the 1st str. These instruction DOES ALLOW immediate strings for the 2nd parameter, starting with '#'. ''' output = _addr(ins.quad[1]) op = ins.quad[2] indirect = op[0] == '*' if indirect: op = op[1:] immediate = op[0] == '#' if immediate: op = op[1:] temporal = op[0] != '$' if not temporal: op = op[1:] if is_int(op): op = str(int(op) & 0xFFFF) if indirect: if immediate: # *#<addr> = ld hl, (number) output.append('ld de, (%s)' % op) else: output.append('ld de, (%s)' % op) output.append('call __LOAD_DE_DE') REQUIRES.add('lddede.asm') else: # Integer does not make sense here (unless it's a ptr) raise InvalidICError(str(ins)) output.append('ld de, (%s)' % op) elif op[0] == '_': # an identifier temporal = False # Global var is not a temporary string if indirect: if immediate: # *#_id = _id output.append('ld de, (%s)' % op) else: # *_id output.append('ld de, (%s)' % op) output.append('call __LOAD_DE_DE') REQUIRES.add('lddede.asm') else: if immediate: output.append('ld de, %s' % op) else: output.append('ld de, (%s)' % op) else: # tn output.append('pop de') if indirect: output.append('call __LOAD_DE_DE') REQUIRES.add('lddede.asm') if not temporal: output.append('call __STORE_STR') REQUIRES.add('storestr.asm') else: # A value already on dynamic memory output.append('call __STORE_STR2') REQUIRES.add('storestr2.asm') return output
def _astorestr(ins)
Stores a string value into a memory address. It copies content of 2nd operand (string), into 1st, reallocating dynamic memory for the 1st str. These instruction DOES ALLOW immediate strings for the 2nd parameter, starting with '#'.
4.899621
3.536684
1.385371
if node is None: node = cls() assert isinstance(node, SymbolARGUMENT) or isinstance(node, cls) if not isinstance(node, cls): return cls.make_node(None, node, *args) for arg in args: assert isinstance(arg, SymbolARGUMENT) node.appendChild(arg) return node
def make_node(cls, node, *args)
This will return a node with an argument_list.
4.116243
3.941766
1.044264