Articulo de referencia

Interpreter (computing)

W3sDesign Interpreter Design Pattern UML In computing , an interpreter is software that executes source code without first compiling it to machine code . An interpreted runtime ...

W3sDesign Interpreter Design Pattern UML

In computing, an interpreter is software that executessource code without first compiling it to machine code. An interpreted runtime environment differs from one that processes CPU-native executable code which requires translating source code before executing it. An interpreter may translate the source code to an intermediate format, such as bytecode. A hybrid environment may translate the bytecode to machine code via just-in-time compilation, as in the case of .NET and Java, instead of interpreting the bytecode directly.

Before the widespread adoption of interpreters, the execution of computer programs often relied on compilers, which translate and compile source code into machine code. Early runtime environments for Lisp and BASIC could parse source code directly. Thereafter, runtime environments were developed for languages (such as Perl, Raku, Python, MATLAB, and Ruby), which translated source code into an intermediate format before executing to enhance runtime performance.

Code that runs in an interpreter can be run on any platform that has a compatible interpreter. The same code can be distributed to any such platform, instead of an executable having to be built for each platform. Although each programming language is usually associated with a particular runtime environment, a language can be used in different environments. Interpreters have been constructed for languages traditionally associated with compilation, such as ALGOL, Fortran, COBOL, C and C++.

History

In the early days of computing, compilers were more commonly found and used than interpreters because hardware at that time could not support both the interpreter and interpreted code and the typical batch environment of the time limited the advantages of interpretation.[1]

Interpreters were used as early as 1952 to ease programming within the limitations of computers at the time (e.g. a shortage of program storage space, or no native support for floating point numbers). Interpreters were also used to translate between low-level machine languages, allowing code to be written for machines that were still under construction and tested on computers that already existed.[2] The first interpreted high-level language was Lisp. Lisp was first implemented by Steve Russell on an IBM 704 computer. Russell had read John McCarthy's paper, "Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I", and realized (to McCarthy's surprise) that the Lisp eval function could be implemented in machine code.[3] The result was a working Lisp interpreter which could be used to run Lisp programs, or more properly, "evaluate Lisp expressions".

The development of editing interpreters was influenced by the need for interactive computing. In the 1960s, the introduction of time-sharing systems allowed multiple users to access a computer simultaneously, and editing interpreters became essential for managing and modifying code in real-time. The first editing interpreters were likely developed for mainframe computers, where they were used to create and modify programs on the fly. One of the earliest examples of an editing interpreter is the EDT (Editor and Debugger for the TECO) system, which was developed in the late 1960s for the PDP-1 computer. EDT allowed users to edit and debug programs using a combination of commands and macros, paving the way for modern text editors and interactive development environments.

Use

Notable uses for interpreters include:

Commands and scripts
Interpreters are frequently used to execute commands and scripts
Virtualization
An interpreter acts as a virtual machine to execute machine code for a hardware architecture different from the one running the interpreter.
Emulation
An interpreter (virtual machine) can emulate another computer system in order to run code written for that system.
Sandboxing
While some types of sandboxes rely on operating system protections, an interpreter (virtual machine) can offer additional control such as blocking code that violates security rules.
Self-modifying code
Self-modifying code can be implemented in an interpreted language. This relates to the origins of interpretation in Lisp and artificial intelligence research.

Efficiency

Interpretive overhead is the runtime cost of executing code via an interpreter instead of as native (compiled) code. Interpreting is slower because the interpreter executes multiple machine-code instructions for the equivalent functionality in the native code. In particular, access to variables is slower in an interpreter because the mapping of identifiers to storage locations must be done repeatedly at run-time rather than at compile time.[4] But faster development (due to factors such as shorter edit-build-run cycle) can outweigh the value of faster execution speed—especially when prototyping and testing when the edit-build-run cycle is frequent.[4][5]

An interpreter may generate an intermediate representation (IR) of the program from source code in order to achieve goals such as fast runtime performance. A compiler may also generate an IR, but the compiler generates machine code for later execution whereas the interpreter prepares to execute the program. These differing goals lead to differing IR design. Many BASIC interpreters replace keywords with single bytetokens which can be used to find the instruction in a jump table.[4] A few interpreters, such as the PBASIC interpreter, achieve even higher levels of program compaction by using a bit-oriented rather than a byte-oriented program memory structure, where commands tokens occupy perhaps 5 bits, nominally "16-bit" constants are stored in a variable-length code requiring 3, 6, 10, or 18 bits, and address operands include a "bit offset". Many BASIC interpreters can store and read back their own tokenized internal representation.

There are various compromises between the development speed when using an interpreter and the execution speed when using a compiler. Some systems (such as some Lisps) allow interpreted and compiled code to call each other and to share variables. This means that once a routine has been tested and debugged under the interpreter it can be compiled and thus benefit from faster execution while other routines are being developed.[6]

Implementation

Since the early stages of interpreting and compiling are similar, an interpreter might use the same lexical analyzer and parser as a compiler and then interpret the resulting abstract syntax tree.

Example

An expression interpreter written in C++.

importstd;using std :: runtime_error ; using std :: unique_ptr ; using std :: variant ;// tipos de datos para el árbol de sintaxis abstracta enum class Kind : char { VAR , CONST , SUM , DIFF , MULT , DIV , PLUS , MINUS , NOT };// declaración anticipada de la clase Nodo ;clase Variable { público : int * memoria ; };clase Constante { público : int valor ; };clase UnaryOperation { public : unique_ptr <Node> right ; } ;clase BinaryOperation { público : unique_ptr <Node> izquierda ; unique_ptr <Node> derecha ; } ;usando Expresión = variante < Variable , Constante , OperaciónBinaria , OperaciónUnaria > ;clase Nodo { público : Tipo tipo ; Expresión e ; };// procedimiento del intérprete [[ nodiscard ]] int executeIntExpression ( const Node & n ) { int leftValue ; int rightValue ; switch ( n -> kind ) { case Kind :: VAR : return std :: get < Variable > ( n . e ). memory ; case Kind :: CONST : return std :: get < Constant > ( n . e ). value ; case Kind :: SUM : case Kind :: DIFF : case Kind :: MULT : case Kind :: DIV : const BinaryOperation & bin = std :: get < BinaryOperation > ( n . e ); leftValue = executeIntExpression ( bin . left . get ()); rightValue = executeIntExpression ( bin . right . get ()); switch ( n . kind ) { case Kind :: SUM : return leftValue + rightValue ; case Kind :: DIFF : return leftValue - rightValue ; case Kind :: MULT : return leftValue * rightValue ; case Kind :: DIV : if ( rightValue == 0 ) { throw runtime_error ( "División por cero" ); } return leftValue / rightValue;}caseKind::PLUS:caseKind::MINUS:caseKind::NOT:constUnaryOperation&un=std::get<UnaryOperation>(n.e);rightValue=executeIntExpression(un.right.get());switch(n.kind){caseKind::PLUS:return+rightValue;caseKind::MINUS:return-rightValue;caseKind::NOT:return!rightValue;}default:std::unreachable();}}

Just-in-time compilation

Just-in-time (JIT) compilation is the process of converting an intermediate format (i.e. bytecode) to native code at runtime. As this results in native code execution, it is a method of avoiding the runtime cost of using an interpreter while maintaining some of the benefits that led to the development of interpreters.

Variations

Control table interpreter
Logic is specified as data formatted as a table.
Bytecode interpreter
Some interpreters process bytecode which is an intermediate format of logic compiled from a high-level language. For example, Emacs Lisp is compiled to bytecode which is interpreted by an interpreter. One might say that this compiled code is machine code for a virtual machine implemented by the interpreter. Such an interpreter is sometimes called a compreter.[7][8]
Threaded code interpreter
Un intérprete de código multihilo es similar a un intérprete de bytecode, pero en lugar de bytes, utiliza punteros. Cada instrucción es una palabra que apunta a una función o una secuencia de instrucciones, posiblemente seguida de un parámetro. El intérprete de código multihilo puede iterar obteniendo instrucciones y llamando a las funciones a las que apuntan, o bien obtener la primera instrucción y saltar a ella, y cada secuencia de instrucciones finaliza con una obtención y un salto a la siguiente instrucción. Un ejemplo de código multihilo es el código Forth utilizado en los sistemas Open Firmware . El lenguaje fuente se compila en "código F" (un bytecode), que luego es interpretado por una máquina virtual .
Intérprete de árbol de sintaxis abstracta
Un intérprete de árbol de sintaxis abstracta transforma el código fuente en un árbol de sintaxis abstracta (AST), luego lo interpreta directamente o lo usa para generar código nativo mediante compilación JIT. [ 9 ] En este enfoque, cada oración necesita ser analizada solo una vez. Como ventaja sobre el código de bytes, el AST conserva la estructura global del programa y las relaciones entre las instrucciones (que se pierden en una representación de código de bytes) y, cuando se comprime, proporciona una representación más compacta. [ 10 ] Por lo tanto, se ha propuesto el uso de AST como un mejor formato intermedio que el código de bytes. Sin embargo, para los intérpretes, el AST resulta en una mayor sobrecarga que un intérprete de código de bytes, debido a que los nodos relacionados con la sintaxis no realizan trabajo útil, a una representación menos secuencial (que requiere recorrer más punteros) y a la sobrecarga de visitar el árbol. [ 11 ]
Intérprete de plantillas
En lugar de implementar la ejecución del código mediante una gran sentencia switch que contiene todos los posibles bytecode, mientras opera en una pila de software o un recorrido de árbol, un intérprete de plantillas mantiene una gran matriz de bytecode (o cualquier representación intermedia eficiente) mapeada directamente a las instrucciones de máquina nativas correspondientes que pueden ejecutarse en el hardware del host como pares clave-valor (o en diseños más eficientes, direcciones directas a las instrucciones nativas), [ 12 ] [ 13 ] conocida como "Plantilla". Cuando se ejecuta el segmento de código particular, el intérprete simplemente carga o salta al mapeo de opcode en la plantilla y lo ejecuta directamente en el hardware. [ 14 ] [ 15 ] Debido a su diseño, el intérprete de plantillas se asemeja mucho a un compilador JIT en lugar de a un intérprete tradicional; sin embargo, técnicamente no es un JIT debido a que simplemente traduce el código del lenguaje a llamadas nativas un opcode a la vez en lugar de crear secuencias optimizadas de instrucciones ejecutables por la CPU a partir de todo el segmento de código. Debido al diseño simple del intérprete, que consiste en pasar las llamadas directamente al hardware en lugar de implementarlas directamente, es mucho más rápido que cualquier otro tipo, incluso que los intérpretes de bytecode, y hasta cierto punto menos propenso a errores, pero como contrapartida es más difícil de mantener debido a que el intérprete debe admitir la traducción a múltiples arquitecturas diferentes en lugar de una máquina virtual/pila independiente de la plataforma. Hasta la fecha, las únicas implementaciones de intérpretes de plantillas de lenguajes ampliamente conocidos que existen son el intérprete dentro de la implementación de referencia oficial de Java, la máquina virtual Java Sun HotSpot [ 12 ] y el intérprete Ignition en el motor de ejecución JavaScript V8 de Google .
Microcódigo
El microcódigo proporciona una capa de abstracción que actúa como intérprete de hardware, implementando el código máquina en un lenguaje de bajo nivel. [ 16 ] Separa las instrucciones de máquina de alto nivel de la electrónica subyacente , permitiendo así que dichas instrucciones se diseñen y modifiquen con mayor libertad. Además, facilita la implementación de instrucciones complejas de varios pasos, a la vez que reduce la complejidad de los circuitos informáticos.

Véase también

Referencias

  1. "Why was the first compiler written before the first interpreter?". Ars Technica. 8 November 2014. Retrieved 9 November 2014.
  2. Bennett, J. M.; Prinz, D. G.; Woods, M. L. (1952). "Interpretative sub-routines". Proceedings of the ACM National Conference, Toronto.
  3. According to what reported by Paul Graham in Hackers & Painters, p. 185, McCarthy said: "Steve Russell said, look, why don't I program this eval..., and I said to him, ho, ho, you're confusing theory with practice, this eval is intended for reading, not for computing. But he went ahead and did it. That is, he compiled the eval in my paper into IBM 704 machine code, fixing bug, and then advertised this as a Lisp interpreter, which it certainly was. So at that point Lisp had essentially the form that it has today..."
  4. 123This article is based on material taken from Interpreter at the Free On-line Dictionary of Computingprior to 1 November 2008 and incorporated under the "relicensing" terms of the GFDL, version 1.3 or later.
  5. "Compilers vs. interpreters: explanation and differences". IONOS Digital Guide. Retrieved 2022-09-16.
  6. Nanz, Sebastian; Furia, Carlo A. (May 2015). "A Comparative Study of Programming Languages in Rosetta Code". 2015 IEEE/ACM 37th IEEE International Conference on Software Engineering. pp. 778–788. arXiv:1409.0252. doi:10.1109/icse.2015.90. ISBN 978-1-4799-1934-5.
  7. Kühnel, Claus (1987) [1986]. "4. Kleincomputer - Eigenschaften und Möglichkeiten" [4. Microcomputer - Properties and possibilities]. In Erlekampf, Rainer; Mönk, Hans-Joachim (eds.). Mikroelektronik in der Amateurpraxis[Micro-electronics for the practical amateur] (in German) (3 ed.). Berlin: Militärverlag der Deutschen Demokratischen Republik, Leipzig. p. 222. ISBN 3-327-00357-2. 7469332.
  8. Heyne, R. (1984). "Basic-Compreter für U880" [BASIC compreter for U880 (Z80)]. radio-fernsehn-elektronik (in German). 1984 (3): 150–152.
  9. Representaciones intermedias de AST , Lambda the Ultimate forum
  10. Kistler, Thomas; Franz, Michael (febrero de 1999). "Una alternativa basada en árboles a los códigos de bytes de Java" (PDF) . International Journal of Parallel Programming . 27 (1): 21– 33. CiteSeerX 10.1.1.87.2257 . doi : 10.1023/A:1018740018601 . ISSN 0885-7458 . S2CID 14330985. Recuperado el 20 de diciembre de 2020 .   
  11. Surfin' Safari - Archivo del blog  » Anunciando SquirrelFish . Webkit.org (2 de junio de 2008). Consultado el 10 de agosto de 2013.
  12. ^ " openjdk/jdk" . GitHub . 18 de noviembre de 2021.
  13. "Descripción general del entorno de ejecución de HotSpot" . Openjdk.java.net . Consultado el 6 de agosto de 2022 .
  14. "Desmitificando la JVM: Variantes de la JVM, Cppinterpreter y TemplateInterpreter" . metebalci.com .
  15. "Intérprete de plantillas JVM" . ProgrammerSought .
  16. Kent, Allen; Williams, James G. (5 de abril de 1993). Enciclopedia de Ciencias de la Computación y Tecnología: Volumen 28 - Suplemento 13. Nueva York: Marcel Dekker, Inc. ISBN 0-8247-2281-7Consultado el 17 de enero de 2016 .

Fuentes

  • Aycock, J. (junio de 2003). "Una breve historia del sistema justo a tiempo". ACM Computing Surveys . 35 (2): 97– 113. CiteSeerX 10.1.1.97.3985 . doi : 10.1145/857076.857077 . S2CID 15345671 .  
  • Página de intérpretes de tarjetas IBM en la Universidad de Columbia.
  • Fundamentos teóricos para la "programación totalmente funcional" práctica (especialmente el capítulo 7). Tesis doctoral que aborda el problema de formalizar qué es un intérprete.