[Solved] How do compliers or interpreters read the source code and convert it into machine code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

[Solved] How do compliers or interpreters read the source code and convert it into machine code?

I was kinda curious for a while that how do compliers converts our code that we write into binary? and how interpreters converts our code into machine-code in modern coding languages? (like python for example)

8th May 2020, 7:58 AM
Rellot's screwdriver
Rellot's screwdriver - avatar
3 Answers
+ 1
An interpreter translates source code into a data structure, and then the interpreter "runs" through the data structure to create the illusion of an executing program. The interpreter uses indicators in the structure to decide what procedures within itself to call to carry out what is specified by the indicators. So, the machine code that the source code is "translated to" was actually pre-compiled before you ever wrote a program with the interpreter. Really what's going on is the interpreter is just using the same package of machine code it carries with it, over and over again, to execute your program. Your program only exists in source code, and in the in-memory data structure that the interpreter constructs. This is in contrast to a compiler, where aspects of your source code are translated directly into object code, with other aspects linked from, or referenced to pre-compiled libraries. With a compiler, the resulting object code operates independently from the program that created it. With an interpreter
8th May 2020, 8:18 AM
ycsvenom
ycsvenom - avatar
0
, no object code is created, and the internal representation of the program, which is "run," is very dependent on the program that created it. An interpreter has three parts: a parser (to read source code, and construct the data structure), a traversal routine (for traversing the constructed data structure, and executing internal routines), and a library of routines that are used by the interpreter to carry out what was originally specified by the source code. This library of routines corresponds to key words and characters that are used in the interpreted language. Transcriped from Quora questions
8th May 2020, 8:19 AM
ycsvenom
ycsvenom - avatar
0
Code is just text so first you "lex" and "parse" the input code into something manageable that you can more easily manipupate in a program, like an "abstract syntax tree". Your "compiler" can use that tree to generate "assembly" code for example, that can be assembled into a .exe by an "assembler". (Words in quotes are things to look up) If you are up for a challenge, look at the programming language brainfuck. First learn to code in it (it's like a puzzle) and then try to write an interpreter for it. It's surprisingly doable. (Extra challenge: make that a brainfuck->python compiler instead)
8th May 2020, 9:55 AM
Schindlabua
Schindlabua - avatar