コード例 #1
0
def handle_token(token, input_stream):
    token_is_literal, parsed = is_a_literal(token)

    if token_is_literal:
        # Push literals on to the Data stack
        Data.push(parsed)
    elif token in Words.keys():
        # token is a Word -- call it!
        call_word(token)
    elif token in Memory.keys():
        # Get a variable definition or redefine existing variable
        set_or_get_variable(token, input_stream)
    elif token == "see":
        # Show a Word's definition
        show_definition(next(input_stream))
    elif token == ":":
        # Define a new Word
        define_word(input_stream)
    elif token == "?DO":
        # Execute DO loop
        doloop_body = take_tokens("?DO", "LOOP", input_stream)
        run_doloop(doloop_body)
    elif token == "BEGIN":
        # Execute WHILE loop
        whileloop_body = take_tokens("BEGIN", "WHILE", input_stream)
        run_whileloop(whileloop_body)
    elif token == "IF":
        # Handle Conditionals
        run_conditional(input_stream)
    elif token == "variable":
        # Declare the existence of a new variable in Memory
        declare_variable(next(input_stream))
    else:
        raise SyntaxError(f"""I don't know what to do with `{token}` !!!""")
コード例 #2
0
def set_or_get_variable(token, input_stream):
    next_token = next(input_stream)

    if next_token not in ("!", "@"):
        input_stream.clear()
        raise SyntaxError(
            f"""Was trying to get or set '{token}', but missing ! or @""")

    if next_token == "!":
        Memory[token] = Data.pop()
    else:  # next_token == "@"
        Data.push(Memory[token])