This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com
Yesterday we concluded the live session on live coding a bytecode compiler and interpreter (VM) for a tiny subset of Python in Python. Even though I said I will not be sharing the recording, I think the session went quite smooth so I am sharing it here.
The original goal of the session was quite ambitious to try to implement a non-trivial subset of Python in 3 hours which included loops, conditionals, and functions apart from the basic syntax. We could only get to a small subset of what we planned, but that’s the nature of live coding.
Note that we did not talk about tokenization or parsing, we used Python’s ast module to avoid writing the parser. Discussing or implementing a parser can take several hours in itself and it isn’t as interesting as the compiler, so that wasn’t on the agenda.
Within three hours we were able to cover this much:
* What a compiler does and its components
* Structure of Python’s abstract syntax tree (AST), and a walk through some of the node types that we would be using in our compiler
* Implementing a tree walking interpreter - we started by learning how to evaluate a program by walking an AST.
* Implementing a bytecode compiler and VM incrementally. We covered these features:
* Handling constants
* Assigning values to variables
* Being able to get values back from variables
* Handling binary operations
The original objective was to also cover if/else, while loops and function calls. But it would have probably taken another couple of hours or possibly more.
Prerequisites
If you want to watch it but are concerned about prerequisites, here’s what you need:
* Python
* Pattern matching syntax of Python - if you’ve used pattern matching in other languages such as Rust, Java, Scala, it should not be a problem to understand Python’s pattern matching.
* Recursion - the compiler requires tree traversal to generate the bytecode
Future Iterations
Many people were interested in the session but could not attend because of schedule conflicts.
I will plan it again, but I will most likely have to break it down into multiple parts which might mean multiple committing multiple weekends to it.
I will plan it again if there is significant interest. Please let me know by voting below.
Slides and Code
You can find the slides and code from the session at below links:
Audio and video play straight from the show's own hosting. PodSubs stores and serves no media.
Transcript
From the show. Tap a time to play from there.
SPEAKER_00Can you guys see the screen? Yeah, I can see. So the idea is to live code a compiler for a very small subset of Python. And in that process, we'll talk about the various pieces that go behind the design of a compiler, because we are going to be discussing such a small and simple subset of Python.
SPEAKER_00So it will be very simple. But it should still give you an idea of if you want to extend and add more features, you will have some direction from where to start. The other thing is because compiler is like a huge piece of code. So there are various parts to it, as I will talk about it.
SPEAKER_00So we are only going to be talking about the compiler and the virtual machine interpreter. So the other parts that come behind, sorry, before it, We are not going to be talking about that because that can take probably two or three such sessions before we can get to the compiler. And compiler is actually the interesting part of such an implementation.
SPEAKER_00So while I'm doing this, I might not check the chat. So please just unmute and interrupt if you feel like. So before I start, I want to show what is the goal here. So for example, so this is an implementation that I already made before this talk, just to demonstrate what is the end goal here.
SPEAKER_00So we should be able to do things like this. I mean, if you have, so this is not the actual Python ripple, but a ripple that I have implemented for this compiler. So can assign values to a variable and I can get those values. you can update the values. So now is 11. So basically, you can do some simple math here.
SPEAKER_00You can define functions. Sorry. So this is a reply requires a lot of handling of various edge cases, which is not there. So I want to write a function here. So so it acts one now.
SPEAKER_00So it does that can write loops. So is equal to 10. Why is greater than So now I should be 0. So we can do loops.
SPEAKER_00Not sure if. And we can do conditionals. So if I is greater than 10. So we can do conditions or things like that. So very basic, simple subset of Python.
SPEAKER_00So we can have simple math. So addition minus division multiplication, we can assign various values to variables, we can have constants, we can have if else conditions, we can have while loops, so there is no for loop, we can write simple functions, we could do recursion also. Uh, what else? So just this much subset of Python. Um, so that is the goal. Um, so I've given us around three hours or 20 minutes of pass.
SPEAKER_00So two hours or 40 minutes we have left here. Uh, we might not be able to get to all of this, but let's see how much we can cover and we'll do this incrementally. Um, so every small feature that we add, we'll go do, uh, feature by feature and incrementally make the implementation more complicated. So I'll try to start with a clean slate and basically take you through what why something is required in the compiler and in the virtual machine.
SPEAKER_00And the other thing is the whole virtual machine and the compiler, in spirit, it is going to be very similar to what the Python compiler and the interpreter does. Even though we are going to be writing all of this in Python, and the actual C Python is implemented in C, but the instruction code format, the virtual machine design,
SPEAKER_00those are going to be very similar to what the way Python implements those things. So if you understand this part, you will have a better understanding of how those parts work in Python implementation as well. So if you have some familiarity with C, you could go and look at that code as well after this. With that, I'll start. So I have a few slides, because we have to get some background before we can actually get into the code.
SPEAKER_00Okay. So as I said, a compiler is a very complicated system. There are various modules to a compiler and every module is Modules implementation is like a project in itself. Usually within a compiler team, there are various people who are specializing in different parts of this. So here are those four, broadly speaking, four stages or four parts that a compiler has to have. So you start with the source code where you actually, whatever is your source language.
SPEAKER_00For example, here we have Python. First of all, we tokenize it. So usually it's called a tokenizer or a Lexer module that you have to implement. And what it does is it scans the source code character by character, and it translates them into a discrete sequence of tokens. Tokens are essentially identifiers or names categorizing those symbols within your code.
SPEAKER_00So for example, here, what I've shown here, if I have this simple line of Python code is equal to B plus C, and I pass it through the tokenizer, it will produce this list of tokens. This is very similar to what the Python tokenizer would also produce. So it will have some for A. So A is an identifier, it identifies a value. So we refer to it as a variable, but in compilers, you see variables being referred to as identifiers,
SPEAKER_00because it's not just variables that you refer by a name. You also refer to many other things like function names are also identifiers. When you import objects from other modules, those are also referred by names. So those become identifiers. So you have to have, so basically this is a broader way to call it. So A becomes an identifier token and the token object itself will also contain information about that token. So here we know that it is an identifier token and the actual name of the token is
SPEAKER_00also embedded inside of it. So this is the complete definition of an identifier token. After that, we have the assignment. So it will be an assigned token with the operator embedded within it. Then again, we have B, which is again an identifier. with the name b. Then we have an operator. So we have an add token here to identify that this is add. So you will have different tokens for other operators like subtract, multiply, divide, and so on.
SPEAKER_00And then finally, we have another identifier for the c variable. So this is how token tokenization works. sound sample, you have to implement it. Usually, you do it character by character, or you use regular expressions to do that pattern matching. So different patterns match to different tokens. Apart from these, you will also have some prominent token types. So you will have keyword token types. So as I said, every language has certain keywords.
SPEAKER_00So for example, Python will have def, return, if, else. So those become keywords. So you will have a keyword token and then that token object will contain the actual keyword name or the value. So once you have this sequence of tokens produced by the tokenizer, then we come to the parsing stage. So there is a parser model, which takes this stream of tokens and goes through that and tries to make sense of
SPEAKER_00what this program actually represents. So So it produces something called an abstract syntax tree, also commonly referred everywhere as AST. So essentially, if you think about any natural language, so for example, if you see English language, so if you take a dictionary, you will have thousands of words defined in it. any random sequence of any words, if you take from that dictionary, it doesn't really make sense.
SPEAKER_00So English language has a grammar that following those rules, we can make sense of those words. So there is only a specific order in which certain words are actually sensible. Any other arbitrary sequence of those words is basically gibberish. So the same thing applies in programming languages, even though, uh, you can have hundreds of tokens within that language, but only a certain sequence of tokens is actually,
SPEAKER_00uh, can represent the program. So that is called the grammar of that language. Uh, so Python also has a grammar, every language has a grammar. Uh, so basically it maps, it basically defines if, uh, If this sequence of tokens has been seen, then what should be the expected, what are the allowed sequence of tokens that can come after this sequence of tokens? Anything else will not be allowed and the compiler will give you a compilation error.
SPEAKER_00So for example, if I miss a colon in my if after the if condition in Python, you'll get a compiler error because basically anything after that doesn't really make sense. The compiler expects after a condition that it should be a colon token. If you don't have it, that program doesn't really make sense. So the compiler follows that grammar and takes the sequence of tokens and makes sure that the program follows that grammar. And based on if it follows those rules of the grammar,
SPEAKER_00then the compiler will produce this data structure in a tree format. So for example, in our A is equal to B plus C, it will produce this tree. the B plus C expression will translate into this binary node. So you have the plus node here, and it needs to left and right operands to operate the plus operator. And then we have the result of this has to be assigned to the variable a.
SPEAKER_00So we have the assignment operator here as the parent. So the right hand side of the assignment operator is another expression and the left hand side is the destination where the result of this right hand side has to be assigned. So you have similarly, for every kind of expression in your program, in your syntax, you would have corresponding node type defined. So we have assign node for handling assignment operations, we have binary op node for handling binary math operations.
SPEAKER_00Just referring a variable by its name results in a name node, you will have a constant node for representing constant values will come across all of those. So once the parser stage is done, you have the AST ready. Then comes the compiler part. This is what we are going to be doing today. So the compiler takes this AST, the tree that was produced by the parser and walks through that tree and produces a sequence of instructions.
SPEAKER_00These instructions can be targeted towards the actual hardware. So for example, if I'm writing a C compiler, I will walk this tree and emit the assembly instructions supported by the hardware. So for example, I will emit instruction for the x86 hardware. Or those instructions can be for a virtual machine. a machine which is implemented within the software itself. So that machine will have its own instructions.
SPEAKER_00In case of Python, it implements a virtual machine. It has its own instruction set. So for example, on the right-hand side, I have shown the instructions that should be generated for executing this line of code in the CPython interpreter itself. So it will generate two load instructions. loading the values B and C on the stack. I'll talk about a stack and everything. Then it will emit a binary operation node instruction for executing the plus operation.
SPEAKER_00So basically, it will pop the two values from the stack, apply this plus operation, whatever is the result, it will push on the stack. And then you want to assign the result into A. So there will be a store global instruction, which has to be emitted for assigning or storing that value into A. So there are hundreds of instructions that the Python virtual machine supports.
SPEAKER_00We'll cover a few of those, probably 15 or 20. So this is the overall structure of a typical compiler project, we are going to be doing these final two parts, the compiler and the interpreter. Okay, so this is more slightly more sophisticated example of the tokenization here.
SPEAKER_00So I have a function defing why it does something. So if I take it through the tokenizer, it will produce this sequence of tokens here. So for def is a keyword in Python. So it will emit a keyword token here with the value embedded in as def.
SPEAKER_00It will also usually a production quality compiler should token either should also include line and column information so that when you have to report an error, syntax error, you should be able to point to the exact line and column where you found the problem. So it will also have the line and column of each token. Def is a keyword, then ink is a function name. So it will become an identifier. I have some here, this is a typo, should have been ink, and line and column information about that.
SPEAKER_00Then we have left parenthesis, there will be a token for that. Then again, we have the parameter y, which is an identifier node, an identifier token. Then we have our parent, then we have colon, then we will have a new line, Python, because Python is white space sensitive. So it has to track new lines and tabs and everything. So it will emit those tokens as well. Again, on the next line, we have the result variable. So that becomes an identifier. Then we have an assigned token.
SPEAKER_00One is a constant. So we will the constant token or some number token should have been a number. So this is how usually a tokenizer has to work. So in this session, we are going to be working directly from the output of the parser. So we are going to be skipping the tokenization and the parsing stage. And we are just going to take the parser output generated by the Python's AST module.
SPEAKER_00So Python comes with the AST module, which you can use to parse any Python code. So we are going to be taking advantage of that. So we'll give it all the Python code that we want to run. It will give us the AST, and then we will work with the AST to implement our compiler. Now, because we are doing that way, we have to understand the structure of Python's AST. So what are the various nodes in that tree? Nodes and their types and what it looks like. So I want to give you a general idea of that. The advantage of learning this is that you will also,
SPEAKER_00so this is exactly how the Python parser produces the AST. So you will learn that. So these are all handwritten notes that I have. I don't really have slides for this part. So just bear with me. Any questions if you have, you're not able to read, just feel free to ask. So one of the basic nodes that you will have is the constant node. So any literal that you define in your program,
SPEAKER_00like here, I have 42, 3.14, the string, hello, all of these are constants. And the Python AST has a dedicated constant node. It's called constant. which contains that value. So here, you will have 42 converted into a constant node with a value 42, or 3.14 becomes constant with the value 3.14, so on. Pretty simple. Then you have name nodes. So any names that you have in your program, these could be variable names, function names,
SPEAKER_00any external externally imported names that you have, if you import any name from another module, those become names. So anything you refer in your code, those are names. So those become name nodes. So essentially this is a very simple node. It's called name and it contains the name of the identifier that you are trying to refer to. So if in my code, I have X, the parser is going to convert it into name x, essentially convert into a name node with the name of the identifier.
SPEAKER_00Pretty simple. After that, let's take it one step forward. So you have constants, we have names. Now, if I want to assign that a constant to a variable, so it becomes an assigned node. So we have four is equal to 42. For any assignment, the parcel generates an assigned node. Now, assigned node contains two fields inside it.
SPEAKER_00there will be a list of targets. Here, we only have one target, which is full. But if you see Python, you can assign on the left hand side of the operator, assign operator, you can have a list of comma separated list of names, you can assign to multiple variables in a single go. So that is why the assign node is a list of targets. But in our implementation, we are not really going to be worried about that. We are just going to handle one assignment per equals operation.
SPEAKER_00But because we are working with Python CST, we have to understand that this is a list rather than a single target. And after the targets, we have the value. So what is the value that you want to assign? So we have the value. Now again, value is a constant. So right inside here is a constant node. So you see the left hand side of equals is a name node. And the right hand side is a constant node. And combine those, we have the assign node. Assign is an operation or an operator.
SPEAKER_00After that, one slightly more complicated one is binary operations. So here I have B plus one as an expression. So B plus one is a binary expression. We are applying the plus operation on two operands, B and one. So Python AST supports a node called bin op. And it has three fields inside it, the left, the right, and the operation that we're applying.
SPEAKER_00Again, depending on what is there on the left and right of the operator, you will have a different type of node here. So for example, on the left of plus, we have B, which is a name. So we have name B here. And on the right, we have a constant. So we have constant one here. If both be both sites for constants, we would have had been up constant at constant in both sites for names, we would have had been up name at me.
SPEAKER_00Okay, so some more examples here. So if I say, we have already seen this. So when you say A is equal to 10, this will be the result, assign value constant 10 to the name A. if I say B is equal to minus three, so minus in isolation, as in here, it represents an unary op in Python. So it has its own node type here, I did not talk about it previously.
SPEAKER_00So this basically becomes assigned to be the result of unary of, uh, and you need, so you can have various kinds of unit operators in Python, the current, the one, which we are talking about here is subtraction. So that is the operator. And then the value on which this operation has to be applied. The result of this is going to be assigned to name B. Similarly, C is equal to A into B will be a binary op node.
SPEAKER_00Left and right are names A and B, and the operator is mult. So this is the overall, the kind of nodes, ASL nodes that we are going to be dealing with. You will get used to it as we are going to be seeing a lot of these. But any questions till this part, something which is not clear?
SPEAKER_00Okay. One more note about the AST nodes. So there are broadly two kinds of nodes that are there in any AST. So there are expression nodes, and then there are statement nodes. So the statements are essentially any statements represent any code that does not produce a value.
SPEAKER_00So for example, when you say A is equal to 10, so you're assigning the value 10 to the variable A, but that line of code does not produce a value. Whereas when you say, I don't know, x plus one, x plus one becomes an expression because x plus one will produce a value. pretty evident when you run something on the Python REPL. So when you write x plus one on the REPL, it will print the result of that expression.
SPEAKER_00Whereas when you say a is equal to 10, it does not print anything as it's output because it does not produce a value. So that's the broad distinction between the two types of nodes that are present within the Python AST. And this is true for any kind of AST. You will see that kind of categorization of nodes. So this is used to implement the object class hierarchy within the AST. So what what this means is that every node type within the Python AST is
SPEAKER_00essentially a statement type node, even the expression type nodes are a special case of statement type nodes. So every node can be represented as a statement within the tree. And, but expression nodes are represented by expr type expression and statement nodes have a type called statement. So this is, we'll soon see this in action in a few moments.
SPEAKER_00Okay. This is the end of my slides. So what we are going to do here is Can you see this code window? Yes. Okay, so we'll start by implementing a tree walking interpretive.
SPEAKER_00So this will give us a better idea of the AST itself, the structure of the AST and what how to walk the AST to do something. And once you understand that the compiler is just a slightly more complicated form of tree walking. So that becomes easier after that. So Okay, let me start from the scratch. So what I have here. So I have this project I've already created,
SPEAKER_00but none of the files that actually contain any code, I just have the skeleton here. So I have this compiler module created. where we'll write all the code. I have a REPL ready. So we'll use it to test some of the code that we're implementing. I have some tests here. So I have some tests for the interpreter that I'm going to implement.
SPEAKER_00Just now I have some tests, a suite of tests for compiler and the VM that will make it pass one by one. Right now, all the tests will fail. So I run the compiler test. It fails. It's getting some import errors. We'll fix all of these. So as we go, Okay, so within my compiler package, I have this AST interpreter.py file,
SPEAKER_00where I am going to implement the interpreter. The interpreter takes the AST as a parameter here, and it is going to evaluate whatever the result of that program is. So AST represented some Python program here. Okay, I did not talk about this part. So what happened? How does the Python?
SPEAKER_00So what's the overall output of the Python parser? We talked about individual nodes, but I have to talk about. Okay, I have something. Yeah.
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com In the last video, we learned about copy-on-write (CoW) and understood its mechanics by digging inside the mmap pathway in the...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com In the last video, we discussed demand paging. Now, let’s move towards an even more interesting topic: copy-on-write (CoW). Just...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com In the previous video in our virtual memory series, we discussed demand paging. But that was mostly theoretical, explaining how...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com Welcome back to the video series on virtual memory based on my article on the same topic. It is also available in ebook format on...
This is a free preview of a paid episode. To hear more, visit blog.codingconfessions.com This is a short aside in our virtual memory series. We have talked extensively about the size of a virtual address and the virtual...