http___en.wikipedia.org_wiki_Interpreter__software_.xml
1.1 2.1 2.2 3.1 4.1 5.1 5.2 5.3 6.1 7.1 7.2 7.3 7.4 8.1 9.1 9.2 10.1 10.2 10.3 10.4 11.1 12.1 12.2 12.3 12.4 12.5 13.1 13.2 14.1 15.1 16.1 17.1 18.1 19.1 20.1 21.1 22.1 23.1 24.1 25.1 26.1 27.1 28.1 29.1 30.1 31.1 32.1 33.1 34.1 35.1 36.1 37.1 38.1 39.1 40.1 41.1 42.1 43.1
Интерпретатор (софтуер) В компютърните науки интерпретатор е компютърна програма, която извършва последователен анализ на командите от изходния код, непосредствено ги превежда на машинен език и изпълнява. По своята същност интерпретаторът е транслатор (на английски: translator - преводач). Съдържание Интерпретатор в сравнение с компилатор и свързващ редактор(linker)[редактиране | edit source] Програмите обикновено се пишат на език от високо ниво, който трябва да бъде превърнат в машинен език, за да могат да бъдат изпълнени от процесора. Това превръщане се извършва от компилатор или от интерпретатор. За да може програмата да се изпълнява компилаторът превежда изходния код само веднъж, докато интерпретаторът извършва превода при всяко нейно стартиране. Цикъл на разработка[редактиране | edit source] По време на разработката на софтуер се извършват чести и множество промени на изходния код. Когато се използва компилатор, при всяка промяна в кода, преди програмата да може да бъде изпълнена, трябва да се изчака компилатора да транслира всички файлове с изходен код и да свърже един с друг получените файлове с двоичен код. Колкото е по-голям обемът на съответната програма толкова е по-дълго и времето за изчакване. В противовес, при използване на интерпретатор времето за изчакване е много по-малко, тъй като интерпретаторът обикновено има нужда да преведе само кода, който е променен, което изисква значително по-малко време преди промените да бъдат тествани. Гъвкавост[редактиране | edit source] Компилаторът преобразува изходния код в двоични инструкции за определена процесорна архитектура, като по този начин се намалява мобилността. Превръщането се прави само веднъж, в средата на разработчика, и след това получените файлове с машинни инструкции могат да бъдат разпространявани на потребителски компютри с необходимата процесорна архитектура, където да бъдат изпълнени без допълнителна транслация. Интерпретируемите програми могат да бъдат разпространявани като изходен код. За целта трябва да бъде преведена на конкретната потребителска машина, което отнема повече време, но прави програмното разпространение независимо от компютърната архитектура. Независимостта обаче зависи от наличието на съответната машина на подходящ интерпретатор. При това ако трябва интерпретатора да съпровожда изходната програма, цялостния процес на инсталация се усложнява в сравнение с използването на един общ изпълним файл. Ефективност[редактиране | edit source] Основният недостатък на интерпретаторите е, че когато дадена програма се интерпретира обикновено работи по-бавно от колкото би работила ако е била компилирана. Разликите в скоростта могат да варират от незабележими до значителни размери. Най-общо стартирането на програма, използвайки интерпретатор отнема повече време в сравнение с това необходимо за изпълнението на вече компилиран код. Но тази разлика може да бъде и в противоположна посока, ако се разглежда общото време необходимо за процеса на компилиране и стартиране на програмата. Това е от особено значение в процеса на създаване и тестване на кода на програмата, когато цикълът редактиране-интерпретиране-дебъгване често може да бъде значително по кратък от този на редактиране-компилиране-стартиране-дебъгване. Интерпретирането на кода е по-бавно от директното стартиране на вече компилиран код, защото интерпретаторът трябва да анализира всеки израз в програмата всеки път когато се изпълнява и чак след това да извърши необходимата операция, докато при стартиране на компилиран код само се изпълняват операциите в логическа последователност зададена при компилирането. Също така и достъпът до променливите при използване на интерпретатор е по-бавен поради непрекъснатото адресиране на идентификаторите по време на изпълнение, за разлика от това по време на компилация. Списък на някои интерпретируеми езици[редактиране | edit source] - APL: J - ASP - BASIC: thinBasic - ECMAScript: ActionScript, E4X, JavaScript, JScript - Системи за математическа обработка: GNU Octave, IDL, Mathematica, MATLAB - Euphoria - Forth - Game Maker Language - Lava - Madness Script - Perl - PHP - PostScript - Python - Lisp: Logo, Scheme - MUMPS - REXX - Ruby: JRuby - Seed7 - Smalltalk: Bistro, Dolphin Smalltalk, F-Script, Little Smalltalk, Squeak, VisualAge, VisualWorks - Скриптови езици: WebDNA - Spreadsheet: Microsoft Excel - S: R - Tcl: XOTcl - XMLmosaic Външни препратки[редактиране | edit source] - IBM Card Interpreters страница на Columbia University - Theoretical Foundations For Practical 'Totally Functional Programming' (Глава 7) Докторска дисертация третираща проблема за формализация на това какво е интерпретатор - Анимация изясняваща концептуалните разлики между интерпретатор и компилатор
1.1 2.1 2.2 3.1 4.1 5.1 6.1 6.2 6.3 6.4 7.1 7.2 7.3 8.1 9.1 10.1 11.1 12.1 13.1 14.1 15.1 16.1 17.1 18.1 18.2 18.3 19.1 20.1 21.1 21.2 21.3 21.4 21.5 22.1 22.2 23.1 23.2 24.1 24.2 24.3 24.4 25.1 25.2 26.1 26.2 27.1 28.1 28.2 28.3 28.4 28.5 28.6 28.7 28.8 28.9 29.1 30.1 30.2 30.3 31.1 31.2 31.3 31.4 32.1 32.2 32.3 33.1 34.1 34.2 34.3 34.4 35.1 35.2 35.3 36.1 36.2 36.3 36.4 36.5 36.6 37.1 37.2 38.1 39.1 40.1 41.1 42.1 42.2 42.3 42.4 42.5 43.1 44.1 45.1 45.2 45.3 46.1 47.1 48.1 48.2 48.3 48.4 49.1 50.1 51.1 51.2 52.1 52.2 52.3 53.1 53.2 53.3 53.4 54.1 54.2 54.3 55.1 55.2 55.3 55.4 55.5 56.1 56.2 57.1 57.2 58.1 59.1 60.1 60.2 61.1 61.2 62.1 62.2 63.1 64.1 64.2 65.1 66.1 67.1 67.2 67.3 67.4 68.1 69.1 70.1 71.1 72.1 72.2 73.1 74.1 75.1 76.1 77.1
Interpreter (computing) In computer science, an interpreter is a computer program that directly executes, i.e. performs, instructions written in a programming or scripting language, without previously compiling them into a machine language program. An interpreter generally uses one of the following strategies for program execution: - parse the source code and perform its behavior directly - translate source code into some efficient intermediate representation and immediately execute this - explicitly execute stored precompiled code[1] made by a compiler which is part of the interpreter system Early versions of the Lisp programming language and Dartmouth BASIC would be examples of the first type. Perl, Python, MATLAB, and Ruby are examples of the second, while UCSD Pascal is an example of the third type. Source programs are compiled ahead of time and stored as machine independent code, which is then linked at run-time and executed by an interpreter and/or compiler (for JIT systems). Some systems, such as Smalltalk, contemporary versions of BASIC, Java and others may also combine two and three. While interpretation and compilation are the two main means by which programming languages are implemented, they are not mutually exclusive, as most interpreting systems also perform some translation work, just like compilers. The terms "interpreted language" or "compiled language" signify that the canonical implementation of that language is an interpreter or a compiler, respectively. A high level language is ideally an abstraction independent of particular implementations. Contents - 1 History - 2 Compilers versus interpreters - 3 Variations - 4 Applications - 5 Punched card interpreter - 6 See also - 7 Notes and references - 8 External links History[edit] 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, and realized (to McCarthy's surprise) that the Lisp eval function could be implemented in machine code.[2] The result was a working Lisp interpreter which could be used to run Lisp programs, or more properly, "evaluate Lisp expressions". Compilers versus interpreters[edit] Programs written in a high level language are either directly executed by some kind of interpreter or converted into machine code by a compiler (and assembler and linker) for the CPU to execute. While compilers (and assemblers) generally produce machine code directly executable by computer hardware, they can often (optionally) produce an intermediate form called object code. This is basically the same machine specific code but augmented with a symbol table with names and tags to make executable blocks (or modules) identifiable and relocatable. Compiled programs will typically use building blocks (functions) kept in a library of such object code modules. A linker is used to combine (pre-made) library files with the object file(s) of the application to form a single executable file. The object files that are used to generate an executable file are thus often produced at different times, and sometimes even by different languages (capable of generating the same object format). A simple interpreter written in a low level language (e.g. assembly) may have similar machine code blocks implementing functions of the high level language stored, and executed when a function's entry in a look up table points to that code. However, an interpreter written in a high level language typically uses another approach, such as generating and then walking a parse tree, or by generating and executing intermediate software-defined instructions, or both. Thus, both compilers and interpreters generally turn source code (text files) into tokens, both may (or may not) generate a parse tree, and both may generate immediate instructions (for a stack machine, quadruple code, or by other means). The basic difference is that a compiler system, including a (built in or separate) linker, generates a stand alone machine code program, while an interpreter system instead performs the actions described by the high level program. A compiler can thus make almost all the conversions from source code semantics to the machine level once and for all (i.e. until the program has to be changed) while an interpreter has to do some of this conversion work every time a statement or function is executed. However, in an efficient interpreter, much of the translation work (including analysis of types, and similar) is factored out and done only the first time a program, module, function, or even statement, is run, thus quite akin to how a compiler works. However, a compiled program still runs much faster, under most circumstances, in part because compilers are designed to optimize code, and may be given ample time for this. This is especially true for simpler high level languages without (much) dynamic data structures, checks or typing. In traditional compilation, the executable output of the linkers (.exe files or .dll files or a library, see picture) is typically relocatable when run under a general operating system, much like the object code modules are but with the difference that this relocation is done dynamically at run time, i.e. when the program is loaded for execution. On the other hand, compiled and linked programs for small embedded systems are typically statically allocated, often hard coded in a NOR flash memory, as there are often no secondary storage and no operating system in this sense. Historically, most interpreter-systems have had a self-contained editor built in. This is becoming more common also for compilers (then often called an IDE), although some programmers prefer to use an editor of their choice and run the compiler, linker and other tools manually. Development cycle[edit] During the software development cycle, programmers make frequent changes to source code. When using a compiler, each time a change is made to the source code, they must wait for the compiler to translate the altered source files and link all of the binary code files together before the program can be executed. The larger the program, the longer the wait. By contrast, a programmer using an interpreter does a lot less waiting, as the interpreter usually just needs to translate the code being worked on to an intermediate representation (or not translate it at all), thus requiring much less time before the changes can be tested. Effects are evident upon saving the source code and reloading the program. Compiled code is generally less readily debugged as editing, compiling, and linking are sequential processes that have to be conducted in the proper sequence with a proper set of commands. For this reason, many compilers also have an executive aid, known as a Make file and program. The Make file lists compiler and linker command lines and program source code files, but might take a simple command line menu input (e.g. "Make 3") which selects the third group (set) of instructions then issues the commands to the compiler, and linker feeding the specified source code files. In a WYSIWYG program, the Make groups might manifest as buttons. Distribution[edit] A compiler converts source code into binary instruction for a specific processor's architecture, thus making it less portable. This conversion is made just once, on the developer's environment, and after that the same binary can be distributed to the user's machines where it can be executed without further translation. A cross compiler can generate binary code for the user machine even if it has a different processor than the machine where the code is compiled. An interpreted program can be distributed as source code. It needs to be translated in each final machine, which takes more time but makes the program distribution independent of the machine's architecture. However, the portability of interpreted source code is dependent on the target machine actually having a suitable interpreter. If the interpreter needs to be supplied along with the source, the overall installation process is more complex than delivery of a monolithic executable since the interpreter itself is part of what need be installed. The fact that interpreted code can easily be read and copied by humans can be of concern from the point of view of copyright. However, various systems of encryption and obfuscation exist. Delivery of intermediate code, such as bytecode, has a similar effect to obfuscation, but bytecode could be decoded with a decompiler or disassembler.[citation needed] Efficiency[edit] The main disadvantage of interpreters is that when a program is interpreted, it typically runs more slowly than if it had been compiled. The difference in speeds could be tiny or great; often an order of magnitude and sometimes more. It generally takes longer to run a program under an interpreter than to run the compiled code but it can take less time to interpret it than the total time required to compile and run it. This is especially important when prototyping and testing code when an edit-interpret-debug cycle can often be much shorter than an edit-compile-run-debug cycle.[citation needed] Interpreting code is slower than running the compiled code because the interpreter must analyze each statement in the program each time it is executed and then perform the desired action, whereas the compiled code just performs the action within a fixed context determined by the compilation. This run-time analysis is known as "interpretive overhead". Access to variables is also slower in an interpreter because the mapping of identifiers to storage locations must be done repeatedly at run-time rather than at compile time.[citation needed] 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.[citation needed] Many interpreters do not execute the source code as it stands but convert it into some more compact internal form. Many BASIC interpreters replace keywords with single byte tokens which can be used to find the instruction in a jump table. 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. An interpreter might well use the same lexical analyzer and parser as the compiler and then interpret the resulting abstract syntax tree. Example data type definitions for the latter, and a toy interpreter for syntax trees obtained from C expressions are shown in the box. Regression[edit] Interpretation cannot be used as the sole method of execution: even though an interpreter can itself be interpreted and so on, a directly executed program is needed somewhere at the bottom of the stack because the code being interpreted is not, by definition, the same as the machine code that the CPU can execute.[3][4] Variations[edit] Bytecode interpreters[edit] There is a spectrum of possibilities between interpreting and compiling, depending on the amount of analysis performed before the program is executed. For example, Emacs Lisp is compiled to bytecode, which is a highly compressed and optimized representation of the Lisp source, but is not machine code (and therefore not tied to any particular hardware). This "compiled" code is then interpreted by a bytecode interpreter (itself written in C). The compiled code in this case is machine code for a virtual machine, which is implemented not in hardware, but in the bytecode interpreter. The same approach is used with the Forth code used in Open Firmware systems: the source language is compiled into "F code" (a bytecode), which is then interpreted by a virtual machine.[citation needed] Control tables - that do not necessarily ever need to pass through a compiling phase - dictate appropriate algorithmic control flow via customized interpreters in similar fashion to bytecode interpreters. Abstract Syntax Tree interpreters[edit] In the spectrum between interpreting and compiling, another approach is transforming the source code into an optimized Abstract Syntax Tree (AST) then executing the program following this tree structure, or using it to generate native code Just-In-Time.[5] In this approach, each sentence needs to be parsed just once. As an advantage over bytecode, the AST keeps the global program structure and relations between statements (which is lost in a bytecode representation), and when compressed provides a more compact representation.[6] Thus, using AST has been proposed as a better intermediate format for Just-in-time compilers than bytecode. Also, it allows to perform better analysis during runtime. However, for interpreters, an AST causes more overhead than a bytecode interpreter, because of nodes related to syntax performing no useful work, of a less sequential representation (requiring traversal of more pointers) and of overhead visiting the tree.[7] Just-in-time compilation[edit] Further blurring the distinction between interpreters, byte-code interpreters and compilation is just-in-time compilation (or JIT), a technique in which the intermediate representation is compiled to native machine code at runtime. This confers the efficiency of running native code, at the cost of startup time and increased memory use when the bytecode or AST is first compiled. Adaptive optimization is a complementary technique in which the interpreter profiles the running program and compiles its most frequently executed parts into native code. Both techniques are a few decades old, appearing in languages such as Smalltalk in the 1980s.[8] Just-in-time compilation has gained mainstream attention amongst language implementers in recent years, with Java, the .NET Framework and most modern JavaScript implementations now including JITs.[citation needed] Self-interpreter[edit] A self-interpreter is a programming language interpreter written in a programming language which can interpret itself; an example is a BASIC interpreter written in BASIC. Self-interpreters are related to self-hosting compilers. If no compiler exists for the language to be interpreted, creating a self-interpreter requires the implementation of the language in a host language (which may be another programming language or assembler). By having a first interpreter such as this, the system is bootstrapped and new versions of the interpreter can be developed in the language itself. It was in this way that Donald Knuth developed the TANGLE interpreter for the language WEB of the industrial standard TeX typesetting system. Defining a computer language is usually done in relation to an abstract machine (so-called operational semantics) or as a mathematical function (denotational semantics). A language may also be defined by an interpreter in which the semantics of the host language is given. The definition of a language by a self-interpreter is not well-founded (it cannot define a language), but a self-interpreter tells a reader about the expressiveness and elegance of a language. It also enables the interpreter to interpret its source code, the first step towards reflective interpreting. An important design dimension in the implementation of a self-interpreter is whether a feature of the interpreted language is implemented with the same feature in the interpreter's host language. An example is whether a closure in a Lisp-like language is implemented using closures in the interpreter language or implemented "manually" with a data structure explicitly storing the environment. The more features implemented by the same feature in the host language, the less control the programmer of the interpreter has; a different behavior for dealing with number overflows cannot be realized if the arithmetic operations are delegated to corresponding operations in the host language. Some languages have an elegant self-interpreter, such as Lisp or Prolog.[citation needed] Much research on self-interpreters (particularly reflective interpreters) has been conducted in the Scheme programming language, a dialect of Lisp. In general, however, any Turing-complete language allows writing of its own interpreter. Lisp is such a language, because Lisp programs are lists of symbols and other lists. XSLT is such a language, because XSLT programs are written in XML. A sub-domain of meta-programming is the writing of domain-specific languages (DSLs). Clive Gifford introduced a measure quality of self-interpreter (the eigenratio), the limit of the ratio between computer time spent running a stack of N self-interpreters and time spent to run a stack of N−1 self-interpreters as N goes to infinity. This value does not depend on the program being run. The book Structure and Interpretation of Computer Programs presents examples of meta-circular interpretation for Scheme and its dialects. Other examples of languages with a self-interpreter are Forth and Pascal. Applications[edit] - Interpreters are frequently used to execute command languages, and glue languages since each operator executed in command language is usually an invocation of a complex routine such as an editor or compiler.[citation needed] - Self-modifying code can easily be implemented in an interpreted language. This relates to the origins of interpretation in Lisp and artificial intelligence research.[citation needed] - Virtualization. Machine code intended for one hardware architecture can be run on another using a virtual machine, which is essentially an interpreter.[citation needed] - Sandboxing: An interpreter or virtual machine is not compelled to actually execute all the instructions the source code it is processing. In particular, it can refuse to execute code that violates any security constraints it is operating under.[citation needed] Punched card interpreter[edit] The term "interpreter" often referred to a piece of unit record equipment that could read punched cards and print the characters in human-readable form on the card. The IBM 550 Numeric Interpreter and IBM 557 Alphabetic Interpreter are typical examples from 1930 and 1954, respectively.[citation needed] Notes and references[edit] - ^ In this sense, the CPU is also an interpreter, of machine instructions. - ^ 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..." - ^ Theodore H. Romer, Dennis Lee, Geoffrey M. Voelker, Alec Wolman, Wayne A. Wong, Jean-Loup Baer, Brian N. Bershad, and Henry M. Levy, [1] The Structure and Performance of Interpreters - ^ Terence Parr, Johannes Luber, [2] The Difference Between Compilers and Interpreters - ^ AST intermediate representations, Lambda the Ultimate forum - ^ A Tree-Based Alternative to Java Byte-Codes, Thomas Kistler, Michael Franz - ^ Surfin' Safari - Blog Archive » Announcing SquirrelFish. Retrieved on 2013-08-10. - ^ L. Deutsch, A. Schiffman, Efficient implementation of the Smalltalk-80 system, Proceedings of 11th POPL symposium, 1984. External links[edit] - IBM Card Interpreters page at Columbia University - Theoretical Foundations For Practical 'Totally Functional Programming' (Chapter 7 especially) Doctoral dissertation tackling the problem of formalising what is an interpreter - Short animation explaining the key conceptual difference between interpreters and compilers