Latest / CyberSecurity Summary / Writing a C Compiler: Build a Real Programming Language from Scratch
Transcript
- 0:00Speaker 1: Welcome to the deep dive. Today, we're tackling something fundamental
- 0:04Speaker 1: yet often unseen in the world of coding. The compiler.
- 0:08Speaker 1: Think of it as the architect behind the scenes, taking
- 0:12Speaker 1: your human readable instructions and blueprinting them into the precise
- 0:16Speaker 1: machine language your computer understands precisely.
- 0:19Speaker 2: And for this deep dive, we're not just talking about
- 0:21Speaker 2: compilers conceptually. We're getting into the initial stages of building
- 0:24Speaker 2: our own. Our mission is to really dissect the core
- 0:28Speaker 2: transformations required to compile even the most well the simplest
- 0:32Speaker 2: see programs.
- 0:33Speaker 1: And to guide this architectural exploration, we'll be using excerpts
- 0:37Speaker 1: from Writing a C Compiler as our foundational text. It's
- 0:40Speaker 1: our guide as we uncover how source code undergoes its
- 0:43Speaker 1: initial metamorphosis into executable form. Okay, let's unpack this, let's
- 0:47Speaker 1: do it. Our compiler construction starts with establishing a modular
- 0:51Speaker 1: pipeline of four key stages.
- 0:53Speaker 2: That's right. Yeah, even for the simplest stuff like maybe
- 0:55Speaker 2: not even Hello World, maybe just returning a number, will
- 0:59Speaker 2: be setting up a four pass structure. The first of.
- 1:01Speaker 1: These is the lex lexer or tokenizer.
- 1:04Speaker 2: Right or tokenizer, Yeah, same thing.
- 1:06Speaker 1: So the lexer's fundamental task is to scan our c
- 1:09Speaker 1: code and break it down into its essential components, right
- 1:12Speaker 1: like identifying the individual building blocks before you start assembling
- 1:15Speaker 1: them exactly.
- 1:16Speaker 2: These smallest meaningful units are the tokens. Think about curly braces,
- 1:23Speaker 2: defining scope, the summit, colon, ending statements, see words like
- 1:27Speaker 2: int right, int return, and then the identifiers you create
- 1:31Speaker 2: for functions, variables. All of these are distinct tokens. The
- 1:34Speaker 2: lexer read your code character by character and groups them intelligently.
- 1:37Speaker 1: I see, so a basic line like into main return
- 1:40Speaker 1: thirty two would be segmented into tokens int main return
- 1:44Speaker 1: thirty two taxes.
- 1:45Speaker 2: Enter exactly that sequence.
- 1:47Speaker 1: Okay, what's the next step after this initial segmentation.
- 1:51Speaker 2: Following tokenization gives the parser? It takes that linear sequence
- 1:55Speaker 2: of tokens.
- 1:55Speaker 1: Just a list basically just a list.
- 1:57Speaker 2: And imposes a hierarchical structure. It constructs what's known as
- 2:01Speaker 2: an abstract syntax tree or at an AST.
- 2:04Speaker 1: Okay, so instead of just a flat list, we get
- 2:06Speaker 1: a structured representation that shows how these tokens relate to
- 2:09Speaker 1: each other.
- 2:10Speaker 2: Precisely. Think of it as moving from say a list
- 2:13Speaker 2: of ingredients to an actual recipe.
- 2:15Speaker 1: Oh nice analogy.
- 2:17Speaker 2: The AST is this tree like structure that embodies the
- 2:21Speaker 2: grammatical rules of C and reveals the program's operational flow.
- 2:25Speaker 2: It's a format that lets the compiler analyze and well
- 2:29Speaker 2: understand the codes intent much better than just that stream of.
- 2:33Speaker 1: Tokens, right, because just having a list of words doesn't
- 2:37Speaker 1: tell you the sentence structure of the meaning exactly. So,
- 2:39Speaker 1: for our example in Maine return thirty two, what would
- 2:44Speaker 1: the AST look like in its simplest form.
- 2:46Speaker 2: In a simplified view, the root might be a program node, okay.
- 2:50Speaker 2: Descending from that, you'd have a function node for Maine.
- 2:53Speaker 2: Inside the function there'd be a return node, and finally,
- 2:56Speaker 2: connected to return, a constant node holding the value.
- 2:59Speaker 1: There So it visually organizes the program's components and their relationships.
- 3:04Speaker 1: Function contains a return statement which returns a.
- 3:07Speaker 2: Constant exactly captures that structure.
- 3:09Speaker 1: Interesting, Now the compiler has this structured tree. What happens
- 3:12Speaker 1: next in the transformation.
- 3:14Speaker 2: This is where the translation to a lower level language begins.
- 3:17Speaker 2: The code generation pass takes the AST the tree we
- 3:21Speaker 2: just spilled, yes, that tree, and translates it into assembly
- 3:25Speaker 2: language instruction assembly.
- 3:26Speaker 1: Okay, that's much closer to the hardware, right exactly.
- 3:29Speaker 2: And it's important to understand at this stage the compiler
- 3:33Speaker 2: isn't directly writing out like a human readable assembly text file.
- 3:38Speaker 2: Oh okay, it's still manipulating data structures internally. It's creating
- 3:42Speaker 2: an in memory representation of these assembly instructions.
- 3:46Speaker 1: So the creation of the actual DOTS file comes later.
- 3:49Speaker 2: Yes, that's the job of the fourth initial pass code emission, right.
- 3:53Speaker 2: This pass takes the in memory assembly representation what just
- 3:57Speaker 2: created and finally writes it out, serializes it into a file,
- 4:02Speaker 2: usually with the dot extension.
- 4:03Speaker 1: And that S file is what the assembler and linker
- 4:06Speaker 1: use later on.
- 4:07Speaker 2: That's the one they take that and produce your final
- 4:09Speaker 2: executable program.
- 4:10Speaker 1: It seems like a considerable number of steps for such
- 4:13Speaker 1: a basic program, you know, return thirty two. Why not
- 4:15Speaker 1: a more direct approach.
- 4:17Speaker 2: That's a really fair question. Again, it might seem like
- 4:19Speaker 2: overkill for these tiny examples, but establishing this multipass architecture
- 4:24Speaker 2: right from the start gives us huge advantages later. By
- 4:28Speaker 2: separating concerns lexical analysis here, syntax there, cogen over here,
- 4:33Speaker 2: modularity exactly, modularity, we create a more maintainable system. Imagine
- 4:39Speaker 2: trying to translate I don't know, a complex novel straight
- 4:42Speaker 2: into another language without first understanding the grammar and structure.
- 4:45Speaker 1: Yeah, that would be a mess.
- 4:46Speaker 2: It would be incredibly hard. This separation lets us handle
- 4:49Speaker 2: more complexity later without having to rip everything up and
- 4:52Speaker 2: start again. It's really about building a scalable foundation that.
- 4:55Speaker 1: Makes a lot of sense planning for future complexity. Okay,
- 4:58Speaker 1: speaking of assembly language, can we actually peek under the
- 5:01Speaker 1: hood see what a real compiler like GCC generates for
- 5:04Speaker 1: a simple C program.
- 5:06Speaker 2: That's an excellent idea. It helps ground this discussion. For
- 5:09Speaker 2: a simple program like in main return two saved us
- 5:12Speaker 2: say return two dot C. You can use GCC with
- 5:15Speaker 2: some specific commandline flags gccss and f and O. A
- 5:18Speaker 2: secret is unwine tables FCF protection none, return two dot
- 5:22Speaker 2: e t whoa.
- 5:24Speaker 1: Okay, lots of flags there, but the key is mesh
- 5:26Speaker 1: s ash.
- 5:27Speaker 2: This is the main one telling it to stop after
- 5:29Speaker 2: compilation and output assembly. The others just simplify the output
- 5:32Speaker 2: a bit for our purposes.
- 5:33Speaker 1: Got it, And what's the output look like?
- 5:35Speaker 2: This command generates a file probably return two dots. With
- 5:38Speaker 2: the assembly for that C program, you'll likely see something
- 5:41Speaker 2: really simple like dot globalmine, dot main, dot movell two
- 5:45Speaker 2: dollars percent ax red.
- 5:48Speaker 1: Okay, that's definitely not c what's going on.
- 5:50Speaker 2: Here, Let's break it down. The syntax is AT and
- 5:53Speaker 2: T assembly syntax common on Linux and mac os. That
- 5:56Speaker 2: first line dot global main that starts with a period, right,
- 6:00Speaker 2: That means it's an assembler directive. It's an instruction for
- 6:02Speaker 2: the assembler itself, not the CPU docl WI main just
- 6:06Speaker 2: makes the main symbol visible outside this.
- 6:08Speaker 1: File, a symbol like a label or a name for
- 6:10Speaker 1: a place in memory.
- 6:11Speaker 2: Precisely. Here, Maine is a symbol representing the starting address
- 6:14Speaker 2: of our main function. The compiler doesn't know the final
- 6:17Speaker 2: address yet. The linker figures that out later. Ah.
- 6:19Speaker 1: The linker's job resolving symbols exactly.
- 6:23Speaker 2: It resolves them assigns actual memory locations. If code refers
- 6:27Speaker 2: to Maine, the linker patches in the real address. That's
- 6:30Speaker 2: called relocation.
- 6:31Speaker 1: So Maine on the next line is just marking the
- 6:33Speaker 1: spot the start of the code exactly.
- 6:35Speaker 2: It's the label. Then move two dollars percent ax. That's
- 6:39Speaker 2: a real instruction.
- 6:40Speaker 1: MOLL move long thirty two bit.
- 6:43Speaker 2: Yep thirty two bit integer two dollars means the literal value.
- 6:47Speaker 1: Too an immediate value, right, and percent.
- 6:49Speaker 2: X is a register, a small fast storage spot inside
- 6:52Speaker 2: the CPU. So this instruction puts the value too into
- 6:55Speaker 2: the percent ax register.
- 6:57Speaker 1: Okay, but y percent x specifically convention.
- 7:01Speaker 2: In many standard ways, functions call each other calling conventions,
- 7:04Speaker 2: the percent x register is designated to hold the function's
- 7:07Speaker 2: return value.
- 7:08Speaker 1: Oh okay, So because our C code returns two, we put.
- 7:10Speaker 2: Two in percent acts so whoever called main can find
- 7:13Speaker 2: the result.
- 7:13Speaker 1: There makes sense. And the last line writ.
- 7:16Speaker 2: Just means return tells the CPU to go back to
- 7:18Speaker 2: where main was called from. So yeah, those four lines
- 7:20Speaker 2: are the complete assembly for a tiny C program.
- 7:23Speaker 1: That's surprisingly direct.
- 7:25Speaker 2: Cool.
- 7:26Speaker 1: So when we compile a C program, even with our
- 7:28Speaker 1: own simple compiler, what's the typical sequence of operations overall?
- 7:31Speaker 2: Right? So while our first compiler focuses mainly on that
- 7:34Speaker 2: compilation to assembly.
- 7:35Speaker 1: Step step two, in the usual process, Yeah, the standard.
- 7:38Speaker 2: C process has a few phases. First, there's pre processing.
- 7:42Speaker 1: Handling hashtag include and macros and stuff.
- 7:44Speaker 2: Exactly Commands like GCCE do this. It often outputs a
- 7:48Speaker 2: DITI file.
- 7:49Speaker 1: Then comes compilation proper our focus generating the didass assembly
- 7:53Speaker 1: file correct?
- 7:53Speaker 2: Then in a full setup you have assembly and linking
- 7:56Speaker 2: usually just GCC assembly file. Oh, output file.
- 8:00Speaker 1: Takes the dot S file, makes machine code, links libraries.
- 8:03Speaker 2: And gives you the final executable. Right. Our initial compiler
- 8:06Speaker 2: will sort of stub out that last step, relying on
- 8:08Speaker 2: the system's assembler and linker. Gotcha.
- 8:10Speaker 1: And for our own compiler driver, the command line tool
- 8:13Speaker 1: we're building, how should.
- 8:14Speaker 2: That behave, good question. It should take the path to
- 8:17Speaker 2: a C source file like your compiler paths to program
- 8:19Speaker 2: dot C. If it works, success, it should create an
- 8:23Speaker 2: executable in the same directory, same name, but no dot C.
- 8:26Speaker 2: So pats a program and exit with code zero. And
- 8:29Speaker 2: if it fails, non zero exit code and crucially no
- 8:32Speaker 2: output files, no executable, clean failure.
- 8:36Speaker 1: Clear rules. And I saw mentions of lex and parse
- 8:39Speaker 1: options in the notes.
- 8:40Speaker 2: Uh yeah, those are mostly for testing and debugging. Our
- 8:43Speaker 2: compiler lexmis just run the lexer.
- 8:45Speaker 1: And stop check tokenizing, right, and.
- 8:48Speaker 2: Parse runs the lexer and parser builds the AST then stops.
- 8:52Speaker 2: Neither should create any output files, they just check those
- 8:55Speaker 2: stages internally.
- 8:56Speaker 1: Okay, that makes sense for development. All right, we've got
- 8:59Speaker 1: a solid high light picture. The four passes the standard
- 9:01Speaker 1: GCC flow. Let's dive deeper into the lexer and pulser.
- 9:06Speaker 1: Now they're the first big hurdle in building our own
- 9:08Speaker 1: right absolutely.
- 9:09Speaker 2: Chapter two of the guide digs into building these starting
- 9:13Speaker 2: with the lexer. As we said, its job is finding tokens,
- 9:17Speaker 2: and one simplifying assumption we make early on is that
- 9:19Speaker 2: our c files only use ASKI characters.
- 9:22Speaker 1: Just standard ask you for now sensible starting point. How
- 9:25Speaker 1: do we actually test if our lexer is doing the
- 9:27Speaker 1: right thing.
- 9:28Speaker 2: The guide provides a test compiler tool, which is super helpful.
- 9:31Speaker 2: It comes with test programs. In test chapter two, you'll
- 9:33Speaker 2: find directories like invalid.
- 9:35Speaker 1: Lex programs that should fail the lexer.
- 9:37Speaker 2: Exactly, bad tokens, weird characters, and then invalid parts and
- 9:41Speaker 2: valid directories. For later stages. You test the lexer specifically
- 9:46Speaker 2: using dot test compiler path toward compiler chapter two stage lex.
- 9:50Speaker 1: Okay, So that command runs our compiler inlex only mode
- 9:53Speaker 1: against those test cases and checks if it accepts or
- 9:56Speaker 1: rejects them correctly.
- 9:57Speaker 2: That's the idea. It verifies the pass feel behavior. It
- 10:00Speaker 2: doesn't necessarily check the exact stream of tokens for the
- 10:03Speaker 2: valid files.
- 10:04Speaker 1: Though, ah so for that level of detail, we'd need
- 10:07Speaker 1: our own unit tests.
- 10:08Speaker 2: Precisely, you'd write tests to feed it valid code and
- 10:11Speaker 2: assert that the token list matches exactly what you expect,
- 10:14Speaker 2: and feed it invalid code to check the error messages.
- 10:17Speaker 1: Got it? Any key implementation tips for the lexer itself, Yes.
- 10:20Speaker 2: A couple of important ones. First, when you see something
- 10:23Speaker 2: that looks like an identifier, a sequence of letters, numbers,
- 10:25Speaker 2: underscores like maine or my variable right your logic. Maybe
- 10:29Speaker 2: your rejects will probably also match keywords like int or return.
- 10:33Speaker 2: The efficient way is first recognize it as a generic identifier.
- 10:37Speaker 2: Then check if that identifier happens to be on the
- 10:40Speaker 2: list of reserved keywords.
- 10:41Speaker 1: Ah, don't try to make the initial pattern, distinguish them, identify, then.
- 10:45Speaker 2: Classify exactly two steps. The other thing is, don't rely
- 10:49Speaker 2: only on white space to split tokens. Oh right, think
- 10:52Speaker 2: about main. That's three tokens main and no white space
- 10:55Speaker 2: separating them. If you just split on spaces, you'd get
- 10:59Speaker 2: it wrong.
- 10:59Speaker 1: Point Okay, So the lexer spins out tokens. Then the
- 11:03Speaker 1: parser steps in to build the ast exactly.
- 11:06Speaker 2: The parser takes that flat stream and gives it structure
- 11:10Speaker 2: hierarchy based on the C grammar. The AST is the
- 11:13Speaker 2: data structure holding that hierarchy.
- 11:15Speaker 1: We saw the simple AST for return thirty two. What
- 11:18Speaker 1: about something slightly more complex, like an if statement. How
- 11:22Speaker 1: does the hierarchy show up there?
- 11:23Speaker 2: Okay, good example. Let's say you have if ab return
- 11:27Speaker 2: two plus two. Right, the top AST node might be
- 11:29Speaker 2: an if node. This if node would have say, two
- 11:32Speaker 2: main children, one for the condition.
- 11:34Speaker 1: Ab, which itself might be structured.
- 11:36Speaker 2: Oh yeah, that condition could be a binary op node
- 11:38Speaker 2: for with this own children for the variable A and
- 11:40Speaker 2: the variable b.
- 11:41Speaker 1: Okay, and the other child of the if.
- 11:43Speaker 2: That would be the then block return two plus two.
- 11:46Speaker 2: That could be a return node, and its child would
- 11:48Speaker 2: be another binary op node for the plus with two
- 11:52Speaker 2: constant children both holding to wow.
- 11:54Speaker 1: Okay, So the tree really mirrors the nesting and the
- 11:57Speaker 1: logic if conditioned then and the condition the then part
- 12:00Speaker 1: have their own little subtrees.
- 12:02Speaker 2: Decisely, it captures that structure directly, which is what the
- 12:04Speaker 2: next stages need now. To define these AST structures formally
- 12:08Speaker 2: and importantly in a language neutral way, the guide introduces
- 12:12Speaker 2: something called ASDL.
- 12:13Speaker 1: Asdl zephyr abstract syntax description language.
- 12:16Speaker 2: That's the one. It's just a formal way to write
- 12:18Speaker 2: down what our AST nodes look like.
- 12:20Speaker 1: Okay, So what does the ASDL look like for our
- 12:23Speaker 1: super simple C subset in chapter two?
- 12:25Speaker 2: It's pretty minimal. It's like program program function definition, function definition, function,
- 12:30Speaker 2: identify your name, statement, body, return next, sovisp.
- 12:34Speaker 1: Okay, let's decode that a program is just a program
- 12:37Speaker 1: node containing one function definition. Yep, A function definition is
- 12:40Speaker 1: a function node. It has a name, which is an
- 12:43Speaker 1: identifier type, and a body which is a statement type.
- 12:47Speaker 2: Right, and those words name and body are just field
- 12:49Speaker 2: names helpful labels.
- 12:51Speaker 1: Gotcha. Then a statement can only be a return node
- 12:54Speaker 1: containing an x expression for now, yes, and an x
- 12:57Speaker 1: can only be a constant node holding an int.
- 13:00Speaker 2: That's it for chapter two. Identifier and int are like
- 13:03Speaker 2: built in ASDL types.
- 13:05Speaker 1: So when we implement this, say in Python or Rust
- 13:08Speaker 1: or drava, will create classes or data types that match
- 13:12Speaker 1: this ASDL structure exactly.
- 13:15Speaker 2: Functional languages might use algebraic data types. OP languages might
- 13:18Speaker 2: use abstract classes and inheritance. The guide mentioned some idioms
- 13:22Speaker 2: and points to more reading if you want to go
- 13:23Speaker 2: deeper into implementation strategies.
- 13:25Speaker 1: Okay, but the ASDL defines the structure, but it doesn't
- 13:28Speaker 1: tell the parser which tokens in what order make up
- 13:32Speaker 1: say a function definition. Right, it doesn't mention the ind
- 13:34Speaker 1: keyword or the parentheses or braces.
- 13:37Speaker 2: That is a crucial distinction. You're absolutely right. The AST
- 13:39Speaker 2: is abstract. It leaves out the syntactic sugar like semicolons embraces.
- 13:43Speaker 2: The parser needs a concrete map of the token sequences.
- 13:45Speaker 1: Which is where the formal grammar comes.
- 13:47Speaker 2: In, exactly, using a notation called backus nair form or
- 13:50Speaker 2: BNF BNF.
- 13:52Speaker 1: Okay, what's the BNF for this simplecy it mirrors.
- 13:55Speaker 2: The ASDL pretty closely. The program function I identify return
- 14:00Speaker 2: expeed a statement return expediment, and then it clarifies the
- 14:04Speaker 2: terminals identifier an identify your token and in a constant.
- 14:09Speaker 1: Token then okay, So things in angle brackets like this
- 14:11Speaker 1: are non terminals. They correspond to our AST node types.
- 14:15Speaker 2: Yes, grammatical categories.
- 14:16Speaker 1: And things in quotes like this are terminals. The actual
- 14:19Speaker 1: tokens the lexer gives.
- 14:20Speaker 2: Us exactly the literal tokens we expect to see. The
- 14:23Speaker 2: bn F spells out the exact sequence and int token.
- 14:27Speaker 2: Then an identifier token then art rcedo a statement right,
- 14:31Speaker 2: and the.
- 14:32Speaker 1: Question mark definitions are just clarifying what kind of token
- 14:35Speaker 1: identifier and in refer to. So the BNF is the
- 14:38Speaker 1: parser's rulebook for matching token sequences to build the AST
- 14:42Speaker 1: nodes defined by the asdo.
- 14:43Speaker 2: You've got it perfect summary. The guide also shows how
- 14:46Speaker 2: you'd extend bn F like adding an if statement rules
- 14:49Speaker 2: ifpanis statement l statement the brackets mean the l's part
- 14:53Speaker 2: is optional neat Okay.
- 14:54Speaker 1: So we have tokens, the ASDL defining the target AST
- 14:58Speaker 1: and the BNF grammar as a rule book. How does
- 15:01Speaker 1: the parser actually do the parsing? What's the technique?
- 15:04Speaker 2: The guide introduces a common technique called recursive descent parsing.
- 15:08Speaker 1: Recursive dissent sounds intriguing.
- 15:10Speaker 2: The basic idea is simple, For each non terminal symbol
- 15:14Speaker 2: in the BNF grammar, like program function statement, you write
- 15:18Speaker 2: a corresponding parsing function.
- 15:20Speaker 1: Okay, a function for each rule.
- 15:22Speaker 2: Pretty much, and these functions often call each other, mirroring
- 15:25Speaker 2: the structure of the grammar. That's the recursive part.
- 15:27Speaker 1: Ah okay, So how would parse statement work based on
- 15:31Speaker 1: our simple grammar?
- 15:32Speaker 2: Well, the rule is statement return x biller. So the
- 15:35Speaker 2: par statement function would first look for a return token. Okay,
- 15:38Speaker 2: if it finds one, it consumes it. Then it needs
- 15:41Speaker 2: to parson x, so it would call another function, maybe parsex.
- 15:45Speaker 1: Which would handle parsing the integer constant in our.
- 15:47Speaker 2: Case, right parsiicus would return the constant ast node, then parsated,
- 15:51Speaker 2: but looks for the final token, consumes that, consumes that,
- 15:55Speaker 2: and if everything worked, it bundles up the constant node
- 15:58Speaker 2: returned by parsis inside a new return ast node and
- 16:01Speaker 2: returns that got it.
- 16:03Speaker 1: The guide showed some pseudocode with an expect helper function.
- 16:06Speaker 2: Yeah. Expect is useful. It basically means check if the
- 16:09Speaker 2: next token is x, consume it if yes, raise an
- 16:12Speaker 2: error if no.
- 16:13Speaker 1: And these functions consume tokens as they go, So if
- 16:16Speaker 1: parse program finishes and there are still tokens left over.
- 16:19Speaker 2: That usually means there's extra stuff that doesn't fit the grammar.
- 16:22Speaker 2: A syntax error makes sense.
- 16:23Speaker 1: The guide mentioned predictive parsers and backtracking briefly too.
- 16:26Speaker 2: Yeah. For more complex grammars where a rule might have
- 16:29Speaker 2: multiple options like if versus return for statement, the parser
- 16:33Speaker 2: might need to peek ahead at the next token to
- 16:36Speaker 2: decide which path to take predictive or try one path
- 16:40Speaker 2: and backtrack if it fails.
- 16:41Speaker 1: But for our simple start, direct recursive descent works well.
- 16:45Speaker 2: And testing the parser same tool.
- 16:47Speaker 1: YEP test compiler path where you're compiler chapter two stage pars.
- 16:50Speaker 1: It checks against the invalid pars and valid tests again.
- 16:54Speaker 1: Writing your own tests to check the structure of the
- 16:56Speaker 1: output AST is super helpful for debugging and the implementation
- 17:00Speaker 1: tips where write a pretty printer for the ASD definitely
- 17:03Speaker 1: helps visualize the tree and give good error messages.
- 17:05Speaker 2: Crucial expected but found return online five column ten is
- 17:10Speaker 2: way better than just syntax error.
- 17:12Speaker 1: Absolutely okay. So source DAN lexer, the DAN pokins, the
- 17:16Speaker 1: met parser, DAN cast. We have the tree. What's next?
- 17:20Speaker 2: Now we hit cogeneration. This pass takes that c language AST.
- 17:24Speaker 1: The one the parser is built.
- 17:25Speaker 2: Exactly and transforms it into our target by sixty four
- 17:30Speaker 2: assembly instructions, but again not as text yet. We represent
- 17:33Speaker 2: the assembly program as another internal data.
- 17:35Speaker 1: Structure first another AST, an assembly AST precisely.
- 17:39Speaker 2: The guide calls it that. To keep things clear, it
- 17:41Speaker 2: has its own ASDL definition two.
- 17:43Speaker 1: Okay, what does the assembly ASDL look like?
- 17:45Speaker 2: It's also quite simple for now. Program function definition function
- 17:49Speaker 2: identify our name, instruction instructions instructions op src, opern and
- 17:54Speaker 2: dst ret oper im in register.
- 17:58Speaker 1: Okay, interesting parallels. Program has a function definition. A function
- 18:02Speaker 1: has a name, but instead of a C statement body,
- 18:04Speaker 1: it has instruction a list of instructions.
- 18:07Speaker 2: The astrisk means a list or sequence.
- 18:09Speaker 1: And the instruction types are mauve or reht and their
- 18:13Speaker 1: operations can be immediate, a constant or a register.
- 18:16Speaker 2: That's it for now, and initially, the only register we
- 18:18Speaker 2: care about is percent ax for the return value. The
- 18:21Speaker 2: code generator walks the cast and for each node it
- 18:25Speaker 2: figures out the equivalent assembly instructions and builds up this
- 18:28Speaker 2: assembly AST.
- 18:30Speaker 1: The guide had a table mapping cast nodes to assembly
- 18:33Speaker 1: AST constructs like return in C becomes a mauv register
- 18:38Speaker 1: than are ret in assembling.
- 18:39Speaker 2: Right, and constant int in the cast becomes in in
- 18:43Speaker 2: the assembly AST.
- 18:44Speaker 1: So it's a translation step building a new tree that
- 18:46Speaker 1: represents the assembly code needed exactly.
- 18:48Speaker 2: And you can see how one C statement return maps
- 18:51Speaker 2: to two assembly instructions movel and ret. That becomes more
- 18:54Speaker 2: common as things get complex.
- 18:56Speaker 1: Okay, assembly AST constructed in memory. The final step of
- 18:59Speaker 1: the initial four passes code emission.
- 19:01Speaker 2: Take that assembly AST we just built and write it
- 19:03Speaker 2: out to the s text file.
- 19:04Speaker 1: Finally the text file.
- 19:06Speaker 2: Finally the text file. And since the assembly AST structure
- 19:09Speaker 2: closely matches actual assembly syntax, this cast is usually quite straightforward.
- 19:13Speaker 2: You just traverse the assembly AST and put the text
- 19:15Speaker 2: for each node.
- 19:16Speaker 1: Another table in the guide showed the formatting function name
- 19:20Speaker 1: instructions becomes dot global name, then name than the text
- 19:24Speaker 1: for each instruction each On.
- 19:26Speaker 2: The new line, Yeah, mov A sarvisctst becomes move, srcdst,
- 19:31Speaker 2: rep becomes REHT, register becomes percent x, mint becomes NT.
- 19:35Speaker 1: Just translating the assembly AST nodes into their standard text representation.
- 19:40Speaker 2: Pretty much a direct translation.
- 19:41Speaker 1: Yeah, and remembering that mac OS needs the underscore prefix
- 19:45Speaker 1: on the global name like Maine.
- 19:46Speaker 2: Right, that platform detail needs to be handled by the emitter.
- 19:49Speaker 1: Okay. And then to test the whole thing lexer parser
- 19:51Speaker 1: codegen code emitter, we run test compiler without the stage flags.
- 19:55Speaker 2: Exactly test compiler path toward your compiler. Chapter two. That
- 19:59Speaker 2: command will one run your compiler on the test c
- 20:02Speaker 2: files to generate S files. Two use the system's GCC.
- 20:07Speaker 2: We're Clang to assemble and link those STS files into executables. Three.
- 20:13Speaker 2: Run those executables. Four compare their exit codes to the
- 20:17Speaker 2: exit codes produced by compiling the original C files directly
- 20:20Speaker 2: with GCC.
- 20:21Speaker 1: So it verifies the end to end behavior. Does our
- 20:25Speaker 1: compiler produce assembly that results in a program doing the
- 20:27Speaker 1: same thing at least in terms of exit code as GCC.
- 20:30Speaker 2: That's the goal for this stage. It's the final check
- 20:33Speaker 2: that all four passes are working together correctly for these
- 20:36Speaker 2: simple programs.
- 20:37Speaker 1: Wow. Okay, so in this deep dive, we've really laid
- 20:39Speaker 1: out the blueprint for a compiler's first steps. Yeah, lexingcode
- 20:43Speaker 1: into tokens, parsing tokens into that crucial abstracts and text tree,
- 20:47Speaker 1: generating an intermediate assembly representation from that tree, and finally
- 20:51Speaker 1: emitting that assembly into a text file. It's fascinating to
- 20:54Speaker 1: see how these stages transform the code step by step.
- 20:57Speaker 2: Absolutely and like we said, while it seems like a
- 21:00Speaker 2: for just returning a number, this structured multi pass approach
- 21:03Speaker 2: is really the key. It's the foundation we need to
- 21:05Speaker 2: start handling more complex sea features like operators, variables, control
- 21:11Speaker 2: flow in our next deep dives.
- 21:13Speaker 1: It definitely gives you a much deeper appreciation for what's
- 21:15Speaker 1: happening when you just type gccmiprogram dot c okay. Thinking
- 21:20Speaker 1: about these basic steps, how do they scale, How does
- 21:23Speaker 1: this foundation handle the sheer complexity of say, the Linux
- 21:26Speaker 1: kernel source code, and what are the really tricky sea
- 21:29Speaker 1: features that will challenge this simple pipeline later on. Definitely
- 21:33Speaker 1: something to chew on.
- 21:33Speaker 2: Indeed, plenty more complexity ahead.
- 21:36Speaker 1: Thanks for joining us for this deep dive