#!/usr/bin/env python3
#
# (c) Mit authors 1994-2020
#
# The package is distributed under the MIT/X11 License.
#
# THIS PROGRAM IS PROVIDED AS IS, WITH NO WARRANTY. USE IS AT THE USER’S
# RISK.

import argparse

from spec import Instructions
from code_util import copyright_banner, Code
from code_gen import run_fn, run_inner_fn


GENERATOR_PROGRAM = 'gen-instructions'
PURPOSE = 'Run the virtual machine main loop (naive version).'
COPYRIGHT_YEARS = '1994-2020'


# Command-line arguments.
parser = argparse.ArgumentParser(
    prog=GENERATOR_PROGRAM,
    description='Generate naive interpreter',
)
args = parser.parse_args()


# Write the output file
code = copyright_banner(GENERATOR_PROGRAM, PURPOSE, COPYRIGHT_YEARS)
code.append('''

    #include "config.h"

    #include "mit/mit.h"
    #include "mit/features.h"

    #include "run.h"


    MIT_THREAD_LOCAL mit_fn_t *mit_run = mit_run_simple;
    MIT_THREAD_LOCAL mit_uword_t mit_stack_words = 32;
'''
)

# `mit_run_simple()`.
code.extend(run_inner_fn(Instructions, 'simple', ''))
code.extend(run_fn('simple'))

code.append('')

# `mit_run_break()`, for debugging.
code.append('MIT_THREAD_LOCAL mit_fn_t *mit_break_fn = NULL;')
code.extend(run_inner_fn(Instructions, 'break', Code('''\
        if (mit_break_fn != NULL) {
            error = mit_break_fn(pc, ir, stack, stack_words, &stack_depth);
            if (error != MIT_ERROR_OK)
                THROW(error);
        }
''')))
code.extend(run_fn('break'))

print(code)
