如果从未将其翻译为机器语言,如何执行以解释语言编写的程序? [英] How programs written in interpreted languages are executed if they are never translated into machine language?

查看:137
本文介绍了如果从未将其翻译为机器语言,如何执行以解释语言编写的程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

计算机只能理解机器语言.那么,代言人又如何直接执行程序而又不将其翻译成机器语言呢?例如:

Computers can only understand machine language. Then how come interepreters execute a program directly without translating it into machine language? For example:

<?php
    echo "Hello, World!" ;

这是一个用PHP编写的简单的Hello World程序.当机器不知道echo是什么时,它如何在机器中执行?在这种情况下,它如何输出预期的字符串Hello,World !?

It's a simple Hello World program written in PHP. How does it execute in machine while the machine has no idea what echo is? How does it output what's expected, in this case, the string Hello, World!?

推荐答案

许多解释器,包括官方的PHP解释器,实际上都是出于性能(我想是灵活性)的原因,在执行代码之前将代码转换为字节码格式,但是在解释器最简单,它只需遍历代码并为每个语句执行相应的操作.例如,类似PHP的语言的极其简单的解释器可能看起来像这样:

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 ...

请注意,大的if-else-if语句实际上并不是通过AST的最干净的方法,并且真正的解释器还需要跟踪范围和调用堆栈以实现函数调用和返回.

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

除了更加复杂之外,它与编写响应用户命令的程序没有什么不同,在该程序中,用户可以键入矩形",然后绘制一个矩形.在这里,CPU也不了解矩形"的含义,但是您的代码包含类似if user_input == rectangle: [code to draw a rectangle]之类的东西,而这正是您所需要的.

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.

这篇关于如果从未将其翻译为机器语言,如何执行以解释语言编写的程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆