Compiler vs Interpreter, or does writing a compiler in interpreted language still makes it a compiler? [closed]

StackOverflow https://stackoverflow.com/questions/21102724

  •  27-09-2022
  •  | 
  •  

I am interested in writing a Pascal compiler in JavaScript. But I am confused about what makes a compiler - a compiler and not an interpreter. Specifically do I need to generate byte code or assembly code like C/C++, e.g. a.out?

So if I were to scan and parse hello_world.pas:

program helloworld;
begin
    Writeln('Hello world!');
end.

And generate something like this:

(function() {
  console.log('Hello world!');
})();

Did I just write an interpreter or a compiler?

Any hints or suggestions for writing a compiler in JavaScript would be much appreciated.

有帮助吗?

解决方案

Whether a program is a compiler or an interpreter is determined by its input and output, not by the architecture of the program itself.

A compiler reads in source code written in a high level language and translates it to something else. Most often, compilers generate an executable program in a low level language, usually machine code. From there, all you need is the compiled executable to run the program; you only need the source code and compiler if you want to modify the program.

An interpreter also reads high level source code, but instead of generating an executable it executes the program as it parses. To run a program like this you'll always need a copy of the source code and the interpreter.

Compilers and interpreters are usually compiled, and in the case of compilers, the compiler is often used to compile itself (this is called bootstrapping). But that's just common practice. There's no practical reason why you couldn't write a compiler in an interpreted language.

As to what type of low level language your compiler should output, that depends on what architecture you want your executable to run on. More than likely you'll want to generate assembly language for your platform and then use a preexisting assembler to convert that to machine code.

The code you wrote simply translated the Pascal code into Javascript code. You could think of that as a type of compilation: you're compiling Pascal into Javascript so it can be run by a Javascript interpreter. If you're trying to write something that allows the user to run Pascal code in a web browser, for example, then you've got the right idea.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top