{
  "id": "interpreter",
  "title": "Interpreter",
  "lang": "en",
  "source_lang": "en",
  "summary": "An interpreter executes programs by evaluating source code or an intermediate representation, often working alongside compilers within a language implementation.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "Program interpreter",
    "software interpreter"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/interpreter/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/interpreter/",
      "json": "https://aiwiki.page/zh/interpreter.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "An interpreter is a program that executes instructions expressed in a programming language or another executable notation by implementing their meaning at run time. Its input may be source code, a structured representation of that source, or instructions for an abstract machine. Unlike a conventional ahead-of-time compiler, which produces a translated program for subsequent execution, an interpreter remains directly involved in carrying out the operations of the program being executed.\n\nInterpretation is an implementation technique rather than an intrinsic property of a language. A language can have interpreted, compiled, and hybrid implementations, and a single implementation can interpret some code while compiling other code. Modern language systems frequently combine parsing, compilation to intermediate instructions, interpretation, and dynamic compilation. Consequently, the familiar distinction between “interpreted languages” and “compiled languages” is useful only as shorthand for common implementation practices.\n\nInterpreters are important in interactive programming, application scripting, portable execution environments, and the implementation of dynamic language features. Their design connects language semantics with practical questions about execution speed, memory management, interoperability, isolation, and debugging. The same underlying idea also appears in instruction-set emulators and specialized execution engines, although not every program that processes a structured input is normally called an interpreter."
    },
    {
      "heading": "Interpretation, compilation, and execution",
      "text": "The defining activity of an interpreter is to implement the operations specified by an input program. For an expression such as a + b, it may retrieve two values, determine which addition operation applies, perform that operation, and deliver the result. For a conditional statement, it evaluates a condition and selects the appropriate continuation. These actions may be implemented directly in the interpreter’s own code or delegated to runtime services and native libraries.\n\nThe phrase “executes source code directly” is therefore an incomplete definition. Many interpreters never execute source text as such. They first transform it into a syntax tree or a sequence of internal instructions. Conversely, a compiler need not produce machine code: translating source into another language or into instructions for a virtual machine is also compilation. A system that compiles source into bytecode and then interprets that bytecode uses both techniques.\n\nA useful distinction concerns the artifact and timing of execution. An ahead-of-time compiler normally produces a translated artifact before a particular execution begins. An interpreter consumes a representation while performing the program’s requested computation. A dynamically compiling runtime can translate selected portions during execution and then transfer control to the resulting native code. These categories describe stages within a system, not mutually exclusive kinds of software.\n\nNor does interpretation imply that all decisions are postponed until runtime. An interpreter can check syntax, resolve names, analyze control flow, or verify types before executing a program. Some interpreted implementations use statically typed input languages; some compilers implement dynamically typed languages. Type discipline, evaluation order, memory management, and the choice between interpretation and compilation are separate design dimensions, even when particular combinations are common.\n\nAt the lowest level, interpretation is usually implemented by instructions executed by a central processing unit. This does not make the interpreter’s input identical to the processor’s instruction set. The interpreter establishes another execution model above the host machine. In the terminology of operational semantics, it realizes transitions between program states. A simplified description is \\(S_{t+1}=\\delta(S_t,I_t)\\), where \\(S_t\\) contains the relevant state and \\(I_t\\) is the next operation to be interpreted."
    },
    {
      "heading": "Historical development",
      "text": "Interpretive execution appeared early in electronic computing, when programming directly in machine instructions was difficult and hardware resources were limited. Short Code, developed around 1949–1950 from an idea by John Mauchly and work by William Schmitt, is an early example of an interpreted notation for mathematical expressions. Such systems traded execution speed for a representation closer to the problem being solved. They also demonstrated a lasting principle: software could supply a more convenient abstract machine than the physical computer alone provided.\n\nThe development of Lisp made interpretation central to language implementation and language research. John McCarthy introduced Lisp in the late 1950s, and Steve Russell implemented an early Lisp evaluator around 1960. The evaluator gave concrete form to the relationship between symbolic expressions, variable environments, and procedure application. Lisp also supported compilation, but its interpreters helped establish the importance of interactive evaluation and programs that manipulate symbolic representations of other programs.\n\nBASIC, first run at Dartmouth College in 1964 under John Kemeny and Thomas Kurtz, was designed for accessible programming in a time-sharing environment. The original Dartmouth system used compilation; later microcomputer BASIC systems made interpretation particularly familiar. Microsoft’s Altair BASIC appeared in 1975, and BASIC interpreters subsequently became standard interfaces on many home computers. Programs were often stored in tokenized form, replacing keywords with compact codes rather than repeatedly examining their full textual spelling.\n\nPortable intermediate-code systems developed along a related path. UCSD Pascal, developed in the 1970s, compiled programs into p-code for an abstract machine. Implementing the p-machine on another computer could make the programming environment available there without rebuilding every application for a new native instruction set. Smalltalk systems also brought together virtual-machine execution, live object environments, and interactive development. These systems showed that interpretation could underpin a complete development environment rather than merely a command processor.\n\nLater implementations increasingly combined interpretation with compilation. Python, first publicly released in 1991, became closely associated with an implementation that compiles source into bytecode and executes it in a virtual machine. Java’s release in 1995 brought a widely deployed class-file and virtual-machine architecture, while JavaScript, also introduced in 1995, became embedded in web browsers. Subsequent Java and JavaScript engines adopted increasingly elaborate dynamic compilation. This history is not a simple replacement of interpretation by compilation: interpreters continue to provide compact execution engines, fast initial execution, and a baseline for more speculative optimization."
    },
    {
      "heading": "From source text to executable structures",
      "text": "A source-level interpreter generally begins with a front end that recognizes the structure of its input. Lexical analysis groups characters into tokens such as identifiers, numeric literals, and punctuation. Parsing then determines how those tokens form expressions, declarations, and statements according to the language grammar. This process must respect rules such as operator precedence: in 2 + 3 * 4, multiplication ordinarily forms a subexpression before addition.\n\nMany implementations construct an abstract syntax tree, or AST. An AST records meaningful syntactic structure while usually discarding details such as redundant parentheses and comments. For example, an addition node may contain references to its left and right operands rather than a copy of the original text. A tree-walking interpreter evaluates this representation by selecting behavior according to the kind of node it encounters. Literal nodes produce values; variable nodes consult an environment; conditional nodes choose a branch.\n\nA simplified evaluator for arithmetic can be described by the rule\n\n\\[\\operatorname{eval}(\\operatorname{Add}(x,y),\\rho) = \\operatorname{eval}(x,\\rho)+\\operatorname{eval}(y,\\rho),\\]\n\nwhere \\(\\rho\\) maps names to their bindings. Real languages need substantially more machinery. The rule must account for the language’s evaluation order, possible side effects, numeric representations, and any user-defined behavior of addition. An evaluator that accidentally reverses operand evaluation can change a program’s observable behavior even when both orders produce the same result for ordinary arithmetic.\n\nName resolution may also occur before execution. Instead of searching a chain of dictionaries every time a local variable is referenced, an implementation can determine that the variable occupies a particular slot in an activation record. This retains interpretation while eliminating repeated work. Similar preprocessing can distinguish local, enclosing, and global bindings, check whether control-flow constructs are permitted in their context, or reject duplicate declarations.\n\nTree-walking interpreters are attractive for teaching, prototypes, and languages whose operations are relatively coarse-grained. Their implementation often resembles the language’s grammatical structure. However, traversing separately allocated nodes can require many pointer accesses, and recursive evaluation may consume the implementation language’s call stack. Production systems may therefore lower the tree into a more compact representation, use explicit execution stacks, or compile selected operations. The difference between a simple educational evaluator and a production interpreter lies less in the basic idea than in the treatment of these repeated costs and semantic edge cases."
    },
    {
      "heading": "Bytecode machines and instruction dispatch",
      "text": "A bytecode interpreter executes a sequence of instructions defined for a software machine. Despite the name, bytecode instructions need not each occupy exactly one byte. An instruction set may use fixed-width words, variable-length encodings, separate operand tables, or a mixture of formats. The important feature is that the representation is designed for execution by a runtime rather than direct execution by the host processor.\n\nA stack-based bytecode machine typically uses an operand stack. To compute a + b, it might load a, load b, and execute an addition instruction that removes two operands and pushes a result. A register-based machine instead names virtual registers explicitly, expressing the operation as something like ADD r3, r1, r2. Stack formats often have compact instructions and straightforward code generation. Register formats can express some computations with fewer executed instructions, although their operands may require more space. Neither design guarantees superior performance across all workloads.\n\nExecution normally revolves around instruction dispatch: obtaining the next opcode and selecting its handler. A straightforward implementation uses a loop containing a large switch statement. Other implementations use tables of handler addresses or threaded dispatch techniques. The efficiency of dispatch depends on the host compiler, available language extensions, instruction layout, and processor branch prediction. “Direct-threaded code” in this context describes an execution representation, not the use of multiple operating-system threads.\n\nThe virtual machine also maintains state beyond its instruction stream. A frame may contain local variables, temporary operands, a reference to the executing function, and a return position. Branch instructions change the instruction pointer; call instructions establish a new frame; return instructions restore the caller’s state. Exception handling may require tables that map instruction ranges to handlers. Source-location tables allow the runtime to translate an instruction position back into a meaningful line or expression for diagnostics.\n\nBytecode creates a useful implementation boundary. A front end can change while preserving the execution engine, and multiple source languages can target a shared machine when their semantics fit its facilities. However, a bytecode format is not automatically a stable distribution standard. CPython’s bytecode is an internal implementation detail that can change between releases, whereas Java class files are governed by a specified format with versioning rules. The portability of the representation depends on the surrounding specification and compatible implementations, not on its being called bytecode."
    },
    {
      "heading": "Runtime values, environments, and control flow",
      "text": "An interpreter’s runtime representation of values strongly influences both correctness and performance. A statically specialized evaluator may know that a particular slot contains an integer. A dynamically typed interpreter often needs a representation that can distinguish integers, floating-point values, strings, objects, and other categories during execution. Common techniques include tagged values, pointers to heap objects, and combinations in which small values are stored directly while larger ones are allocated separately.\n\nAn operation such as addition illustrates the consequences. The runtime may first inspect operand tags. Two small integers can take a fast path, but overflow may require a larger integer representation if the language specifies unbounded integers. Other operand combinations may invoke floating-point arithmetic, string concatenation, or user-defined methods. An interpreter must implement the language’s rules rather than simply use the host language’s + operator, whose overflow and conversion behavior may differ.\n\nVariable environments connect names with storage. A function call commonly creates an activation record containing arguments, local bindings, and execution state. Lexically scoped functions can also retain access to bindings from their defining context through a closure. If such a function outlives the call that created it, its captured state must remain available. Implementations may allocate captured bindings on the heap, move them there when necessary, or use shared cells so that multiple closures observe updates to the same variable.\n\nMemory management is therefore integral to many interpreters. Garbage collection can reclaim objects that are no longer reachable from active frames, global bindings, and other roots. Reference counting tracks ownership incrementally but needs additional machinery to reclaim cycles. Tracing collectors identify reachable objects more directly, sometimes pausing or relocating them. Native extensions complicate both approaches because references outside the interpreter’s ordinary object graph must still be represented correctly.\n\nControl flow requires equally careful treatment. Recursive calls, exceptions, generators, and coroutines impose different requirements on execution state. A generator may suspend a frame rather than destroy it; an exception may unwind several frames while executing cleanup actions. A language that requires proper tail calls may need to reuse or replace frames instead of accumulating them. These behaviors are not incidental conveniences: they determine which programs can execute within bounded space and which effects occur when execution leaves a scope."
    },
    {
      "heading": "Dynamic compilation and adaptive execution",
      "text": "Many high-performance runtimes begin by interpreting a program and later compile frequently executed portions. Just-in-time compilation, usually abbreviated JIT compilation, generates executable code during program execution. The interpreter can provide an initial execution tier while collecting information about call targets, operand types, branch behavior, and execution frequency. A compiler then uses this information to optimize code whose expected future use justifies the compilation cost.\n\nA common optimization is to specialize an operation for cases observed at runtime. A general property lookup may involve examining an object’s layout and searching for a member. If repeated executions encounter objects with the same layout, an inline cache can record a faster lookup path. A guard checks that the relevant assumptions still hold. If the guard fails, execution returns to a general path or another specialized case. Inline caching can improve an interpreter even when no native code is generated.\n\nSome systems specialize bytecode itself. An instruction that initially performs general addition may be replaced by a form optimized for a recurring operand combination, with a fallback when that combination changes. CPython 3.11, released in 2022, introduced a specializing adaptive interpreter as a major implementation development. Such specialization demonstrates why “interpreted” need not mean that every operation repeats all possible checks on every execution.\n\nNative-code optimization introduces the problem of deoptimization. Compiled code may assume that a call target remains unchanged or that a value has a particular representation. If those assumptions cease to hold, the runtime must reconstruct a valid less-specialized state, often an interpreter frame. This requires metadata connecting optimized machine state with source-level variables and execution positions. Transferring execution in the opposite direction, from a running interpreted frame into compiled code, is commonly called on-stack replacement.\n\nOther designs optimize traces through frequently executed paths or transform an interpreter using partial evaluation. Tracing systems can expose operations across function boundaries along a particular path, but must handle exits when execution diverges. All these approaches involve trade-offs among startup delay, compilation time, memory consumption, peak throughput, and implementation complexity. A small embedded runtime may deliberately avoid native compilation, while a long-running server may benefit greatly from it. The appropriate balance depends on workload and deployment constraints rather than on a universal ranking of execution techniques."
    },
    {
      "heading": "Interactive use and application embedding",
      "text": "An interpreter often supports a read–eval–print loop, or REPL: it accepts a unit of input, evaluates it, displays a result, and repeats. This interaction encourages experimentation because small expressions can be tested without constructing a complete executable program. The runtime usually preserves an environment between inputs, allowing later commands to refer to earlier definitions. However, interaction and interpretation are distinct: a compiled implementation can provide a REPL by compiling each submitted fragment.\n\nInteractive execution creates its own semantic questions. An incomplete function definition may require additional input before parsing can finish. Redeclaring a name may replace a binding while older closures retain access to previous state. A displayed value can require a language-specific representation rather than ordinary string conversion. Errors must usually return control to the prompt without terminating the entire session, while preserving only those state changes that have already occurred under the language’s rules.\n\nA command interpreter provides a related but distinct interface. Unix shells parse commands, perform expansions and redirections, execute built-in operations, and launch external programs through operating-system facilities. A shell is therefore more than a mechanism for reading one command per line. It implements a language with variables, control structures, quoting rules, and process composition. By contrast, a graphical or textual interface that merely selects fixed operations is not necessarily a programming-language interpreter.\n\nEmbedding places an interpreter inside another application. A host program can expose selected objects and functions through an application programming interface, allowing scripts to customize behavior without rebuilding the host. Lua, Python, and Tcl are prominent examples of languages used this way. A game might expose entity movement and event callbacks; an engineering application might expose measurement and plotting operations. The interpreter handles script execution while the host retains control of application-specific resources.\n\nA foreign-function interface connects interpreted code with routines implemented elsewhere, often in C. This can make numerical operations or system facilities available without reimplementing them in the scripting language. The boundary nevertheless requires agreement about value conversion, object lifetime, error propagation, and threading. Passing a pointer to an object that a moving collector can relocate, for example, requires explicit cooperation. Embeddability depends as much on a well-defined ownership and execution model as on the ability to call an evaluation function."
    },
    {
      "heading": "Portability, virtual machines, and emulation",
      "text": "Interpretation can separate a program’s execution model from the host computer. If a program targets an abstract instruction set, a new host may need only a compatible interpreter and runtime services. This can reduce the amount of platform-specific work required to support a language. The claim is strongest when the execution model specifies details such as integer widths, exceptions, memory access, and library behavior rather than leaving them to the host implementation.\n\nPortability has several layers. A bytecode file might be structurally readable on different systems but depend on a native extension available on only one platform. A program might use specified language features yet rely on particular file paths, character encodings, or operating-system behavior. Even consistent arithmetic requires attention: directly mapping a language’s integer operations onto host integers can introduce unintended overflow differences. An interpreter is a portability mechanism, not a guarantee that every program using it is portable.\n\nInstruction-set emulation applies interpretation to machine instructions defined for another processor. The emulator maintains guest registers, a program counter, and a model of memory, then implements each guest instruction using host operations. Correctness may require reproducing details such as condition flags, byte order, alignment rules, exceptions, and privileged instructions. This differs from a high-level language interpreter chiefly in the nature of the guest machine and the level of detail that must be reproduced.\n\nEmulation and virtualization overlap in practice but are not identical. Hardware-assisted virtualization can allow many guest instructions to execute directly on a compatible processor under controlled conditions. An interpreter instead implements guest operations in software. A system emulator may combine interpreted execution, dynamic binary translation, and hardware assistance. Accurately emulating a complete computer also involves devices, interrupts, timers, and interactions with firmware, not merely the processor instruction set.\n\nWebAssembly illustrates a modern portable execution format that supports multiple implementation strategies. Its structured instruction format and validation rules are designed for execution in controlled environments, including web browsers and standalone runtimes. An implementation may interpret WebAssembly, compile it ahead of time, or compile it during execution. Like Java bytecode, it is therefore not itself synonymous with interpretation. A portable target format specifies what execution must mean; the runtime chooses how to realize that meaning on a particular host."
    },
    {
      "heading": "Performance and resource trade-offs",
      "text": "The cost of interpretation is not a single fixed multiplier. It arises from several sources: instruction dispatch, access to runtime data structures, repeated type checks, allocation, name lookup, and the inability to optimize across operations as extensively as a compiler might. A bytecode that represents one small arithmetic action may require many host instructions to execute. Conversely, a single interpreted operation that invokes a large numerical routine can spend almost all its time in optimized native code.\n\nA simple performance model separates these costs:\n\n\\[T_{\\text{run}} \\approx T_{\\text{startup}} + N_{\\text{dispatch}}c_{\\text{dispatch}} + T_{\\text{operations}} + T_{\\text{memory}}.\\]\n\nHere \\(N_{\\text{dispatch}}\\) is the number of interpreted instructions and \\(c_{\\text{dispatch}}\\) their average dispatch cost. The terms are not completely independent: dispatch influences instruction-cache behavior, object representation influences allocation, and specialization changes both instruction counts and operation costs. Nevertheless, the model explains why reducing dispatch alone may have little effect on an application dominated by input/output or a native library.\n\nAn interpreter usually does not change an algorithm’s asymptotic time complexity merely by executing it, but implementation choices can affect complexity in important cases. A variable lookup implemented as a linear search is different from one using a hash table or a resolved frame slot. String concatenation in a loop may repeatedly copy growing strings unless the runtime or program avoids that pattern. Arbitrary-precision integer operations also depend on operand size, so treating every arithmetic instruction as constant-time can conceal substantial costs.\n\nMemory behavior can favor either interpretation or compilation. Compact bytecode can occupy less space than native code, which is useful on constrained devices and can benefit the processor cache. On the other hand, boxed values and heap-allocated objects can consume more memory than specialized native representations. A JIT compiler may eliminate temporary objects or keep values in registers, but compiled code, profiling data, and deoptimization metadata all have their own footprint.\n\nMeaningful comparisons therefore distinguish startup latency, steady-state throughput, peak memory, and latency variability. A short-lived command may finish before dynamic compilation pays for itself, whereas a long-running computational loop may benefit substantially. Benchmarks must also specify the implementation, version, workload, and use of native extensions. Comparing two languages without these details can wrongly attribute differences in libraries, algorithms, or runtime maturity to interpretation alone."
    },
    {
      "heading": "Correctness, isolation, and security boundaries",
      "text": "An interpreter must preserve the observable behavior specified by its language. This includes not only successful results but evaluation order, exceptions, overflow rules, and interactions with external resources. A compact reference interpreter can serve as an executable description against which optimizing implementations are compared. However, a reference implementation is authoritative only when the language’s governance or specification gives it that role; an implementation bug does not automatically define the language.\n\nTesting often compares execution across implementations or execution tiers. The same program can run in an interpreter and in compiled mode, with differences investigated as possible defects. Random program generation and mutation-based testing can expose unusual combinations of control flow, numeric values, and language features. Formal verification can establish stronger properties for specified components, but a proof concerns a particular model and trusted base. Correct evaluation of arithmetic expressions alone does not establish the correctness of parsing, memory management, native libraries, or the surrounding host application.\n\nExecuting code through an interpreter does not automatically provide a sandbox. A script that can open arbitrary files, start processes, or load native extensions may possess substantial authority. Restricting visible names is often insufficient when object introspection or indirect references can recover powerful capabilities. A security boundary must account for every route by which code can reach resources, including host callbacks, module loading, external commands, and native interfaces.\n\nResource exhaustion is another concern even when access to files and networks is blocked. Untrusted code can consume processor time, allocate memory, recurse deeply, or construct outputs of excessive size. Runtimes may enforce instruction budgets, memory limits, cancellation checks, or process-level isolation. These mechanisms require careful accounting: a single interpreted instruction that calls a long-running native function can bypass a budget based only on bytecode dispatch. Restrictions must cover the actual work performed, not merely the number of visible language operations.\n\nInterpreter implementations can themselves contain security vulnerabilities, especially where untrusted input reaches memory-unsafe native code. Bytecode validation can reject malformed instruction sequences, invalid branch targets, or inconsistent operand-stack use before execution, but validation is only as sound as its implementation and its assumptions about later runtime behavior. Source-level evaluation functions also create injection risks when applications combine executable text with untrusted data. Separating data from code, controlling runtime authority, and isolating execution address different failure modes; none is supplied simply by choosing interpretation over compilation."
    }
  ],
  "links": [
    "programming-language",
    "source-code",
    "compiler",
    "machine-code",
    "virtual-machine",
    "central-processing-unit",
    "lisp-programming-language",
    "john-mccarthy",
    "python-programming-language",
    "javascript",
    "abstract-syntax-tree",
    "stack-data-type",
    "garbage-collection",
    "recursion",
    "coroutine",
    "operating-system",
    "application-programming-interface",
    "foreign-function-interface",
    "c-programming-language",
    "virtualization",
    "web-browser",
    "time-complexity",
    "hash-table",
    "cpu-cache",
    "formal-verification",
    "sandbox-computer-security",
    "security-vulnerability"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}