Instruction:
Implement a function in Python 3 to
return an instruction that evaluates to the absolute value of top of the stack.

Response:
def _abs16(ins):
    ''' Absolute value of top of the stack (16 bits in HL)
    '''
    output = _16bit_oper(ins.quad[2])
    output.append('call __ABS16')
    output.append('push hl')
    REQUIRES.add('abs16.asm')
    return output


Instruction:
Can you tell what is the following Python 3 function doing
def _shru16(ins):
    ''' Logical right shift 16bit unsigned integer.
    The result is pushed onto the stack.

    Optimizations:
      * If 2nd op is 0 then
        do nothing

      * If 2nd op is 1
        Shift Right Arithmetic
    '''
    op1, op2 = tuple(ins.quad[2:])
    if is_int(op2):
        op = int16(op2)
        if op == 0:
            return []

        output = _16bit_oper(op1)
        if op == 1:
            output.append('srl h')
            output.append('rr l')
            output.append('push hl')
            return output

        output.append('ld b, %i' % op)
    else:
        output = _8bit_oper(op2)
        output.append('ld b, a')
        output.extend(_16bit_oper(op1))

    label = tmp_label()
    output.append('%s:' % label)
    output.append('srl h')
    output.append('rr l')
    output.append('djnz %s' % label)
    output.append('push hl')
    return output

Response: Logical right shift 16bit unsigned integer.


Instruction:
Write a Python 3 script to
read a txt file and returns the content as a unicode string.

Response:
def read_txt_file(fname):
    """Reads a txt file, regardless of its encoding
    """
    encodings = ['utf-8-sig', 'cp1252']
    with open(fname, 'rb') as f:
        content = bytes(f.read())

    for i in encodings:
        try:
            result = content.decode(i)
            if six.PY2:
                result = result.encode('utf-8')
            return result
        except UnicodeDecodeError:
            pass

    global_.FILENAME = fname
    errmsg.syntax_error(1, 'Invalid file encoding. Use one of: %s' % ', '.join(encodings))
    return ''


Instruction:
Make a summary of the following Python 3 code
def open_file(fname, mode='rb', encoding='utf-8'):
    if six.PY2 or 't' not in mode:
        kwargs = {}
    else:
        kwargs = {'encoding': encoding}

    return open(fname, mode, **kwargs)

Response: A wrapper for open that supports both Python 2 and Python 3.


Instruction:
Can you generate the documentation for the following Python 3 function
def parse_int(str_num):
    str_num = (str_num or "").strip().upper()
    if not str_num:
        return None

    base = 10
    if str_num.startswith('0X'):
        base = 16
        str_num = str_num[2:]
    if str_num.endswith('H'):
        base = 16
        str_num = str_num[:-1]
    if str_num.startswith('$'):
        base = 16
        str_num = str_num[1:]

    try:
        return int(str_num, base)
    except ValueError:
        return None

Response: Given an integer number return its value or None if it could not be parsed.


Instruction:
Explain what the following Python 3 code does
def out(self, l):
        if not isinstance(l, list):
            l = [l]

        self.output.extend([int(i) & 0xFF for i in l])

Response: Adds a list of bytes to the output string


Instruction:
Make a summary of the following Python 3 code
def standard_block(self, _bytes):
        self.out(self.BLOCK_STANDARD)  # Standard block ID
        self.out(self.LH(1000))  # 1000 ms standard pause
        self.out(self.LH(len(_bytes) + 1))  # + 1 for CHECKSUM byte

        checksum = 0
        for i in _bytes:
            checksum ^= (int(i) & 0xFF)
            self.out(i)

        self.out(checksum)

Response: Adds a standard block of bytes to the internal buffer.


Instruction:
Can you create a Python 3 function that
saves the TZX file to fname

Response:
def dump(self, fname):
        """ Saves TZX file to fname
        """
        with open(fname, 'wb') as f:
            f.write(self.output)


Instruction:
Implement a Python 3 function for
saving a generic standard header for the current object.

Response:
def save_header(self, _type, title, length, param1, param2):
        """ Saves a generic standard header:
                type:   00 -- Program
                        01 -- Number Array
                        02 -- Char Array
                        03 -- Code

                title:  Name title.
                        Will be truncated to 10 chars and padded
                        with spaces if necessary.

                length: Data length (in bytes) of the next block.

                param1: For CODE -> Start address.
                        For PROGRAM -> Autostart line (>=32768 for no autostart)
                        For DATA (02 & 03) high byte of param1 have the variable name.

                param2: For CODE -> 32768
                        For PROGRAM -> Start of the Variable area relative to program Start (Length of basic in bytes)
                        For DATA (02 & 03) NOT USED

        Info taken from: http://www.worldofspectrum.org/faq/reference/48kreference.htm#TapeDataStructure
        """
        title = (title + 10 * ' ')[:10]  # Padd it with spaces
        title_bytes = [ord(i) for i in title]  # Convert it to bytes

        _bytes = [self.BLOCK_TYPE_HEADER, _type] + title_bytes + self.LH(length) + self.LH(param1) + self.LH(param2)
        self.standard_block(_bytes)


Instruction:
Explain what the following Python 3 code does
def standard_bytes_header(self, title, addr, length):
        self.save_header(self.HEADER_TYPE_CODE, title, length, param1=addr, param2=32768)

Response: Generates a standard header block of CODE type


Instruction:
Can you generate a brief explanation for the following Python 3 code
def standard_program_header(self, title, length, line=32768):
        self.save_header(self.HEADER_TYPE_BASIC, title, length, param1=line, param2=length)

Response: Generates a standard header block of PROGRAM type


Instruction:
Can you write a function in Python 3 where it
saves the given bytes as code.

Response:
def save_code(self, title, addr, _bytes):
        """ Saves the given bytes as code. If bytes are strings,
        its chars will be converted to bytes
        """
        self.standard_bytes_header(title, addr, len(_bytes))
        _bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in _bytes]  # & 0xFF truncates to bytes
        self.standard_block(_bytes)


Instruction:
Here you have a function in Python 3, explain what it does
def save_program(self, title, bytes, line=32768):
        self.standard_program_header(title, len(bytes), line)
        bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in bytes]  # & 0xFF truncates to bytes
        self.standard_block(bytes)

Response: Saves the given bytes as a BASIC program.


Instruction:
Create a Python 3 function to
create a node for a string slice.

Response:
def make_node(cls, lineno, s, lower, upper):
        """ Creates a node for a string slice. S is the string expression Tree.
        Lower and upper are the bounds, if lower & upper are constants, and
        s is also constant, then a string constant is returned.

        If lower > upper, an empty string is returned.
        """
        if lower is None or upper is None or s is None:
            return None

        if not check_type(lineno, Type.string, s):
            return None

        lo = up = None
        base = NUMBER(api.config.OPTIONS.string_base.value, lineno=lineno)
        lower = TYPECAST.make_node(gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE],
                                   BINARY.make_node('MINUS', lower, base, lineno=lineno,
                                                    func=lambda x, y: x - y), lineno)
        upper = TYPECAST.make_node(gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE],
                                   BINARY.make_node('MINUS', upper, base, lineno=lineno,
                                                    func=lambda x, y: x - y), lineno)

        if lower is None or upper is None:
            return None

        if is_number(lower):
            lo = lower.value
            if lo < gl.MIN_STRSLICE_IDX:
                lower.value = lo = gl.MIN_STRSLICE_IDX

        if is_number(upper):
            up = upper.value
            if up > gl.MAX_STRSLICE_IDX:
                upper.value = up = gl.MAX_STRSLICE_IDX

        if is_number(lower, upper):
            if lo > up:
                return STRING('', lineno)

            if s.token == 'STRING':  # A constant string? Recalculate it now
                up += 1
                st = s.value.ljust(up)  # Procrustean filled (right)
                return STRING(st[lo:up], lineno)

            # a$(0 TO INF.) = a$
            if lo == gl.MIN_STRSLICE_IDX and up == gl.MAX_STRSLICE_IDX:
                return s

        return cls(s, lower, upper, lineno)


Instruction:
Implement a Python 3 function for
returning the instruction sequence for converting from the given type to byte.

Response:
def to_byte(stype):
    """ Returns the instruction sequence for converting from
    the given type to byte.
    """
    output = []

    if stype in ('i8', 'u8'):
        return []

    if is_int_type(stype):
        output.append('ld a, l')
    elif stype == 'f16':
        output.append('ld a, e')
    elif stype == 'f':  # Converts C ED LH to byte
        output.append('call __FTOU32REG')
        output.append('ld a, l')
        REQUIRES.add('ftou32reg.asm')

    return output


Instruction:
Given the following Python 3 function, write the documentation
def to_word(stype):
    output = []  # List of instructions

    if stype == 'u8':  # Byte to word
        output.append('ld l, a')
        output.append('ld h, 0')

    elif stype == 'i8':  # Signed byte to word
        output.append('ld l, a')
        output.append('add a, a')
        output.append('sbc a, a')
        output.append('ld h, a')

    elif stype == 'f16':  # Must MOVE HL into DE
        output.append('ex de, hl')

    elif stype == 'f':
        output.append('call __FTOU32REG')
        REQUIRES.add('ftou32reg.asm')

    return output

Response: Returns the instruction sequence for converting the given type stored in DE HL to word ( unsigned ) HL.


Instruction:
Can you generate the documentation for the following Python 3 function
def to_fixed(stype):
    output = []  # List of instructions

    if is_int_type(stype):
        output = to_word(stype)
        output.append('ex de, hl')
        output.append('ld hl, 0')  # 'Truncate' the fixed point
    elif stype == 'f':
        output.append('call __FTOF16REG')
        REQUIRES.add('ftof16reg.asm')

    return output

Response:
Returns the instruction sequence for converting the given
    type stored in DE HL to fixed DE HL.


Instruction:
Write a Python 3 function for
returning the instruction sequence for converting the given type stored in DE HL to fixed DE HL.

Response:
def to_float(stype):
    """ Returns the instruction sequence for converting the given
    type stored in DE,HL to fixed DE,HL.
    """
    output = []  # List of instructions

    if stype == 'f':
        return []  # Nothing to do

    if stype == 'f16':
        output.append('call __F16TOFREG')
        REQUIRES.add('f16tofreg.asm')
        return output

    # If we reach this point, it's an integer type
    if stype == 'u8':
        output.append('call __U8TOFREG')
    elif stype == 'i8':
        output.append('call __I8TOFREG')
    else:
        output = to_long(stype)
        if stype in ('i16', 'i32'):
            output.append('call __I32TOFREG')
        else:
            output.append('call __U32TOFREG')

    REQUIRES.add('u32tofreg.asm')

    return output


Instruction:
Write a Python 3 function for
outputting the ending sequence

Response:
def _end(ins):
    """ Outputs the ending sequence
    """
    global FLAG_end_emitted
    output = _16bit_oper(ins.quad[1])
    output.append('ld b, h')
    output.append('ld c, l')

    if FLAG_end_emitted:
        return output + ['jp %s' % END_LABEL]

    FLAG_end_emitted = True

    output.append('%s:' % END_LABEL)
    if OPTIONS.headerless.value:
        return output + ['ret']

    output.append('di')
    output.append('ld hl, (%s)' % CALL_BACK)
    output.append('ld sp, hl')
    output.append('exx')
    output.append('pop hl')
    output.append('exx')
    output.append('pop iy')
    output.append('pop ix')
    output.append('ei')
    output.append('ret')
    output.append('%s:' % CALL_BACK)
    output.append('DEFW 0')

    return output


Instruction:
Can you generate the documentation for the following Python 3 function
def _data(ins):
    output = []
    t = ins.quad[1]
    q = eval(ins.quad[2])

    if t in ('i8', 'u8'):
        size = 'B'
    elif t in ('i16', 'u16'):
        size = 'W'
    elif t in ('i32', 'u32'):
        size = 'W'
        z = list()
        for expr in ins.quad[2]:
            z.extend(['(%s) & 0xFFFF' % expr, '(%s) >> 16' % expr])
        q = z
    elif t == 'str':
        size = "B"
        q = ['"%s"' % x.replace('"', '""') for x in q]
    elif t == 'f':
        dat_ = [api.fp.immediate_float(float(x)) for x in q]
        for x in dat_:
            output.extend(['DEFB %s' % x[0], 'DEFW %s, %s' % (x[1], x[2])])
        return output
    else:
        raise InvalidIC(ins.quad, 'Unimplemented data size %s for %s' % (t, q))

    for x in q:
        output.append('DEF%s %s' % (size, x))

    return output

Response: Defines a data item for the current object.


Instruction:
Can you tell what is the following Python 3 function doing
def _var(ins):
    output = []
    output.append('%s:' % ins.quad[1])
    output.append('DEFB %s' % ((int(ins.quad[2]) - 1) * '00, ' + '00'))

    return output

Response: Defines a memory variable.


Instruction:
Write a Python 3 function that can
define a memory space with a default CONSTANT expression

Response:
def _varx(ins):
    """ Defines a memory space with a default CONSTANT expression
    1st parameter is the var name
    2nd parameter is the type-size (u8 or i8 for byte, u16 or i16 for word, etc)
    3rd parameter is the list of expressions. All of them will be converted to the
        type required.
    """
    output = []
    output.append('%s:' % ins.quad[1])
    q = eval(ins.quad[3])

    if ins.quad[2] in ('i8', 'u8'):
        size = 'B'
    elif ins.quad[2] in ('i16', 'u16'):
        size = 'W'
    elif ins.quad[2] in ('i32', 'u32'):
        size = 'W'
        z = list()
        for expr in q:
            z.extend(['(%s) & 0xFFFF' % expr, '(%s) >> 16' % expr])
        q = z
    else:
        raise InvalidIC(ins.quad, 'Unimplemented vard size: %s' % ins.quad[2])

    for x in q:
        output.append('DEF%s %s' % (size, x))

    return output


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _vard(ins):
    output = []
    output.append('%s:' % ins.quad[1])

    q = eval(ins.quad[2])

    for x in q:
        if x[0] == '#':  # literal?
            size_t = 'W' if x[1] == '#' else 'B'
            output.append('DEF{0} {1}'.format(size_t, x.lstrip('#')))
            continue

        # must be an hex number
        x = x.upper()
        assert RE_HEXA.match(x), 'expected an hex number, got "%s"' % x
        size_t = 'B' if len(x) <= 2 else 'W'
        if x[0] > '9':  # Not a number?
            x = '0' + x
        output.append('DEF{0} {1}h'.format(size_t, x))

    return output

Response: Defines a memory space with a default set of bytes or words in hexadecimal.


Instruction:
Can you tell what is the following Python 3 function doing
def _lvarx(ins):
    output = []

    l = eval(ins.quad[3])  # List of bytes to push
    label = tmp_label()
    offset = int(ins.quad[1])
    tmp = list(ins.quad)
    tmp[1] = label
    ins.quad = tmp
    AT_END.extend(_varx(ins))

    output.append('push ix')
    output.append('pop hl')
    output.append('ld bc, %i' % -offset)
    output.append('add hl, bc')
    output.append('ex de, hl')
    output.append('ld hl, %s' % label)
    output.append('ld bc, %i' % (len(l) * YY_TYPES[ins.quad[2]]))
    output.append('ldir')

    return output

Response: Defines a local variable.


Instruction:
Create a Python 3 function to
define a local variable. 1st param is offset of the local variable. 2nd param is a list of bytes in hexadecimal.

Response:
def _lvard(ins):
    """ Defines a local variable. 1st param is offset of the local variable.
    2nd param is a list of bytes in hexadecimal.
    """
    output = []

    l = eval(ins.quad[2])  # List of bytes to push
    label = tmp_label()
    offset = int(ins.quad[1])
    tmp = list(ins.quad)
    tmp[1] = label
    ins.quad = tmp
    AT_END.extend(_vard(ins))

    output.append('push ix')
    output.append('pop hl')
    output.append('ld bc, %i' % -offset)
    output.append('add hl, bc')
    output.append('ex de, hl')
    output.append('ld hl, %s' % label)
    output.append('ld bc, %i' % len(l))
    output.append('ldir')

    return output


Instruction:
Write a Python 3 script to
translate OUT to asm.

Response:
def _out(ins):
    """ Translates OUT to asm.
    """
    output = _8bit_oper(ins.quad[2])
    output.extend(_16bit_oper(ins.quad[1]))
    output.append('ld b, h')
    output.append('ld c, l')
    output.append('out (c), a')

    return output


Instruction:
How would you implement a function in Python 3 that
translates IN to asm.

Response:
def _in(ins):
    """ Translates IN to asm.
    """
    output = _16bit_oper(ins.quad[1])
    output.append('ld b, h')
    output.append('ld c, l')
    output.append('in a, (c)')
    output.append('push af')

    return output


Instruction:
Create a Python 3 function for
loading a 32 bit value from a memory address.

Response:
def _load32(ins):
    """ Load a 32 bit value from a memory address
    If 2nd arg. start with '*', it is always treated as
    an indirect value.
    """
    output = _32bit_oper(ins.quad[2])
    output.append('push de')
    output.append('push hl')
    return output


Instruction:
Write a Python 3 function for
loading a 32 bit fixed point value from a memory address.

Response:
def _loadf16(ins):
    """ Load a 32 bit (16.16) fixed point value from a memory address
    If 2nd arg. start with '*', it is always treated as
    an indirect value.
    """
    output = _f16_oper(ins.quad[2])
    output.append('push de')
    output.append('push hl')
    return output


Instruction:
Implement a function in Python 3 to
load a floating point value from a memory address.

Response:
def _loadf(ins):
    """ Loads a floating point value from a memory address.
    If 2nd arg. start with '*', it is always treated as
    an indirect value.
    """
    output = _float_oper(ins.quad[2])
    output.extend(_fpush())
    return output


Instruction:
Here you have a function in Python 3, explain what it does
def _loadstr(ins):
    temporal, output = _str_oper(ins.quad[2], no_exaf=True)

    if not temporal:
        output.append('call __LOADSTR')
        REQUIRES.add('loadstr.asm')

    output.append('push hl')
    return output

Response: Loads a string value from a memory address.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _store8(ins):
    output = _8bit_oper(ins.quad[2])

    op = ins.quad[1]

    indirect = op[0] == '*'
    if indirect:
        op = op[1:]

    immediate = op[0] == '#'
    if immediate:
        op = op[1:]

    if is_int(op) or op[0] == '_':
        if is_int(op):
            op = str(int(op) & 0xFFFF)

        if immediate:
            if indirect:
                output.append('ld (%s), a' % op)
            else:  # ???
                output.append('ld (%s), a' % op)
        elif indirect:
            output.append('ld hl, (%s)' % op)
            output.append('ld (hl), a')
        else:
            output.append('ld (%s), a' % op)
    else:
        if immediate:
            if indirect:  # A label not starting with _
                output.append('ld hl, (%s)' % op)
                output.append('ld (hl), a')
            else:
                output.append('ld (%s), a' % op)
            return output
        else:
            output.append('pop hl')

        if indirect:
            output.append('ld e, (hl)')
            output.append('inc hl')
            output.append('ld d, (hl)')
            output.append('ld (de), a')
        else:
            output.append('ld (hl), a')

    return output

Response: Stores 2nd operand content into address of 1st operand.


Instruction:
Can you create a Python 3 function that
stores 2nd operand content into address of 1st operand.

Response:
def _store16(ins):
    """ Stores 2nd operand content into address of 1st operand.
    store16 a, x =>  *(&a) = x
    Use '*' for indirect store on 1st operand.
    """
    output = []
    output = _16bit_oper(ins.quad[2])

    try:
        value = ins.quad[1]
        indirect = False
        if value[0] == '*':
            indirect = True
            value = value[1:]

        value = int(value) & 0xFFFF
        if indirect:
            output.append('ex de, hl')
            output.append('ld hl, (%s)' % str(value))
            output.append('ld (hl), e')
            output.append('inc hl')
            output.append('ld (hl), d')
        else:
            output.append('ld (%s), hl' % str(value))
    except ValueError:
        if value[0] == '_':
            if indirect:
                output.append('ex de, hl')
                output.append('ld hl, (%s)' % str(value))
                output.append('ld (hl), e')
                output.append('inc hl')
                output.append('ld (hl), d')
            else:
                output.append('ld (%s), hl' % str(value))
        elif value[0] == '#':
            value = value[1:]
            if indirect:
                output.append('ex de, hl')
                output.append('ld hl, (%s)' % str(value))
                output.append('ld (hl), e')
                output.append('inc hl')
                output.append('ld (hl), d')
            else:
                output.append('ld (%s), hl' % str(value))
        else:
            output.append('ex de, hl')
            if indirect:
                output.append('pop hl')
                output.append('ld a, (hl)')
                output.append('inc hl')
                output.append('ld h, (hl)')
                output.append('ld l, a')
            else:
                output.append('pop hl')

            output.append('ld (hl), e')
            output.append('inc hl')
            output.append('ld (hl), d')

    return output


Instruction:
Implement a Python 3 function for
storing 2nd operand content into address of 1st operand.

Response:
def _store32(ins):
    """ Stores 2nd operand content into address of 1st operand.
    store16 a, x =>  *(&a) = x
    """
    op = ins.quad[1]

    indirect = op[0] == '*'
    if indirect:
        op = op[1:]

    immediate = op[0] == '#'  # Might make no sense here?
    if immediate:
        op = op[1:]

    if is_int(op) or op[0] == '_' or immediate:
        output = _32bit_oper(ins.quad[2], preserveHL=indirect)

        if is_int(op):
            op = str(int(op) & 0xFFFF)

        if indirect:
            output.append('ld hl, (%s)' % op)
            output.append('call __STORE32')
            REQUIRES.add('store32.asm')

            return output

        output.append('ld (%s), hl' % op)
        output.append('ld (%s + 2), de' % op)

        return output

    output = _32bit_oper(ins.quad[2], preserveHL=True)
    output.append('pop hl')

    if indirect:
        output.append('call __ISTORE32')
        REQUIRES.add('store32.asm')

        return output

    output.append('call __STORE32')
    REQUIRES.add('store32.asm')

    return output


Instruction:
Create a Python 3 function for
storing 2º operand content into address of 1st operand.

Response:
def _storef16(ins):
    """ Stores 2º operand content into address of 1st operand.
    store16 a, x =>  *(&a) = x
    """
    value = ins.quad[2]
    if is_float(value):
        val = float(ins.quad[2])  # Immediate?
        (de, hl) = f16(val)
        q = list(ins.quad)
        q[2] = (de << 16) | hl
        ins.quad = tuple(q)

    return _store32(ins)


Instruction:
Create a Python 3 function to
store a floating point value into a memory address.

Response:
def _storef(ins):
    """ Stores a floating point value into a memory address.
    """
    output = _float_oper(ins.quad[2])

    op = ins.quad[1]

    indirect = op[0] == '*'
    if indirect:
        op = op[1:]

    immediate = op[0] == '#'  # Might make no sense here?
    if immediate:
        op = op[1:]

    if is_int(op) or op[0] == '_':
        if is_int(op):
            op = str(int(op) & 0xFFFF)

        if indirect:
            output.append('ld hl, (%s)' % op)
        else:
            output.append('ld hl, %s' % op)
    else:
        output.append('pop hl')
        if indirect:
            output.append('call __ISTOREF')
            REQUIRES.add('storef.asm')

            return output

    output.append('call __STOREF')
    REQUIRES.add('storef.asm')

    return output


Instruction:
Here you have a function in Python 3, explain what it does
def _storestr(ins):
    op1 = ins.quad[1]
    indirect = op1[0] == '*'
    if indirect:
        op1 = op1[1:]

    immediate = op1[0] == '#'
    if immediate and not indirect:
        raise InvalidIC('storestr does not allow immediate destination', ins.quad)

    if not indirect:
        op1 = '#' + op1

    tmp1, tmp2, output = _str_oper(op1, ins.quad[2], no_exaf=True)

    if not tmp2:
        output.append('call __STORE_STR')
        REQUIRES.add('storestr.asm')
    else:
        output.append('call __STORE_STR2')
        REQUIRES.add('storestr2.asm')

    return output

Response: Stores a string value into a memory address.


Instruction:
How would you implement a function in Python 3 that
converts data from typeA to typeB.

Response:
def _cast(ins):
    """ Convert data from typeA to typeB (only numeric data types)
    """
    # Signed and unsigned types are the same in the Z80
    tA = ins.quad[2]  # From TypeA
    tB = ins.quad[3]  # To TypeB

    YY_TYPES[tA]  # Type sizes
    xsB = sB = YY_TYPES[tB]  # Type sizes

    output = []
    if tA in ('u8', 'i8'):
        output.extend(_8bit_oper(ins.quad[4]))
    elif tA in ('u16', 'i16'):
        output.extend(_16bit_oper(ins.quad[4]))
    elif tA in ('u32', 'i32'):
        output.extend(_32bit_oper(ins.quad[4]))
    elif tA == 'f16':
        output.extend(_f16_oper(ins.quad[4]))
    elif tA == 'f':
        output.extend(_float_oper(ins.quad[4]))
    else:
        raise errors.GenericError(
            'Internal error: invalid typecast from %s to %s' % (tA, tB))

    if tB in ('u8', 'i8'):  # It was a byte
        output.extend(to_byte(tA))
    elif tB in ('u16', 'i16'):
        output.extend(to_word(tA))
    elif tB in ('u32', 'i32'):
        output.extend(to_long(tA))
    elif tB == 'f16':
        output.extend(to_fixed(tA))
    elif tB == 'f':
        output.extend(to_float(tA))

    xsB += sB % 2  # make it even (round up)

    if xsB > 4:
        output.extend(_fpush())
    else:
        if xsB > 2:
            output.append('push de')  # Fixed or 32 bit Integer

        if sB > 1:
            output.append('push hl')  # 16 bit Integer
        else:
            output.append('push af')  # 8 bit Integer

    return output


Instruction:
How would you implement a function in Python 3 that
jumps if the top of the stack is 0 to arg ( 1 )

Response:
def _jzerof(ins):
    """ Jumps if top of the stack (40bit, float) is 0 to arg(1)
    """
    value = ins.quad[1]
    if is_float(value):
        if float(value) == 0:
            return ['jp %s' % str(ins.quad[2])]  # Always true
        else:
            return []

    output = _float_oper(value)
    output.append('ld a, c')
    output.append('or l')
    output.append('or h')
    output.append('or e')
    output.append('or d')
    output.append('jp z, %s' % str(ins.quad[2]))
    return output


Instruction:
Explain what the following Python 3 code does
def _jzerostr(ins):
    output = []
    disposable = False  # True if string must be freed from memory

    if ins.quad[1][0] == '_':  # Variable?
        output.append('ld hl, (%s)' % ins.quad[1][0])
    else:
        output.append('pop hl')
        output.append('push hl')  # Saves it for later
        disposable = True

    output.append('call __STRLEN')

    if disposable:
        output.append('ex (sp), hl')
        output.append('call __MEM_FREE')
        output.append('pop hl')
        REQUIRES.add('alloc.asm')

    output.append('ld a, h')
    output.append('or l')
    output.append('jp z, %s' % str(ins.quad[2]))
    REQUIRES.add('strlen.asm')
    return output

Response: Jumps if the top of the stack contains a NULL pointer


Instruction:
Write a Python 3 script for
jumping if top of the stack is not 0 to arg ( 1 )

Response:
def _jnzero16(ins):
    """ Jumps if top of the stack (16bit) is != 0 to arg(1)
    """
    value = ins.quad[1]
    if is_int(value):
        if int(value) != 0:
            return ['jp %s' % str(ins.quad[2])]  # Always true
        else:
            return []

    output = _16bit_oper(value)
    output.append('ld a, h')
    output.append('or l')
    output.append('jp nz, %s' % str(ins.quad[2]))
    return output


Instruction:
How would you implement a function in Python 3 that
jumps if top of the stack is!0 to arg ( 1 )

Response:
def _jnzero32(ins):
    """ Jumps if top of the stack (32bit) is !=0 to arg(1)
    """
    value = ins.quad[1]
    if is_int(value):
        if int(value) != 0:
            return ['jp %s' % str(ins.quad[2])]  # Always true
        else:
            return []

    output = _32bit_oper(value)
    output.append('ld a, h')
    output.append('or l')
    output.append('or e')
    output.append('or d')
    output.append('jp nz, %s' % str(ins.quad[2]))
    return output


Instruction:
Create a Python 3 function for
jumping if top of the stack is!0 to arg ( 1 )

Response:
def _jnzerof16(ins):
    """ Jumps if top of the stack (32bit) is !=0 to arg(1)
    Fixed Point (16.16 bit) values.
    """
    value = ins.quad[1]
    if is_float(value):
        if float(value) != 0:
            return ['jp %s' % str(ins.quad[2])]  # Always true
        else:
            return []

    output = _f16_oper(value)
    output.append('ld a, h')
    output.append('or l')
    output.append('or e')
    output.append('or d')
    output.append('jp nz, %s' % str(ins.quad[2]))
    return output


Instruction:
Can you generate the documentation for the following Python 3 function
def _jgezerou8(ins):
    output = []
    value = ins.quad[1]
    if not is_int(value):
        output = _8bit_oper(value)

    output.append('jp %s' % str(ins.quad[2]))
    return output

Response: Jumps if top of the stack is > = 0 to arg ( 1 ) Always TRUE for unsigned


Instruction:
Make a summary of the following Python 3 code
def _jgezeroi8(ins):
    value = ins.quad[1]
    if is_int(value):
        if int(value) >= 0:
            return ['jp %s' % str(ins.quad[2])]  # Always true
        else:
            return []

    output = _8bit_oper(value)
    output.append('add a, a')  # Puts sign into carry
    output.append('jp nc, %s' % str(ins.quad[2]))
    return output

Response: Jumps if top of the stack is >= 0 to arg1


Instruction:
Write a Python 3 function that can
jump if top of the stack is > = 0 to arg ( 1 ) Always TRUE for unsigned

Response:
def _jgezerou16(ins):
    """ Jumps if top of the stack (16bit) is >= 0 to arg(1)
        Always TRUE for unsigned
    """
    output = []
    value = ins.quad[1]
    if not is_int(value):
        output = _16bit_oper(value)

    output.append('jp %s' % str(ins.quad[2]))
    return output


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _jgezerou32(ins):
    output = []
    value = ins.quad[1]
    if not is_int(value):
        output = _32bit_oper(value)

    output.append('jp %s' % str(ins.quad[2]))
    return output

Response: Jumps if top of the stack is >= 0 to arg ( 1 ) Always TRUE for unsigned


Instruction:
Can you implement a function in Python 3 that
returns from a procedure or function an 8bits value

Response:
def _ret8(ins):
    """ Returns from a procedure / function an 8bits value
    """
    output = _8bit_oper(ins.quad[1])
    output.append('#pragma opt require a')
    output.append('jp %s' % str(ins.quad[2]))
    return output


Instruction:
Can you implement a function in Python 3 that
returns from a procedure or function a 16bits value

Response:
def _ret16(ins):
    """ Returns from a procedure / function a 16bits value
    """
    output = _16bit_oper(ins.quad[1])
    output.append('#pragma opt require hl')
    output.append('jp %s' % str(ins.quad[2]))
    return output


Instruction:
How would you explain what the following Python 3 function does
def _ret32(ins):
    output = _32bit_oper(ins.quad[1])
    output.append('#pragma opt require hl,de')
    output.append('jp %s' % str(ins.quad[2]))
    return output

Response: Returns from a procedure or function a 32bits value


Instruction:
Create a Python 3 function to
return from a procedure a function a Fixed Point ( 32bits ) value

Response:
def _retf16(ins):
    """ Returns from a procedure / function a Fixed Point (32bits) value
    """
    output = _f16_oper(ins.quad[1])
    output.append('#pragma opt require hl,de')
    output.append('jp %s' % str(ins.quad[2]))
    return output


Instruction:
How would you explain what the following Python 3 function does
def _retf(ins):
    output = _float_oper(ins.quad[1])
    output.append('#pragma opt require a,bc,de')
    output.append('jp %s' % str(ins.quad[2]))
    return output

Response: Returns from a procedure a Floating Point ( 40bits ) value


Instruction:
Implement a function in Python 3 to
return from a procedure or function a string pointer ( 16bits ) value

Response:
def _retstr(ins):
    """ Returns from a procedure / function a string pointer (16bits) value
    """
    tmp, output = _str_oper(ins.quad[1], no_exaf=True)

    if not tmp:
        output.append('call __LOADSTR')
        REQUIRES.add('loadstr.asm')

    output.append('#pragma opt require hl')
    output.append('jp %s' % str(ins.quad[2]))
    return output


Instruction:
Can you tell what is the following Python 3 function doing
def _call(ins):
    output = []
    output.append('call %s' % str(ins.quad[1]))

    try:
        val = int(ins.quad[2])
        if val == 1:
            output.append('push af')  # Byte
        else:
            if val > 4:
                output.extend(_fpush())
            else:
                if val > 2:
                    output.append('push de')
                if val > 1:
                    output.append('push hl')

    except ValueError:
        pass

    return output

Response: Returns a list of the return values of a function.


Instruction:
Here you have a function in Python 3, explain what it does
def _leave(ins):
    global FLAG_use_function_exit

    output = []

    if ins.quad[1] == '__fastcall__':
        output.append('ret')
        return output

    nbytes = int(ins.quad[1])  # Number of bytes to pop (params size)

    if nbytes == 0:
        output.append('ld sp, ix')
        output.append('pop ix')
        output.append('ret')

        return output

    if nbytes == 1:
        output.append('ld sp, ix')
        output.append('pop ix')
        output.append('inc sp')  # "Pops" 1 byte
        output.append('ret')

        return output

    if nbytes <= 11:  # Number of bytes it worth the hassle to "pop" off the stack
        output.append('ld sp, ix')
        output.append('pop ix')
        output.append('exx')
        output.append('pop hl')
        for i in range((nbytes >> 1) - 1):
            output.append('pop bc')  # Removes (n * 2  - 2) bytes form the stack

        if nbytes & 1:  # Odd?
            output.append('inc sp')  # "Pops" 1 byte (This should never happens, since params are always even-sized)

        output.append('ex (sp), hl')  # Place back return address
        output.append('exx')
        output.append('ret')

        return output

    if not FLAG_use_function_exit:
        FLAG_use_function_exit = True  # Use standard exit
        output.append('exx')
        output.append('ld hl, %i' % nbytes)
        output.append('__EXIT_FUNCTION:')
        output.append('ld sp, ix')
        output.append('pop ix')
        output.append('pop de')
        output.append('add hl, sp')
        output.append('ld sp, hl')
        output.append('push de')
        output.append('exx')
        output.append('ret')
    else:
        output.append('exx')
        output.append('ld hl, %i' % nbytes)
        output.append('jp __EXIT_FUNCTION')

    return output

Response: Return from a function popping N bytes from the stack and leaving the stack.


Instruction:
Can you implement a function in Python 3 that
enters a function sequence for doing a function.

Response:
def _enter(ins):
    """ Enter function sequence for doing a function start
        ins.quad[1] contains size (in bytes) of local variables
        Use '__fastcall__' as 1st parameter to prepare a fastcall
        function (no local variables).
    """
    output = []

    if ins.quad[1] == '__fastcall__':
        return output

    output.append('push ix')
    output.append('ld ix, 0')
    output.append('add ix, sp')

    size_bytes = int(ins.quad[1])

    if size_bytes != 0:
        if size_bytes < 7:
            output.append('ld hl, 0')
            output.extend(['push hl'] * (size_bytes >> 1))

            if size_bytes % 2:  # odd?
                output.append('push hl')
                output.append('inc sp')
        else:
            output.append('ld hl, -%i' % size_bytes)  # "Pushes nn bytes"
            output.append('add hl, sp')
            output.append('ld sp, hl')
            output.append('ld (hl), 0')
            output.append('ld bc, %i' % (size_bytes - 1))
            output.append('ld d, h')
            output.append('ld e, l')
            output.append('inc de')
            output.append('ldir')  # Clear with ZEROs

    return output


Instruction:
How would you code a function in Python 3 to
push a 32bit param into the stack

Response:
def _param32(ins):
    """ Pushes 32bit param into the stack
    """
    output = _32bit_oper(ins.quad[1])
    output.append('push de')
    output.append('push hl')
    return output


Instruction:
Create a Python 3 function to
push 32bit fixed point param into the stack

Response:
def _paramf16(ins):
    """ Pushes 32bit fixed point param into the stack
    """
    output = _f16_oper(ins.quad[1])
    output.append('push de')
    output.append('push hl')
    return output


Instruction:
Write a Python 3 script for
pushing 40bit float param into the stack

Response:
def _paramf(ins):
    """ Pushes 40bit (float) param into the stack
    """
    output = _float_oper(ins.quad[1])
    output.extend(_fpush())
    return output


Instruction:
Implement a Python 3 function for
copying a block of memory from param 2 addrto param 1 addr.

Response:
def _memcopy(ins):
    """ Copies a block of memory from param 2 addr
    to param 1 addr.
    """
    output = _16bit_oper(ins.quad[3])
    output.append('ld b, h')
    output.append('ld c, l')
    output.extend(_16bit_oper(ins.quad[1], ins.quad[2], reversed=True))
    output.append('ldir')  # ***

    return output


Instruction:
How would you explain what the following Python 3 function does
def convertToBool():
    if not OPTIONS.strictBool.value:
        return []

    REQUIRES.add('strictbool.asm')

    result = []
    result.append('pop af')
    result.append('call __NORMALIZE_BOOLEAN')
    result.append('push af')

    return result

Response: Convert a byte value to boolean


Instruction:
Given the following Python 3 function, write the documentation
def emit_end(MEMORY=None):
    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

Response: This function is used to emit the end of the current memory area.


Instruction:
How would you code a function in Python 3 to
begin converting each quad instruction to asm by iterating over the "mem" array, and called its associated function. Each function returns an array of ASM instructions which will be appended to the 'output' array

Response:
def emit(mem):
    """ Begin converting each quad instruction to asm
    by iterating over the "mem" array, and called its
    associated function. Each function returns an array of
    ASM instructions which will be appended to the
    'output' array
    """

    def output_join(output, new_chunk):
        """ Extends output instruction list
        performing a little peep-hole optimization
        """
        changed = True and OPTIONS.optimization.value > 0  # Only enter here if -O0 was not set

        while changed and new_chunk:
            if output:
                a1 = output[-1]  # Last output instruction
                i1 = inst(a1)
                o1 = oper(a1)
            else:
                a1 = i1 = o1 = None

            if len(output) > 1:
                a0 = output[-2]
                i0 = inst(a0)
                o0 = oper(a0)
            else:
                a0 = i0 = o0 = None

            a2 = new_chunk[0]  # Fist new output instruction
            i2 = inst(a2)
            o2 = oper(a2)

            if OPT00 and i2[-1] == ':':
                # Ok, a2 is a label
                # check if the above starts with jr / jp
                if i1 in ('jp', 'jr') and o1[0] == i2[:-1]:
                    # Ok remove the above instruction
                    output.pop()
                    changed = True
                    continue

            if OPT01 and i1 == 'push' and i2 == 'pop' and o1[0] == o2[0]:
                # Ok, we have a push/pop sequence which refers to
                # the same register pairs
                # Ok, remove these instructions (both)
                output.pop()
                new_chunk = new_chunk[1:]
                changed = True
                continue

            if (
                OPT03 and
                (i1 == 'sbc' and
                 o1[0] == o1[1] == 'a' and
                 i2 == 'or' and
                 o2[0] == 'a' and
                 len(new_chunk) > 1)
            ):
                a3 = new_chunk[1]
                i3 = inst(a3)
                o3 = oper(a3)
                c = condition(a3)
                if i3 in ('jp', 'jr') and c in ('z', 'nz'):
                    c = 'nc' if c == 'z' else 'c'
                    changed = True
                    output.pop()
                    new_chunk.pop(0)
                    new_chunk[0] = '%s %s, %s' % (i3, c, o3[0])
                    continue

            if OPT04 and i1 == 'push' and i2 == 'pop':
                if 'af' in (o1[0], o2[0]):
                    output.pop()
                    new_chunk[0] = 'ld %s, %s' % (o2[0][0], o1[0][0])
                    changed = True
                    continue

                if o1[0] in ('hl', 'de') and o2[0] in ('hl', 'de'):
                    # push hl; push de; pop hl; pop de || push de; push hl; pop de; pop hl => ex de, hl
                    if len(new_chunk) > 1 and len(output) > 1 and oper(new_chunk[1])[0] == o1[0] and \
                            o2[0] == oper(output[-2])[0] and \
                            inst(output[-2]) == 'push' and inst(new_chunk[1]) == 'pop':
                        output.pop()
                        new_chunk.pop(0)
                        new_chunk.pop(0)
                        output[-1] = 'ex de, hl'
                        changed = True
                        continue

                    # push hl; pop de || push de ; pop hl
                    if len(new_chunk) > 1 and inst(new_chunk[1]) in ('pop', 'ld') and oper(new_chunk[1])[0] == o1[0]:
                        output.pop()
                        new_chunk[0] = 'ex de, hl'
                        changed = True
                        continue

                if o1[0] not in ('ix', 'iy') and o2[0] not in ('ix', 'iy'):
                    # Change push XX, pop YY sequence with ld Yh, Xl; ld Yl, Xl
                    output.pop()
                    new_chunk = ['ld %s, %s' % (o2[0][0], o1[0][0])] + new_chunk
                    new_chunk[1] = 'ld %s, %s' % (o2[0][1], o1[0][1])
                    changed = True
                    continue

            # ex af, af'; ex af, af' => <nothing>
            # ex de, hl ; ex de, hl  => <nothing>
            if OPT16 and i1 == i2 == 'ex' and o1 == o2:
                output.pop()
                new_chunk.pop(0)
                changed = True
                continue

            # Tries to optimize:
            # jp <condition>, LABEL
            # jp OTHER
            # LABEL:
            # into
            # JP !<condition>, OTHER
            # LABEL:
            if OPT17 and len(output) > 1:
                if i0 == i1 == 'jp' \
                        and i2[-1] == ':' \
                        and condition(a0) in {'c', 'nc', 'z', 'nz'} \
                        and condition(a1) is None \
                        and a2[:-1] in o0:
                    output.pop()
                    output.pop()
                    new_chunk = ['jp %s, %s' % ({'c': 'nc',
                                                 'z': 'nz',
                                                 'nc': 'c',
                                                 'nz': 'z'}[condition(a0)], o1[0])] + new_chunk
                    changed = True
                    continue

            # Tries to optimize a == b for U/Integers
            # call __EQ16
            # or a
            # jp nz, ...
            # into:
            # or a
            # sbc hl, de
            # jp z, ...
            if OPT18 and i1 == 'call' and o1[0] == '__EQ16' \
                    and i2 in {'or', 'and'} and o2[0] == 'a' \
                    and len(new_chunk) > 1:
                a3 = new_chunk[1]
                i3 = inst(a3)
                c3 = condition(a3)
                if i3 == 'jp' and c3 in {'z', 'nz'}:
                    cond = 'z' if c3 == 'nz' else 'nz'
                    new_chunk[1] = 'jp %s, %s' % (cond, oper(a3)[0])
                    output.pop()
                    new_chunk.insert(1, 'sbc hl, de')
                    changed = True
                    continue

            # Tries to optimize a == b for U/Bytes
            # sub N
            # sub 1
            # jp nc, __LABEL
            # into:
            # sub N
            # or a
            # jp nz, __LABEL
            if OPT19 and i1 == 'sub' and '1' in o1 and i2 == 'jp' and len(output) > 1:
                c2 = condition(new_chunk[0])
                if c2 in {'c', 'nc'}:
                    cond = 'z' if c2 == 'c' else 'nz'
                    new_chunk[0] = 'jp %s, %s' % (cond, o2[0])
                    if i0 in ('sub', 'dec'):
                        output.pop()
                    else:
                        output[-1] = 'or a'
                    changed = True
                    continue

            # Removes useless or a from sequence:
            # sub X
            # or a
            # jp z/nz ...
            if OPT21 and i1 == 'sub' and i2 in {'or', 'and'} and o2[0] == 'a':
                new_chunk.pop(0)
                changed = True
                continue

            # Converts:
            # ld a, (ix +/- n)
            # ld r, a
            # pop af
            # Into:
            # pop af
            # ld r, (ix +/- n)
            if OPT22 and len(output) > 1 and i1 == 'ld' and o1[0] in 'bcdehl' and o1[1] == 'a' and \
                    (i2, o2) == ('pop', ['af', 'sp']):
                if (i0, o0[:1]) == ('ld', ['a']) and RE_IX_IDX.match(o0[1]):
                    output.pop()  # Removes ld r, a
                    output.pop()  # Removes ld a, (ix + n)
                    new_chunk.insert(1, 'ld %s, %s' % (o1[0], o0[1]))  # Inserts 'ld r, (ix + n)' after 'pop af'
                    changed = True
                    continue

            # Converts:
            # ld hl, (NN) | ld hl, NN | pop hl
            # ld b, h
            # ld c, l
            # in a, (c)
            # Into:
            # ld bc, (NN) | ld bc, NN | pop bc
            # in a, (c)
            if OPT23 and len(new_chunk) > 3 and inst(new_chunk[3]) == 'in':
                ia = inst(new_chunk[1])
                oa = oper(new_chunk[1])
                ib = inst(new_chunk[2])
                ob = oper(new_chunk[2])
                if (ia, oa[0], oa[1], ib, ob[0], ob[1]) == ('ld', 'b', 'h', 'ld', 'c', 'l'):
                    ii = inst(new_chunk[0])
                    oi = oper(new_chunk[0])
                    if ii in ('pop', 'ld') and oi[0] == 'hl':
                        new_chunk[0] = ii + ' ' + 'bc' + (', %s' % oi[1] if ii == 'ld' else '')
                        new_chunk.pop(1)
                        new_chunk.pop(1)
                        changed = True
                        continue

            # Converts:
            # ld hl, (NN) | ld hl, NN | pop hl
            # ld b, h
            # ld c, l
            # out (c), a
            # Into:
            # ld bc, (NN) | ld bc, NN | pop bc
            # out (c), a
            if OPT23 and len(new_chunk) > 3 and inst(new_chunk[-1]) == 'out':
                ia = inst(new_chunk[-3])
                oa = oper(new_chunk[-3])
                ib = inst(new_chunk[-2])
                ob = oper(new_chunk[-2])
                if (ia, oa[0], oa[1], ib, ob[0], ob[1]) == ('ld', 'b', 'h', 'ld', 'c', 'l'):
                    ii = inst(new_chunk[-4])
                    oi = oper(new_chunk[-4])
                    if ii in ('pop', 'ld') and oi[0] == 'hl':
                        new_chunk[-4] = ii + ' ' + 'bc' + (', %s' % oi[1] if ii == 'ld' else '')
                        new_chunk.pop(-2)
                        new_chunk.pop(-2)
                        changed = True
                        continue

            # Converts:
            # or X | and X
            # or a | and a
            # Into:
            # or X | and X
            if OPT24 and i1 in ('and', 'or') and new_chunk[0] in ('or a', 'and a'):
                new_chunk.pop(0)
                changed = True
                continue

            # Converts:
            # ld h, X  (X != A)
            # ld a, Y
            # or/and/cp/add/sub h
            # Into:
            # ld a, Y
            # or/and/cp X
            if OPT25 and \
                    (i1 in ('cp', 'or', 'and') and o1[0] == 'h' or
                     i1 in ('sub', 'add', 'sbc', 'adc') and o1[1] == 'h') \
                    and i0 == 'ld' and o0[0] == 'a' and len(output) > 2:
                ii = inst(output[-3])
                oo = oper(output[-3])
                if i1 in ('add', 'adc', 'sbc'):
                    i1 = i1 + ' a,'
                if ii == 'ld' and oo[0] == 'h' and oo[1] != 'a':
                    output[-1] = '{0} {1}'.format(i1, oo[1])
                    output.pop(-3)
                    changed = True
                    continue

            # Converts:
            # ld a, (nn) | ld a, (ix+N)
            # inc/dec a
            # ld (nn), a | ld (ix+N), a
            # Into:
            # ld hl, _n    | <removed>
            # inc/dec (hl) | inc/dec (ix+N)
            if OPT26 and i1 in ('inc', 'dec') and o1[0] == 'a' and i0 == i2 == 'ld' and \
                    (o0[0], o0[1]) == (o2[1], o2[0]) and o0[1][0] == '(':
                new_chunk.pop(0)
                if RE_IX_IDX.match(o0[1]):
                    output[-1] = '{0} {1}'.format(i1, o0[1])
                    output.pop(-2)
                else:
                    output[-1] = '{0} (hl)'.format(i1)
                    output[-2] = 'ld hl, {0}'.format(o0[1][1:-1])
                changed = True
                continue

            # Converts:
            # ld X, Y
            # ld Y, X
            # Into:
            # ld X, Y
            if OPT02 and i1 == i2 == 'ld' and o1[0] == o2[1] and o2[0] == o1[1]:
                # This and previous instruction are LD X, Y
                # Ok, previous instruction is LD A, B and current is LD B, A. Remove this one.
                new_chunk = new_chunk[1:]
                changed = True
                continue

            # Converts:
            # ld h, X
            # or/and h
            # Into:
            # or/and X
            if OPT27 and i1 == 'ld' and o1[0] == 'h' and i2 in ('and', 'or') and o2[0] == 'h':
                output.pop()
                new_chunk[0] = '{0} {1}'.format(i2, o1[1])
                changed = True
                continue

            # Converts
            # ld a, r|(ix+/-N)|(hl)
            # ld h, a
            # ld a, XXX | pop af
            # Into:
            # ld h, r|(ix+/-N)|(hl)
            # ld a, XXX | pop af
            if OPT28 and i1 == i0 == 'ld' and o0[0] == 'a' and \
                    (o0[1] in ('a', 'b', 'c', 'd', 'e', 'h', 'l', '(hl)') or RE_IX_IDX.match(o0[1])) and \
                    (o1[0], o1[1]) == ('h', 'a') and new_chunk and (new_chunk[0] == 'pop af' or
                                                                    i2 == 'ld' and o2[0] == 'a'):

                output.pop()
                output[-1] = 'ld h, {0}'.format(o0[1])
                changed = True
                continue

            # Converts:
            # cp 0
            # Into:
            # or a
            if OPT29 and i1 == 'cp' and o1[0] == '0':
                output[-1] = 'or a'
                changed = True
                continue

            # Converts:
            # or/and X
            # jp c/nc XXX
            # Into:
            # <nothing>/jp XXX
            if OPT30 and i1 in ('and', 'or') and i2 == 'jp':
                c = condition(new_chunk[0])
                if c in ('c', 'nc'):
                    output.pop()
                    if c == 'nc':
                        new_chunk[0] = 'jp {0}'.format(o2[0])
                    else:
                        new_chunk.pop(0)
                    changed = True
                    continue

            # Converts
            # jp XXX
            # <any inst>
            # Into:
            # jp XXX
            if OPT31 and i1 == 'jp' and not condition(output[-1]) and i2 is not None and \
                    i2[-1] != ':' and new_chunk[0] not in ASMS:
                new_chunk.pop(0)
                changed = True
                continue

            # Converts:
            # call __LOADSTR
            # ld a, 1
            # call __PRINSTR
            # Into:
            # xor a
            # call __PRINTSTR
            if OPT32 and i0 == 'call' and o0[0] == '__LOADSTR' and i1 == 'ld' and tuple(o1) == ('a', '1') and \
                    i2 == 'call' and o2[0] == '__PRINTSTR':
                output.pop(-2)
                output[-1] = 'xor a'
                changed = True
                continue

            changed, new_chunk = optiblock(new_chunk)

        output.extend(new_chunk)

    output = []
    for i in mem:
        output_join(output, QUADS[i.quad[0]][1](i))
        if RE_BOOL.match(i.quad[0]):  # If it is a boolean operation convert it to 0/1 if the STRICT_BOOL flag is True
            output_join(output, convertToBool())

    changed = OPTIONS.optimization.value > 1
    while changed:
        to_remove = []

        for i, ins in enumerate(output):
            ins = ins[:-1]
            if ins not in TMP_LABELS:
                continue

            for j, ins2 in enumerate(output):
                if j == i:
                    continue
                if ins in oper(ins2):
                    break
            else:
                to_remove.append(i)

        changed = len(to_remove) > 0
        to_remove.reverse()
        for i in to_remove:
            output.pop(i)

        tmp = output
        output = []
        for i in tmp:
            output_join(output, [i])

    for i in sorted(REQUIRES):
        output.append('#include once <%s>' % i)

    return output


Instruction:
Here you have a function in Python 3, explain what it does
def t_defexpr_CONTINUE(self, t):
        r'[\\_]\r?\n'
        t.lexer.lineno += 1
        t.value = t.value[1:]
        return t

Response: r \ _ \ r?\n


Instruction:
Explain what the following Python 3 code does
def t_prepro_ID(self, t):
        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

Response: Look for reserved ID directives and parse them as ID.


Instruction:
How would you explain what the following Python 3 function does
def t_INITIAL_asm_sharp(self, t):
        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

Response: Tokenize the initial asm.


Instruction:
How would you explain what the following Python 3 function does
def put_current_line(self, prefix='', suffix=''):
        return '%s#line %i "%s"%s' % (prefix, self.lex.lineno, self.filestack[-1][0], suffix)

Response: Returns line and file for include sequences.


Instruction:
Implement a function in Python 3 to
perform and end of include.

Response:
def include_end(self):
        """ Performs and end of include.
        """
        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


Instruction:
Implement a Python 3 function for
defining input string removing current lexer.

Response:
def input(self, str, filename=''):
        """ Defines input string, removing current lexer.
        """
        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)


Instruction:
Write a Python 3 script to
return a token from the current input.

Response:
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.
        """
        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


Instruction:
How would you implement a function in Python 3 that
finds the column in the input file that contains the given token.

Response:
def find_column(self, token):
        """ Compute column:
                - token is a token instance
        """
        i = token.lexpos
        while i > 0:
            if self.input_data[i - 1] == '\n':
                break
            i -= 1

        column = token.lexpos - i + 1
        return column


Instruction:
Can you write a function in Python 3 where it
converts duration pitch to a pair of unsigned 16 bit integers and to be loaded in DE HL following the ROM listing.

Response:
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.
    """
    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


Instruction:
Explain what the following Python 3 code does
def make_node(cls, *args):
        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

Response: Creates a chain of code blocks.


Instruction:
Given the following Python 3 function, write the documentation
def t_MACROS(t):
    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)

Response: r A macro can only be used in the tree


Instruction:
Can you generate a brief explanation for the following Python 3 code
def t_string_NGRAPH(t):
    r"\\[ '.:][ '.:]"
    global __STRING

    P = {' ': 0, "'": 2, '.': 8, ':': 10}
    N = {' ': 0, "'": 1, '.': 4, ':': 5}

    __STRING += chr(128 + P[t.value[1]] + N[t.value[2]])

Response: r A string with NGram


Instruction:
Can you generate a brief explanation for the following Python 3 code
def t_asm(t):
    r'\b[aA][sS][mM]\b'

    global ASM, ASMLINENO, IN_STATE
    t.lexer.begin('asm')

    ASM = ''
    ASMLINENO = t.lexer.lineno
    IN_STATE = True

Response: r \ b [ aA][sS][mM]\b


Instruction:
Given the following Python 3 function, write the documentation
def t_ID(t):
    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

Response: t_ID is a token that is used to identify the type of the object


Instruction:
Can you generate the documentation for the following Python 3 function
def t_bin_ZERO(t):
    r'[^01]'
    t.lexer.begin('INITIAL')
    t.type = 'NUMBER'
    t.value = 0
    t.lexer.lexpos -= 1
    return t

Response: r A binary number.


Instruction:
Can you implement a function in Python 3 that
computes the column of the next non - blank line in the token instance.

Response:
def find_column(token):
    """ Compute column:
            input is the input text string
            token is a token instance
    """
    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


Instruction:
Can you implement a function in Python 3 that
returns whether the token is a label.

Response:
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.
    """
    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


Instruction:
Explain what the following Python 3 code does
def _get_val(other):
    assert isinstance(other, (numbers.Number, SymbolNUMBER, SymbolCONST))
    if isinstance(other, SymbolNUMBER):
        return other.value

    if isinstance(other, SymbolCONST):
        return other.expr.value

    return other

Response: Given a Number a Numeric Constant or a python number return its value


Instruction:
Implement a Python 3 function for
dumping a table on screen for debugging purposes

Response:
def __dumptable(self, table):
        """ Dumps table on screen
        for debugging purposes
        """
        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")


Instruction:
Can you create a Python 3 function that
visits the Return node.

Response:
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.
        """
        if len(node.children) == 2:
            node.children[1] = (yield ToVisit(node.children[1]))
        yield node


Instruction:
Can you generate the documentation for the following Python 3 function
def count(self):
        return functools.reduce(lambda x, y: x * y, (x.count for x in self.bounds))

Response: Count the number of cells in the array.


Instruction:
Write a Python 3 script to
return the size of the array cell + indexes

Response:
def memsize(self):
        """ Total array cell + indexes size
        """
        return self.size + 1 + TYPE.size(gl.BOUND_TYPE) * len(self.bounds)


Instruction:
Implement a Python 3 function for
creating a node containing the type cast of the given one.

Response:
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)
        """
        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


Instruction:
Can you create a Python 3 function that
normalizes a namespace to be a single dot - separated list of dots.

Response:
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)
    """
    namespace = (DOT + DOT.join(RE_DOTS.split(namespace))).rstrip(DOT) + DOT
    return namespace


Instruction:
How would you explain what the following Python 3 function does
def p_program(p):
    if p[1] is not None:
        [MEMORY.add_instruction(x) for x in p[1] if isinstance(x, Asm)]

Response: Program is a list of Asm objects.


Instruction:
Write a Python 3 script for
programing line is a list of instruction objects

Response:
def p_program_line(p):
    """ program : program line
    """
    if p[2] is not None:
        [MEMORY.add_instruction(x) for x in p[2] if isinstance(x, Asm)]


Instruction:
Given the following Python 3 function, write the documentation
def p_def_label(p):
    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])

Response: A label declaration is a special case.


Instruction:
How would you implement a function in Python 3 that
lines - label asms NEWLINE

Response:
def p_line_label_asm(p):
    """ line : LABEL asms NEWLINE
    """
    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))


Instruction:
Can you tell what is the following Python 3 function doing
def p_asm_ld8(p):
    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]))

Response: Parse an ASM L8 sequence.


Instruction:
Make a summary of the following Python 3 code
def p_LOCAL(p):
    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)

Response: A macro that sets the first element of the tree to be local.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def p_DEFS(p):  # Define bytes
    if len(p[2]) > 2:
        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])

Response: asm : DEFS number_list


Instruction:
Can you generate the documentation for the following Python 3 function
def p_namespace(p):
    global NAMESPACE

    NAMESPACE = normalize_namespace(p[2])
    __DEBUG__('Setting namespace to ' + (NAMESPACE.rstrip(DOT) or DOT), level=1)

Response: Set the NAMESPACE property of the asm.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def p_incbin(p):
    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)

Response: A function to parse INCBIN STRINGs.


Instruction:
Given the following Python 3 function, write the documentation
def p_JP_hl(p):
    s = 'JP '
    if p[2] == '(HL)':
        s += p[2]
    else:
        s += '(%s)' % p[3]

    p[0] = Asm(p.lineno(1), s)

Response: Asm parser for JP hl.


Instruction:
Can you generate the documentation for the following Python 3 function
def p_BIT(p):
    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]))

Response:
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


Instruction:
Can you generate a brief explanation for the following Python 3 code
def p_jrjp(p):
    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])

Response: A macro - line parser for the next statement in the JVM.


Instruction:
How would you explain what the following Python 3 function does
def p_im(p):
    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)

Response: A function to parse the IM expression.


Instruction:
Create a Python 3 function for
parsing expr DIV expr

Response:
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
    """
    p[0] = Expr.makenode(Container(p[2], p.lineno(2)), p[1], p[3])


Instruction:
Can you generate a brief explanation for the following Python 3 code
def p_expr_label(p):
    p[0] = Expr.makenode(Container(MEMORY.get_label(p[1], p.lineno(1)), p.lineno(1)))

Response: P expr_label - > expr


Instruction:
Make a summary of the following Python 3 code
def p_preprocessor_line_line_file(p):
    p.lexer.lineno = int(p[2]) + p.lexer.lineno - p.lineno(3) - 1
    gl.FILENAME = p[3]

Response: preproc_line : _LINE INTEGER STRING


Instruction:
Can you write a function in Python 3 where it
assembles input string and leave the result in the

Response:
def assemble(input_):
    """ Assembles input string, and leave the result in the
    MEMORY global object
    """
    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


Instruction:
Explain what the following Python 3 code does
def generate_binary(outputfname, format_, progname='', binary_files=None, headless_binary_files=None):
    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))

Response: Generates the memory binary file for the given format


Instruction:
Write a Python 3 function that can
return the bytes representation of the current asm.

Response:
def bytes(self):
        """ Returns opcodes
        """
        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


Instruction:
Can you generate the documentation for the following Python 3 function
def argval(self):
        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()

Response: Solve args values or raise errors if not defined yet


Instruction:
Explain what the following Python 3 code does
def try_eval(self):
        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

Response: Recursively evaluates the node. Returns None if it is still unresolved.


Instruction:
Create a Python 3 function to
define a label value. It can be anything. Even an AST

Response:
def define(self, value, lineno, namespace=None):
        """ Defines label value. It can be anything. Even an AST
        """
        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


Instruction:
Given the following Python 3 function, write the documentation
def resolve(self, lineno):
        if not self.defined:
            error(lineno, "Undeclared label '%s'" % self.name)

        if isinstance(self.value, Expr):
            return self.value.eval()

        return self.value

Response: Resolves the label value. Exits with error if value is not defined.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def enter_proc(self, lineno):
        self.local_labels.append({})  # Add a new context
        self.scopes.append(lineno)
        __DEBUG__('Entering scope level %i at line %i' % (len(self.scopes), lineno))

Response:
Adds a new context
        to the list of scope level names and adds a new context
        to the list of scope level names and the current line number.


Instruction:
Explain what the following Python 3 code does
def set_org(self, value, lineno):
        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

Response: Sets a new ORG value


Instruction:
Can you implement a function in Python 3 that
resolves a name and a namespace returns the name as namespace +. + name.

Response:
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
        """
        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


Instruction:
Make a summary of the following Python 3 code
def __set_byte(self, byte, lineno):
        if byte < 0 or byte > 255:
            error(lineno, 'Invalid byte value %i' % byte)

        self.memory_bytes[self.org] = byte
        self.index += 1

Response: Sets a byte at the current location and increments org in one.


Instruction:
Can you implement a function in Python 3 that
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)

Response:
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)
        """
        __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()


Instruction:
Can you tell what is the following Python 3 function doing
def add_instruction(self, instr):
        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)

Response: This method adds an instruction to the current ASM memory slot and adds the opcode to the memory bytes at the current memory position.


Instruction:
Create a Python 3 function for
returning a tuple containing code ORG and a list of OUTPUT ArcGIS memory regions.

Response:
def dump(self):
        """ Returns a tuple containing code ORG, and a list of OUTPUT
        """
        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


Instruction:
Explain what the following Python 3 code does
def declare_label(self, label, lineno, value=None, local=False, namespace=None):
        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]

Response: Sets a label with the given value or with the current address. Returns the label object.


Instruction:
Can you tell what is the following Python 3 function doing
def get_label(self, label, lineno):
        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

Response: Returns a label in the current context or in the global one.


Instruction:
Can you write a function in Python 3 where it
sets a label lineno and local flag in the current scope .

Response:
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.
        """
        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


Instruction:
Can you generate the documentation for the following Python 3 function
def memory_map(self):
        return '\n'.join(sorted("%04X: %s" % (x.value, x.name) for x in self.global_labels.values() if x.is_address))

Response: Returns a string containing a memory map containing a memory map containing a hex address.


Instruction:
Can you generate the documentation for the following Python 3 function
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.
    '''
    output = _addr(ins.quad[2])
    output.append('ld a, (hl)')
    output.append('push af')

    return output

Response: Load an 8 bit value from a memory address


Instruction:
Implement a Python 3 function for
loading a 16 bit value from a memory address

Response:
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.
    '''
    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


Instruction:
How would you implement a function in Python 3 that
loads a 32 bit value from a memory address.

Response:
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.
    '''
    output = _addr(ins.quad[2])

    output.append('call __ILOAD32')
    output.append('push de')
    output.append('push hl')

    REQUIRES.add('iload32.asm')

    return output


Instruction:
Create a Python 3 function for
loading a floating point value from a memory address.

Response:
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.
    '''
    output = _addr(ins.quad[2])
    output.append('call __LOADF')
    output.extend(_fpush())

    REQUIRES.add('iloadf.asm')

    return output


Instruction:
Write a Python 3 function that can
load a string value from a memory address.

Response:
def _aloadstr(ins):
    ''' 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


Instruction:
Can you create a Python 3 function that
stores 2º operand content into address of 1st operand.

Response:
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)
    '''
    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


Instruction:
Can you tell what is the following Python 3 function doing
def _astore16(ins):
    ''' 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

Response: Stores 2º operand content into address of 1st operand.


Instruction:
Create a Python 3 function to
store 2º operand content into address of 1st operand.

Response:
def _astore32(ins):
    ''' 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


Instruction:
Explain what the following Python 3 code does
def _astoref16(ins):
    ''' 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

Response: Stores 2º operand content into address of 1st operand.


Instruction:
Explain what the following Python 3 code does
def _astoref(ins):
    ''' 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

Response: Stores a floating point value into a memory address.