What is the difference between a compiler and an interpreter

What is the difference between a compiler and an interpreter

Difference Between Compiler and Interpreter

What is the difference between a compiler and an interpreter. Смотреть фото What is the difference between a compiler and an interpreter. Смотреть картинку What is the difference between a compiler and an interpreter. Картинка про What is the difference between a compiler and an interpreter. Фото What is the difference between a compiler and an interpreterA compiler is a translator which transforms source language (high-level language) into object language (machine language). In contrast with a compiler, an interpreter is a program which imitates the execution of programs written in a source language. Another difference between Compiler and interpreter is that Compiler converts the whole program in one go on the other hand Interpreter converts the program by taking a single line at a time.

Evidently, the perceivability of humans and an electronic device like a computer is different. Humans can understand anything through natural languages, but a computer doesn’t. The computer needs a translator to convert the languages written in the human-readable form to the computer-readable form.

Compiler and interpreter are the types of a language translator. What is Language translator? This question might be arising in your mind.

A language translator is a software which translates the programs from a source language that are in human-readable form into an equivalent program in an object language. The source language is generally a high-level programming language, and the object language is typically the machine language of an actual computer.

Content: Compiler Vs Interpreter

Comparison Chart

Basis for comparisonCompilerInterpreter
InputIt takes an entire program at a time.It takes a single line of code or instruction at a time.
OutputIt generates intermediate object code.It does not produce any intermediate object code.
Working mechanismThe compilation is done before execution.Compilation and execution take place simultaneously.
Speed

Comparatively fasterSlower
Memory

Memory requirement is more due to the creation of object code.It requires less memory as it does not create intermediate object code.
ErrorsDisplay all errors after compilation, all at the same time.Displays error of each line one by one.
Error detectionDifficultEasier comparatively
Pertaining Programming languagesC, C++, C#, Scala, typescript uses compiler.PHP, Perl, Python, Ruby uses an interpreter.

Definition of Compiler

A compiler is a program that reads a program written in the high-level language and converts it into the machine or low-level language and reports the errors present in the program. It converts the entire source code in one go or could take multiple passes to do so, but at last, the user gets the compiled code which is ready to execute.

What is the difference between a compiler and an interpreter. Смотреть фото What is the difference between a compiler and an interpreter. Смотреть картинку What is the difference between a compiler and an interpreter. Картинка про What is the difference between a compiler and an interpreter. Фото What is the difference between a compiler and an interpreter

Compiler operates on phases; various stages can be grouped into two parts that are:

Phases of Compiler

Now let’s understand the working of each stage in detail.

What is the difference between a compiler and an interpreter. Смотреть фото What is the difference between a compiler and an interpreter. Смотреть картинку What is the difference between a compiler and an interpreter. Картинка про What is the difference between a compiler and an interpreter. Фото What is the difference between a compiler and an interpreter

The symbol table is somewhat a data structure which manages the identifiers along with the relevant type of data it is storing. Error Handler detect, report, correct the errors encountering in between the different phases of a compiler.

Definition of Interpreter

The interpreter is an alternative for implementing a programming language and does the same work as a compiler. Interpreter performs lexing, parsing and type checking similar to a compiler. But interpreter processes syntax tree directly to access expressions and execute statement rather than generating code from the syntax tree.

An interpreter may require processing the same syntax tree more than once that is the reason why interpretation is comparatively slower than executing the compiled program.

Compilation and interpretation probably combined to implement a programming language. In which a compiler generates intermediate-level code then the code is interpreted rather than compiled to machine code.

Employing an interpreter is advantageous during program development, where the most important part is to be able to test a program modification rapidly rather than run the program efficiently.

Key Differences Between Compiler and Interpreter

Let’s look at major differences between Compiler and Interpreter.

Interpreted vs Compiled Programming Languages: What’s the Difference?

What is the difference between a compiler and an interpreter. Смотреть фото What is the difference between a compiler and an interpreter. Смотреть картинку What is the difference between a compiler and an interpreter. Картинка про What is the difference between a compiler and an interpreter. Фото What is the difference between a compiler and an interpreter

Every program is a set of instructions, whether it’s to add two numbers or send a request over the internet. Compilers and interpreters take human-readable code and convert it to computer-readable machine code.

In a compiled language, the target machine directly translates the program. In an interpreted language, the source code is not directly translated by the target machine. Instead, a different program, aka the interpreter, reads and executes the code.

Okay… but what does that actually mean?

Imagine you have a hummus recipe that you want to make, but it’s written in ancient Greek. There are two ways you, a non-ancient-Greek speaker, could follow its directions.

The first is if someone had already translated it into English for you. You (and anyone else who can speak English) could read the English version of the recipe and make hummus. Think of this translated recipe as the compiled version.

The second way is if you have a friend who knows ancient Greek. When you’re ready to make hummus, your friend sits next to you and translates the recipe into English as you go, line by line. In this case, your friend is the interpreter for the interpreted version of the recipe.

Compiled Languages

Compiled languages are converted directly into machine code that the processor can execute. As a result, they tend to be faster and more efficient to execute than interpreted languages. They also give the developer more control over hardware aspects, like memory management and CPU usage.

Compiled languages need a “build” step – they need to be manually compiled first. You need to “rebuild” the program every time you need to make a change. In our hummus example, the entire translation is written before it gets to you. If the original author decides that he wants to use a different kind of olive oil, the entire recipe would need to be translated again and resent to you.

Examples of pure compiled languages are C, C++, Erlang, Haskell, Rust, and Go.

Interpreted Languages

Interpreters run through a program line by line and execute each command. Here, if the author decides he wants to use a different kind of olive oil, he could scratch the old one out and add the new one. Your translator friend can then convey that change to you as it happens.

Interpreted languages were once significantly slower than compiled languages. But, with the development of just-in-time compilation, that gap is shrinking.

Examples of common interpreted languages are PHP, Ruby, Python, and JavaScript.

A Small Caveat

Most programming languages can have both compiled and interpreted implementations – the language itself is not necessarily compiled or interpreted. However, for simplicity’s sake, they’re typically referred to as such.

Python, for example, can be executed as either a compiled program or as an interpreted language in interactive mode. On the other hand, most command line tools, CLIs, and shells can theoretically be classified as interpreted languages.

Advantages and disadvantages

Advantages of compiled languages

Programs that are compiled into native machine code tend to be faster than interpreted code. This is because the process of translating code at run time adds to the overhead, and can cause the program to be slower overall.

Disadvantages of compiled languages

The most notable disadvantages are:

Advantages of interpreted languages

Interpreted languages tend to be more flexible, and often offer features like dynamic typing and smaller program size. Also, because interpreters execute the source program code themselves, the code itself is platform independent.

Disadvantages of interpreted languages

The most notable disadvantage is typical execution speed compared to compiled languages.

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

The Difference Between a Compiler and an Interpreter

What is the difference between a compiler and an interpreter. Смотреть фото What is the difference between a compiler and an interpreter. Смотреть картинку What is the difference between a compiler and an interpreter. Картинка про What is the difference between a compiler and an interpreter. Фото What is the difference between a compiler and an interpreter

According to their definitions, the difference between a compiler and an interpreter seems clear enough:

If you dig deeper, though, you find some blurring between the two.

In fact an interpreter could translate the source language in a intermediate form, to speed up execution. That is what usually happens with a language that relies on a virtual machine. This naturally lead to the some questions:

Are all languages that use a virtual machine interpreted?

Are they all actually compiled?

You might say both: a language is first compiled in an intermediate form/language and then this intermediate thing is interpreted at run time. Which also lead to another issue, a compiler and an interpreter should not be thought as one program, but more of a group of programs, a system. What you, as a user, think as a compiler may actually include more than one program. For instance, it may include a linker: a program that combines different object files in one file, so that it can be more easily used. Something similar could be said of an interpreter.

Can You Tell Me Everything About Compilers & Interpreters?

So, which are all the pieces that compose a compiler or an interpreter? You could look for a precise and technical answer to such questions in academia. Or you can find discussions on these issues on StackOverflow.

What it really matters to us as developers, or even us as creators of a language, is what are the differences in working with them. Both have advantages and disadvantages, and in fact some languages can have both an interpreter and a compiler, or more than one. That is what we are going to see.

The main point still stands: an interpreter executes the code now, a compiler prepares the source code for an execution that comes later. All the practical differences descend from these different objectives.

How Do You Distribute a Program

In practical terms one important difference is that a compiler generates a stand-alone program, while an interpreted program always need the interpreter to run.

Once you have a compiled program you can run it without needing to install anything else. This simplifies distribution. On the other hand the executable work on one specific platform: different operating systems and different processors need different compiled versions. For example, a compiled C++ program might work on a computer with an x86 processor, but not one with an ARM chip. Or it could work on a Linux system, but not a Windows one.

If you are going to interpret a program you can distribute the same copy to users on different platforms. However they will need an interpreter that runs on their specific platform. You could either distribute the original source code or an intermediate form. An intuitive way to look at an interpreter is this: it is like the eval function in JavaScript. It works wherever JavaScript works, but it need a JavaScript interpreter for that platform to run.

Cross-Platform Support

This is a technical difference that leads to important real consequences: it is easier to make cross-platform programs with an interpreted programming language.

That is because, for the most part, you are just creating a program for the interpreter platform. It will be the interpreter itself that will translate it into the proper form for the real platform (e.g., Windows/Linux and x86/ARM). Of course, there are still some differences in each platform of which you must be aware. A common example is the directory separator character.

When you compile a program, instead, you need to take care yourself of all the little differences between each platform. This happens in part because compiled languages tend to be low(er) level languages, such as C++, so they give you lower access to the system and thus more responsibility. But another reason is that all the libraries you are using need themselves to support different platforms. So, if they do not support Windows, you cannot support Windows.

Speed Has Multiple Faces

Again, in the case of speed, we have a sort of paradox: a compiler is both faster and slower than an interpreter. Many people knows that a compiled program is much faster than an interpreted one, but this is not the whole picture. A compiled program is faster to run than an interpreted program, but it takes more time to compile and run a program than to just interpret it.

A compiler indeed produces faster programs. It happens fundamentally because it must analyze each statement just once, while an interpreter must analyze it each time. Furthermore, a compiler can optimize the executable code it produces. That is both because it knows exactly where it will run and also it takes time to optimize the code. Time that would make the interpretation too slow.

Runtime Speed Versus Development Speed

You might think that this is nitpicking: if you compile a program it runs faster, the time that it takes to compile does not matter. This is usually the old school opinion. And without doubt the resulting program is run more times than it is compiled. So who cares if the development takes more time? Well, for sure it takes a “bring the pain” attitude to development that is somewhat admirable. But what if the gains in run time are not relevant, while the losses in development productivity are significant?

It is one thing if you creating an operating system and another one if you making a selfie app. Even your users might prefer a not-even-noticeable loss in run time speed in exchange for getting features quicker. There is not a one-size-fits-all answer: in some contexts productivity matters more than speed, in others the reverse is true.

The Mysteries Of Debugging

There is another particular aspect that ends up being more uncertain than what one would aspect: debugging. On paper debugging is easier while using a interpreter than using a compiler. That is true for several reasons:

The Difference that Development Tools Makes

While this is all true in practice, this might be less relevant than it seems. In fact if you think about your experience, you would probably find that debugging JavaScript is harder than debugging C++. Why is that? In part is the design of the languages themselves. JavaScript uses dynamic typing, while C++ uses static typing. The latter makes easier to catch mistakes early. But in the end it comes down to the development tools. Compiling C++ by hand is hard, so most people use IDEs to develop with it. On the other hand, you can easily use text editor and command line tools to develop in JavaScript.

This means that, in practical terms, if you develop with C++, you can also debug C++. Instead you can develop with JavaScript without knowing how to do proper debugging in JavaScript.

Having said that, if we put them in the same context, each one with a great IDE and supporting tools, the situation comes back to normal. Indeed many interpreted environment are used by people that want to learn how to use a new language. It is easier to test, and find what is right and wrong, by looking at what happens line by line and in real time.

Summary

We have seen the main differences that matters between a compiler and an interpreter. More importantly we have seen that the consequences of different philosophies are more important than the technical ones. In short, there are cultures that come with certain technical choices that end up being relevant on their own. If you want speed and ease of development you are going to pick all the technologies for speed and not just one. And your users are going to follow your lead.

This is a crucial aspect to think through, especially if you want to create your own programming language. Rasmus Lerdorf created PHP to be easy to use. And indeed it was incredibly easier to use compared to the alternatives, at least at the time of its creation. But it started more as a library than as a language. And while it has improved a lot, it still suffers from its beginnings. You can still create good PHP code, but fewer of its users than usual do. Because if you just need something that works, security, maintenance, etc., all the rest come later.

If you want to know how you can practically build an interpreter or a compiler for your language, you may want to take a look at the resources to create a programming language. If you want to learn that, and all that you need to create your own language, you just need to pick a great book, loved by kids and adults alike, on how to create pragmatic, lightweight languages.

5 things to get right when building a language

What is the difference between a compiler and an interpreter. Смотреть фото What is the difference between a compiler and an interpreter. Смотреть картинку What is the difference between a compiler and an interpreter. Картинка про What is the difference between a compiler and an interpreter. Фото What is the difference between a compiler and an interpreter

Receive the checklist by email and get more tips on building languages

Difference Between Compiler and Interpreter: Compiler Vs Interpreter

What is the difference between a compiler and an interpreter. Смотреть фото What is the difference between a compiler and an interpreter. Смотреть картинку What is the difference between a compiler and an interpreter. Картинка про What is the difference between a compiler and an interpreter. Фото What is the difference between a compiler and an interpreter

If we were to go to a foreign country, where communicating in the native language is difficult, life would have been hazardous. Expecting something in return when asked would be tough unless we have a translator. Even though we don’t go to a different nation every day, we communicate with someone who does not understand any human language; A computer. We speak to a computer through a high-level programming language but did you know that the programming language isn’t the ultimate language that a computer understands? We have system software known as compilers and interpreters that aids in making the conveyance smoother. What are these compilers and interpreters? are they the same? Is there any difference between compilers and interpreters?

Both compiler and interpreter are key components needed to convert a program written in a high-level language into machine code that can be understood by a computer. A compiler and an interpreter, however, function very differently, and there are some differences between the two. In this article, we are going to see what is compilers and interpreters as well as the difference between Compiler and Interpreter.

What are Compilers?

A compiler is computer software that readily translates programming language into machine code or assembly language or low-level language. It translates every program to binary(1’s and 0’s) that a computer feasibly understands and does the task that corresponds to the code. One condition that a compiler has to follow is the syntax of the programming language that is used. Thus, if the syntax of the program does not match the analysis of the compiler, an error arises that has to be corrected manually in the program written.

Working of Compiler

The main work of the compiler is to translate the program into machine code and let the programmer know if there are any errors, ranges, limits, etc., especially the syntactical errors in the program. It analyses the entire program and converts it into machine code. The working of a compiler can be categorized into the following phases:

Benefits of Compilers

The compiler offers various advantages which can be summed up as follows:

Role of a Compiler

What is an Interpreter?

An interpreter is a computer program that converts program statements into machine code. Program statements include source code, pre-compiled code, and scripts. Unlike a compiler, an interpreter takes a shorter amount of time to interpret a program. Since interpreters simplify the process of working with source code, they are especially useful for beginners.

Working of Interpreter

An interpreter works more or less similar to a compiler. The only difference between their working is that the interpreter does not generate any intermediate code forms, reads the program line to line checking for errors, and runs the program simultaneously.

Benefits of Interpreters

The interpreter offers various advantages which can be summed up as follows:

Role of an Interpreter

Difference Between Compiler and Interpreter

What is the difference between a compiler and an interpreter. Смотреть фото What is the difference between a compiler and an interpreter. Смотреть картинку What is the difference between a compiler and an interpreter. Картинка про What is the difference between a compiler and an interpreter. Фото What is the difference between a compiler and an interpreter

While it looks like Compiler and Interpreter work the same by translating programs into machine code, there is a very thin line that differentiates both of them. The differences are as follows:

BasisCompilerInterpreter
AnalysisThe entire program is analyzed in a compiler in one go.In an interpreter, a line-by-line analysis is performed on the program.
Machine CodeStores machine code in the disk storage.Machine code is not stored anywhere.
ExecutionThe execution of the program happens only after the entire program is compiled.The execution of the program takes place after every line is evaluated and hence the error is raised line by line if any.
Run TimeCompiled program runs faster. Since it consumes less time, it is much faster than an interpreter.Interpreted program runs slower. Since it consumes more time, it is much slower than an compiler.
GenerationThe compilation gives an output program that runs independently from the source file.The interpretation does not give any output program and is thus evaluated on every execution.
OptimizationThe compiler reads the entire program and searches multiple times for a time-saving execution.No rigorous optimization takes place as code is evaluated line by line.
Error and error executionAll the errors are shown at the end of the compilation and the program cannot be run until the error is resolved.Displays the errors from line to line. The program runs till the error is found and proceeds further on resolving.
InputThe compiler takes in the entire program for analysis.The interpreter takes in lines of code for analysis.
OutputThe compiler gives intermediate code forms or object code.The interpreter does not generate any intermediate code forms.
Programming languagesC, C++, C#, Java are compiler-based programming languages.PHP, PERL, Ruby are interpreter-based programming languages.
CPU UtilizationCPU utilization is higher in compilers.The interpreter uses less CPU than the compiler.
Error LocalizationLocalizing errors is difficult.Errors can be localized more easily than in the compiler.
Error EffectsAn error can trigger the reorganization of the entire program.Errors only cause part of the program to be reorganized.
FlexibilityIn general, compilers are not flexible.The interpreter provides more flexibility.
Error VerificationYou can simultaneously check for both syntactic and semantic errors.Syntactic errors are checked only.

Conclusion

To sum up, the compilers and the interpreters are like an oven and induction stove. Its functioning is almost the same; To convert a programming language into a machine language. But, the working differs. Their usage depends on the language being used and the purpose.

Frequently Asked Questions

Q: Which is better? Compiler or Interpreter?
A: The betterness depends on the need. The interpreter is highly useful in debugging but the overall execution is slow. While a compiler scans the entire source code, resolving errors is slightly difficult. Selection is purely dependent on the end result.

Q: Which is faster? Compiler or Interpreter?
A: If the process is considered, the Interpreter is faster than the compiler. However, once a program is compiled, Runtime or execution is faster for a compiled program over-interpreted ones.

Q: Can anyone use an interpreter instead of a compiler?
A: Yes. Interpreters have advantages like easier debugging, portability, etc. Depending upon the necessity, one can use an interpreter instead of a compiler.

Q: Is Python interpreter or compiler?
A: Python is known to be an interpreted language. However, the compilation of python code is hidden from users. The python programs get converted to bytecodes, an intermediate form that the machine understands. Thus, Python stands in the center of both parameters.

Q: What are the examples of interpreters?
A: Some examples of interpreters include Python interpreter, PERL interpreter, Ruby interpreter, PHP interpreter, etc.

What is the difference between implementing a compiler and an interpreter?

I’ve read the whole Dragon Book recently (just for fun, I’m not really planning to implement an actual compiler), and I was left with this big question dangling in my head.

What is different between implementing a compiler and an interpreter?

To me a compiler is made up of:

Now, obviously, the interpreter also has the same lexer and parser as the compiler.
But what does it do after that?

Does it «read» the syntax tree and execute it directly? (kind of like having an instruction pointer pointing to the current node in the tree, and the execution is one big tree traversal plus the memory management for the call stack) (and if so, how does it do it? I’m hoping the execution is better than a huge switch statement that checks what type of node it is)

Does it generate 3 address code and interpret that? (if so, how does it do it? Again, I’m looking for something more elegant than a mile long switch statement)

Also, at which point does the concept of «virtual machine» cut in? What do you use a virtual machine for in a language? (to be clear about my level of ignorance, to me a virtual machine is VMWare, I have no idea how the concept of VM applies to programming languages / executing programs).

As you can see, my question is quite broad. I’m mostly looking for not only which method is used but mostly to first understand the big concepts, and then get into how it works in detail. I want the ugly, raw details. Obviously, this is more a quest for references to things to read rather than expecting you to answer all these details in here.

EDIT: Thank you for your answers so far. I realized my title was misleading though. I understand the «functional» difference between a compiler and an interpreter.
What i’m looking for is the difference as to how you implement an interpreter, vs a compiler.
I understand now how a compiler is implemented, the question is how an interpreter differs from that.

For example: VB6 is clearly both a compiler and an interpreter. I understand now the compiler part. However, I can not grasp how, when running inside the IDE, it could let me stop the program at any arbitrary point, change the code, and resume execution with the new code. That’s just one tiny example, it’s not the answer i’m looking for. What i’m trying to understand, as I explain below, is what happens after I have a parse tree. A compiler will generate new code from it in the «target» language. What does an interpreter do?

Thank you for your help!

10 Answers 10

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

An interpreter translates a programming language into its semantic meaning.

An x86 chip is an interpreter for x86 machine language.

Javac is a compiler for java to the java virtual machine. java, the executable application, is an interpreter for the jvm.

Some interpreters share some elements of compilation in that they may translate one language into another internal language that is easier to interpret.

Interpreters usually, but not always, feature a read-eval-print loop.

A program is a description of work you want done.

A compiler converts a high-level description into a simpler description.

An interpreter reads a description of what to do and does the work.

Compilers never do the work. Interpreters always do the work.

there is a great deal of leeway in how either are implemented. It is possible for an interpreter to generate native machine code and then execute that, while a compiler for a virtual machine may generate p-code instead of machine code. Threaded interpreted languages like Forth look up keywords in a dictionary and execute their associated native-code function immediately.

compilers can generally optimize better because they have more time to study the code and produce a file for later execution; interpreters have less time to optimize because they tend to execute the code «as is» upon first sight

an interpreter that optimized in the background, learning better ways to execute the code is also possible

summary: the difference really comes down to ‘prepare the code for later execution’ or ‘execute the code right now’

Both have much in common (eg lexical parser) and there is disagreement on the difference. I look at this way:

The classical definition would be that a compiler parses and translates a stream of symbols into a stream of bytes that can be run by the CPU whereas an interpreter does the same thing but translates them a form that must be executed on a piece of software (eg JVM, CLR).

Yet people call ‘javac’ a compiler so the informal definition of a compiler is something that must be done to source code as a separate step whereas interpreters have no ‘build’ step (eg PHP, Perl).

It’s not as clear cut as it used to be. It used to be build a parse tree, bind it, and execute it (often binding at the last second).

BASIC was mostly done this way.

The old school difference was: If it generates CPU code it’s a compiler. If you run it directly in your editing environment and can interact with it while editing, it’s an interpriter.

If my experience indicates anything;

In shot the difference may be as simple as

(It doesn’t matter if you target another language or (virtual) machine instructions.)

In regard to this part of your question, which the other answers haven’t really addressed:

Also, at which point does the concept of «virtual machine» cut in? What do you use a virtual machine for in a language?

Virtual machines like the JVM or the CLR are a layer of abstraction that allow you to reuse JIT compiler optimization, garbage collection and other implementation details for completely different languages that are compiled to run on the VM.

They also help you make the language specification more independent from the actual hardware. For example, while C code is theoretically portable, you constantly have to worry about things like endianness, type size and variable alignment if you actually want to produce portable code. Whereas with Java, the JVM is very clearly specified in these regards, so the language designer and its users don’t have to worry about them; it’s the job of the JVM implementer to implement the specified behaviour on the actual hardware.

Once a parse-tree is available, there are several strategies:

To achieve Edit-and-Continue, the program counter or instruction pointer has to be recalculated and moved. This requires cooperation from the IDE, because code may have been inserted before or after the little yellow arrow.

One way this could be done is to embed the position of the program counter in the parse tree. For instance, there might be a special statement called «break». The program counter only needs to be positioned after the «break» instruction to continue running.

In addition, you have to decide what you want to do about the current stack frame (and variables on the stack). Perhaps popping the current stack, and copying the variables over, or keeping the stack, but patch in a GOTO and RETURN to the current code.

Given your list of steps:

A very simple interpreter (like early BASICs or TCL) would only perform steps one and two one line at a time. And then throw away most of the results while proceeding to the next line to be executed. The other 3 steps would never be performed at all.

If you’re looking for a book, Structure and Interpretation of Computer Programs («the Wizard book») is a good place to start with interpreter concepts. You’re only ever dealing with Scheme code, which can be traversed, evaluated, and passed around as if it were an AST.

Also, Peter Norvig has a short example explaining the main idea using Python (with many more examples in the comments), and here is another small example on Wikipedia.

Like you said, it’s a tree-traversal, and at least for call-by-value it’s a simple one: whenever you see an operator, evaluate the operands fist, then apply the operator. The final value returned is the result of the program (or the statement given to an REPL).

Note that you don’t always have to do the tree traversal explicitly: you could generate your AST in such a way that accepts a visitor (I think SableCC does this), or for very small languages, like the small arithmetic grammars used to demonstrate parser generators, you can just evaluate the result during parsing.

In order to support declarations and assignments, you need to keep an environment around. Just as you’d evaluate «plus» by adding the operands, you’d evaluate the name of a function, variable, etc., by looking it up in the environment. Supporting scope means treating the environment like a stack and pushing and popping things at the right time. In general, how complicated your interpreter is depends on which language features you mean to support. For instance, interpreters make garbage collection and introspection possible.

But note that, for speed reasons, the default Oracle JVM works by translating runs of Java bytecode instructions into x86 instructions («just in time compilation»).

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *