How programs written in interpreted languages are executed if they are never translated into machine language?

久未见 提交于 2019-12-01 18:59:19

Many interpreters, including the official PHP interpreter, actually translate the code to a byte code format before executing it for performance (and I suppose flexibility) reasons, but at its simplest, an interpreter simply goes through the code and performs the corresponding action for each statement. An extremely simple interpreter for a PHP-like language might look like this for example:

def execute_program(prog)
  for statement in prog.toplevel_statements:
    execute_statement(statement)

def execute_statement(statement):
  if statement is an echo statement:
    print( evaluate_expression(statement.argument) )
  else if statement is a for loop:
    execute_statement(statement.init)
    while evaluate_expression(statement.condition).is_truthy():
      for inner_statement in statement.body:
        execute_statement(inner_statement)
      execute_statement(statement.increment)
  else if ...

Note that a big if-else-if statement is not actually the cleanest way to go through an AST and a real interpreter would also need to keep track of scopes and a call stack to implement function calls and returns.

But at its most basic, this is what it boils down to: "If we see this kind of statement, perform this kind of action etc.".

Except for being much more complex, it isn't really any different from writing a program that responds to user commands where the user could for example type "rectangle" and then you draw a rectangle. Here the CPU also doesn't understand what "rectangle" means, but your code contains something like if user_input == rectangle: [code to draw a rectangle] and that's all you need.

Strictly speaking, the interpreter is being executed and the code that the interpreter is interpreting just determines what actions the interpreter takes. (If it was just compiled to machine code, what would you need the interpreter for?).

For example, I built an automation framework awhile back where we captured reflection metadata on what was occurring at runtime during QA tests. We serialized that metadata to JSON. The JSON was never compiled to anything - it just told the automation engine what methods to call and what parameters to pass. No machine code involved. It wouldn't be exactly correct to say that we were "executing" the JSON - we were executing the automation engine, which was then following the "directions" found in the JSON, but it was certainly interpreting the JSON.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!