From d649c570535f9702c13cbc7b872ddd66c564581c Mon Sep 17 00:00:00 2001 From: Syndamia Date: Thu, 13 Apr 2023 13:49:54 +0300 Subject: [blog/seoc] Restructured layout into multiple page one --- src/blog/sane-explanation-of-compilers/index.md | 854 ----------------------- src/blog/sane-explanation-of-compilers/part-1.md | 851 ++++++++++++++++++++++ 2 files changed, 851 insertions(+), 854 deletions(-) delete mode 100644 src/blog/sane-explanation-of-compilers/index.md create mode 100644 src/blog/sane-explanation-of-compilers/part-1.md (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/index.md b/src/blog/sane-explanation-of-compilers/index.md deleted file mode 100644 index 21a6b64..0000000 --- a/src/blog/sane-explanation-of-compilers/index.md +++ /dev/null @@ -1,854 +0,0 @@ -# Sane explanation of compilers - -## Contents - -1. [Preface](#preface) -2. [I. How do we understand code?](#i.-how-do-we-understand-code) - 1. [Math](#math) - 1. [Regular expressions](#regular-expressions) - 2. [Grammars](#grammars) - 2. [Lexers and parsers](#lexers-and-parsers) - 1. [Implementational difficulties with grammars](#implementational-difficulties-with-grammars) - 2. [Usage in the real world](#usage-in-the-real-world) - 3. [Parsing algorithms](#parsing-algorithms) - 1. [LL](#ll) - 2. [LR](#lr) - 3. [LR's family](#lrs-family) - 4. [Abstract syntax tree](#abstract-syntax-tree) - 3. [Implementing a front-end](#implementing-a-front-end) - 1. [lex](#lex) - 2. [yacc](#yacc) -4. [II. How can we improve the code?] -5. [III. Virtual machines] -6. [Compilation schemes] - 1. [AOT] - 2. [JIT] - - -Recently I signed up for a small university course about compilers. -The resources and lectors were good, but when studying I found most material online either deals with something on a very surface level or a very deep level. -Before I've forgotten everything, I'll try to hit that middle spot, generally covering the most important corners of the subject. - -*P.S.* The course resources are available on [sofiacpp.github.io/IPL](https://sofiacpp.github.io/IPL/) with the underlying repo being [SofiaCPP/IPL](https://github.com/SofiaCPP/IPL). - -## Preface - -Processors work with numbers, every action (instruction) a processor can do is defined by numbers. -However, writing code only with numbers is tedious, error-prone and simple stuff sometimes take ages to implement. -That is why, over time, programmers have tried to abstract sets of instructions into words and text constructions that are easier to work with. - -Thanks to abstraction, programmers have been able to create more and more complicated projects with less and less work, that is more portable and compatible with different machines. -The tradeoff is that we need to translate our nice programmer code to numbers a CPU would understand. -This job is delegated to a special type of program, called a compiler[^how-did-we-get-here], which is separated into three main layers/components: - -1. Front-end: it understands the program, what the code is trying to do -2. Middle: does optimizations and simplifications, though this part is often inside the back-end -3. Back-end: generates the actual machine instructions - -## I. How do we understand code? - -Syntax in current programming languages can be quite sophisticated and ambiguous. For example (taken from [wikipedia](https://en.wikipedia.org/wiki/Most_vexing_parse)) this C++ snippet - -``` -void f(double d) { - int i(int(d)); -} -``` - -could be interpreted either as a: - -1. declaration of variable `i`, which is initialized with the value of `int(d)` (which just casts `d` to an integer), or -2. function declaration, since superfluous parenthesis around function parameter declarations are allowed (meaning it is treated as `int i(int d)`) - -Note that I'm talking about syntax, the valid selection and layouts of characters, and not semantics, the underlying meaning. -Compiled programming languages associate specific templates of code (text) to their "corresponding" machine instructions, there isn't anything special you need to understand in a piece of code. -In natural languages, you could construct a sentence which follows all gramatical rules, but is absolute nonsence, like ["Colorless green ideas sleep furiously"](https://en.wikipedia.org/wiki/Colorless_green_ideas_sleep_furiously). - -The problem of semtantics is extremely difficult, however in our case we only care about syntax. -And this is where math comes into play. - -### Math - -A word of caution, I'll use a decent amount of fancy names, so I have a way to more easily refer to different concepts. -Don't be scared and skip over them if they're confusing you. - -There is a special field in mathematics that deals with syntactical analysis: [formal language theory](https://en.wikipedia.org/wiki/Formal_language). -Although even the basics merit a whole university course, I'll still try to roughly explain what's important, for those that haven't studied it. -This field works primarily with strings via the help of two (relevant for our purposes) instruments: regular expressions and grammars. - -#### Regular expressions - -You might've heard or even already used regexes in a text editor. -They're small text expressions which specify a text pattern. -When a word can be "generated" from the pattern, we say the regex matches the word. - -At their very base, such a pattern is created with the following rules: - -- [concatenation](https://en.wikipedia.org/wiki/Concatenation) - you can put characters next to each other to form strings, so a normal string like `accent` is also a regex. - With braces we can group stuff. - For example, in `a(cc)ent` the two "c"s are grouped together. - This is used to form more sophisticated structures later on, but currently it doesn't alter anything, like the braces in `(1+2)+3` and `1+(2+3)` don't alter the result sum. -- [alternation](https://en.wikipedia.org/wiki/Alternation_%28formal_language_theory%29) - allow different (alternative) strings in the same spot. - We do so with vertical bars (which signify an "or" relationship), the group can be "replaced" with either value. - For example `acce(n | p)t`, matches both "acce**n**t" or "acce**p**t". - There is no limit on how many alternatives you can have and what their lengths are: - - ```regex - acc(ordingly | ent | urate) - ``` - - matches - - + "acc**ordingly**" - + "acc**ent**" and - + "acc**urate**". - - There is no limit on how many groups (with alternation) you can have: - - ```regex - ac(quirem | c | hievem)en(t | ts) - ``` - - matches - - + "ac**quirem**en**t**" - + "ac**quirem**en**ts**" - + "ac**c**en**t** - + "ac**c**en**ts** - + "ac**hievem**en**t**" and - + "ac**hievem**en**ts**". - -- [Kleene star](https://en.wikipedia.org/wiki/Kleene_star) - repeat the preceding letter or group, 0 or more times. - An asterisk is used to mark this operation (hence the name, "Kleene **star**"). - - ```regex - accents* - ``` - will match - - + "accent" - + "accent**s** - + "accent**ss** - + "accent**sss** - + and so on - - Of course, the asterisk could also be in the middle of the regex, like - - ```regex - ac*ent - ``` - - which matches - - + "acent" - + "ac**c**ent" - + "ac**cc**ent" - + ... - - With a group we can repeat entire strings, - - ```regex - acc(ent)*s - ``` - - matches - - + "accs" - + "acc**ent**s" - + "acc**entent**s - + "acc**ententent**s" - + ... - - An alternation allows any alternative to be chosen at any point, so - - ```regex - acce(n | p)*t - ``` - - matches - - + "accet" - + "acce**n**t - + "acce**p**t - + "acce**nn**t - + "acce**np**t" - + "acce**pn**t" - + "acce**pp**t" - + "acce**nnn**t" - + ... - -In the modern day, regular expressions permit [additional constructions](https://en.wikipedia.org/wiki/Regular_expression#Syntax) like matching the start or end of a string, matching character groups or character classes. -There are also sometimes features which significantly increase the matching capabilities of normal regexes, like [lookahead and lookbehind assertions](https://en.wikipedia.org/wiki/Regular_expression#Patterns_for_non-regular_languages). - -#### Grammars - -However, even then regular expressions are fairly weak, they can't match recursive structures. -Let's say you want to be able to have math expressions in your language, you can have braces inside braces as much as you like, but in a certain manner: - -- `1+2` is a valid expression -- `(9-8)+2` also is valid -- `((3*3)-(2^3))+2` is too -- however `()3*3)-(2^3()+2` isn't valid - -Such a structure is recursive, because it can contain "itself", `1+2` can be a standalone math expression, but it can also be contained in another expression, like `(1+2)*3`, which itself could be inside another bigger expressions and so on. -For this task we have a whole separate tool: grammars. - -The syntax is different from regexes: a grammar is divided into (production) rules, each rule is named and specifies an expression. -Expressions are a concatenation of strings and/or names[^terminals-and-nonterminals]. -Names won't appear in our matched strings, the idea is that a name will be replaced with it's expression, kind of like a placeholders. -Additionally, there can be multiple rules with the same name, meaning a rule can be replaced by different stuff at any point of the string generation. - -Always one name is chosen to be the starting point, and generation continues from there. -In math literature, generally we write rules in the form `Name -> Expression`[^grammar-syntax], and often names are a single capital letter. -Additionally, often the starting name is called `S`. -Finally, in future examples, I'll use the thick arrow `🡆` to show derivations, how the generated string looks after one or two replacements of the name with one of it's expressions. - -For an example, with the grammar - -```grammar -S -> aSb -S -> cc -``` - -we can generate the string `aaaaccbbbb` (remember, our starting point is `S`): - -```grammar+ -S 🡆 aSb 🡆 aaSbb 🡆 aaaSbbb 🡆 aaaaSbbbb 🡆 aaaaccbbbb -``` - -or `accb`: - -```grammar+ -S 🡆 aSb 🡆 accb -``` - -where a, b and c are just english characters. -To simplify our lives, often rules with the same name are merged into one rule, separated by vertical bars (`S -> aSb | cc`). -This is practically alternation but in a different context. - -As for our math expressions, we could create something like this: - -```grammar -N -> 0 | 1 | 2 | ... all possible numbers -E -> N | (E) | E + E | E - E | E * E | E / E | E ^ E -``` - -which will sucessfully be able to match (generate) `((3 * 3) - (2 ^ 3)) + 2`: - -```grammar+ -E 🡆 E + E 🡆 (E) + N 🡆 (E - E) + 2 🡆 ((E) - (E)) + 2 🡆 ((E * E) - (E ^ E)) + 2 🡆 ((N * N) - (N ^ N)) + 2 🡆 ((3 * 3) - (2 ^ 3)) + 2 -``` - -but there are no expressions (rules) that allow `()3+3()` or `)3(-6` to be "matched". - -### Lexers and parsers - -You might've noticed that for `N` I use three dots and the note "all possible numbers" to signify that N can be any positive whole number. -In practice we need formally define that grammar: - -```grammar -N -> 0 | 1 | 2 | ... | 9 | 0N | 1N | 2N | ... | 9N -``` - -With this you might've realised that grammars can do anything a regular expressions can: concatenation and alternation are "built-in", and the Kleene star can be done with another rule in the form `R -> strR | str`[^regular-grammars]. -The reason we use both is that grammars are significantly slower and more complicated in code than regexes. - -#### Implementational difficulties with grammars - -Implementing (very roughly) the regular expression `acce(n | p)*t` is quite easy: - -```cpp -bool matchesp(string str) { - string regex = "acce_t"; - - for (int si = 0, ri = 0; si < str.size() && ri < regex.size(); si++, ri++) { - while (regex[ri] == '_') - if (str[si] == 'n' || str[si] == 'p') - si++; - else - ri++; - } - - if (str[si] != regex[ri]) - return false; - } - return true; -} -``` - -In brief, for concatenated characters we do a simple comparison per character. -When we reach "\_", which I use to specify we're in the `(n | p)*` part of the regex, we do comparisons with the characters n and p as much as we can, after which we continue as normal. - -Of course, this version only supports one regular expressions, however a "proper" implementation would look conceptually similar: a couple of different loops and equality checks, with maybe an additional array or two. -The huge benefit is that that loops and arrays are stupid fast, a (simple) C++ for loop could be translated into [a handful of processor instructions](https://godbolt.org/#g:!%28%28g:!%28%28g:!%28%28h:codeEditor,i:%28filename:'1',fontScale:14,fontUsePx:'0',j:1,lang:c%2B%2B,selection:%28endColumn:16,endLineNumber:6,positionColumn:16,positionLineNumber:6,selectionStartColumn:16,selectionStartLineNumber:6,startColumn:16,startLineNumber:6%29,source:'//+Type+your+code+here,+or+load+an+example.%0Aint+f%28int+num%29+%7B%0A++++for+%28int+i+%3D+1%3B+i+%3C+100%3B+i%2B%2B%29+%7B%0A++++++++num+*%3D+100%3B%0A++++%7D%0A++++return+num%3B%0A%7D'%29,l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0'%29%29,k:50,l:'4',n:'0',o:'',s:0,t:'0'%29,%28g:!%28%28h:compiler,i:%28compiler:g122,deviceViewOpen:'1',filters:%28b:'0',binary:'1',binaryObject:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'0',trim:'1'%29,flagsViewOpen:'1',fontScale:14,fontUsePx:'0',j:1,lang:c%2B%2B,libs:!%28%29,options:'',selection:%28endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1%29,source:1%29,l:'5',n:'0',o:'+x86-64+gcc+12.2+%28Editor+%231%29',t:'0'%29%29,k:50,l:'4',n:'0',o:'',s:0,t:'0'%29%29,l:'2',n:'0',o:'',t:'0'%29%29,version:4). - -On the other hand, usually grammars are more complicated and resource-intensive. -Certain ones are simple enough to implement, like `S -> aSb | cc`: - -```cpp -bool matchesp(string str) { - if (str == "cc") - return true; - else if (str[0] == 'a' && str[str.size() - 1] == 'b') - return matchesp(str.substr(1, str.size() - 2)); - else - return false; -} -``` - -However think about more complicated cases[^context-free-grammars], like `S -> aSbSa | cc`. -Implementing this one is quite a bit more difficult, since we don't know where `b` is located on the first iteration, it could either be the 4th character `accb...a` or the 9th `aaccbccab...a`. -Searching for it is also complicated, it could be the first, the last or any other `b` in the middle of the string. - -Another difficulty with grammars is ambiguity, let's look at - -```grammar -E -> E + E | E * E | n -``` - -how would it generate `n + n * n`? -There are two completely valid ways to do so: - -```grammar+ -E 🡆 E + E 🡆 n + E * E 🡆 n + n * n -``` - -```grammar+ -E 🡆 E * E 🡆 E + E * n 🡆 n + n * n -``` - -How exactly we deal with these problems comes later, for now the takeaway is that we have to try and use regular expressions wherever we can, and leave grammars as a bit of a last resort. - -#### Usage in the real world - -Let's think a bit more about grammars: they're really good at handling structure, especially recursive structure, so it's best if we use them only for that. -Our math expression grammar (from [here](#grammars)) shouldn't really care if we're trying to sum integers or floats or chars[^static-typing], it's important how everything is layed out and that our operations are done with numbers. - -This is why we're going to separate and generalize the code into [tokens](https://en.wikipedia.org/wiki/Lexical_analysis#Token), basically into building blocks. -As a rough example, we want `1 + (2 * 3)` to be transformed into `NUMBER + (NUMBER * NUMBER)`, `int var = 13;` into `TYPE NAME = NUMBER;` and so on, where "TYPE", "NUMBER" and "NAME" are tokens. -Now we're reducing the amount of "objects" our grammars need to work on: from all characters to many (but significantly fewer) tokens and some really small amount of characters. -Of course, each token will contain it's name (NUMBER, TYPE, ...) and it's value, since we aren't trying to change the code, but our grammars will work with the token names directly and just output the values at the very end. -Usually we identify at least six token types: - -- identifiers: variable and function names for example -- keywords: `if`, `while`, `for`, `return`, ... -- separators: braces, `;` -- operators: `+`, `-`, `<=` -- literals: numbers, strings, characters -- comments - -As you might've noticed, here we can use regular expressions, grouping consequtive characters is what regexes are good for. -Additionally, we're going to be reading the file, a decently slow operation, only once and for a comparatively very little time. - -In the compiler front-end, the part that implementes our regular expressions is called the "lexer", and the part that implements our grammars - the "parser". -In the last section we already talked about how easy implementing regexes (lexers) is and how difficult implementing grammars (parsers) is, let's look at the latter. - -#### Parsing algorithms - -Proper algorithms that "implement" grammars are kind of complicated, and most can handle only specific types of grammars. -Generally we categorize them into: - -- [top-down](https://en.wikipedia.org/wiki/Top-down_parsing) algorithms, which work in the way we've been talking about grammars: start with a name and replace it with it's expression, and continue replacements until we have no more names -- [bottom-up](https://en.wikipedia.org/wiki/Bottom-up_parsing) algorithms, where we do the opposite: for each substring we find from which rule it could've come from, replace it with the corresponding name, and continue upwards like that, until we reach the starting name - -Furthermore, if our algorithms allow for ambiguity (meaning we can replace a name with any one of multiple expressions), we divide them into: - -- left-most derivation algirithms, where we choose the left-most valid expression -- right-most derivation algorithms, where we chose the right-most valid expression - -The advantage and disadvantages of every type kind of depend on the exact algorithm and grammar. -Looking at some of the more famous ones: - -##### LL - -[LL](https://en.wikipedia.org/wiki/LL_parser): top-down left-most derivations algorithm that can parse only specific types of grammars. -In these grammars, every expression is uniquely identifiable by just looking at the characters (tokens) in the very beginning. -The amount of token we need to look for is very important, so we usually define LL(k) as an LL grammar that needs to look at k amount of tokens. -An "LL(k) grammar" is, by extension, a grammar which can be parsed with an LL(k) parser. - -So, the way we'll check if an expression matches our grammar, is by starting with the start name and reading the next k character from the input. -We check the first k character of all expressions, and if anyone of them is a name, we try with substitution for every possibility with that name, essentially peeking into the name's possibilities. - -- As an example, the grammar: - - ```grammar - F -> a - S -> F | (S + F) - ``` - - is LL(1). - Let's read the input `(a + a)` (the "v" points to the symbol we're looking/peeking at): - - ``` - I v - Input: (a + a) - - I v - Production: S - ``` - - we start with `S`, we peek and get the `(`, in our production we're looking at a name, S. - Let's check the first character of every expression of S. - In the first expression, the first "character" is `F`, a name, so we look at every expression for `F`. - There is only one, which is "a", different than "(", no dice. - Now we check the second expression for S, it's first character is "(", success! - We replace: - - ``` - I v - Input: (a + a) - - I v - Production: (S + F) - ``` - - Now the first symbol in our production is also `(`, so we incremenet the symbols we're looking/peeking at - - ``` - I v - Input: (a + a) - - I v - Production: (S + F) - ``` - - we peek and get the `a`, in our production the second "character" is the name `S`, `S` has to become `a`. - We do that same check from before, first expression for `S` is `F`, whose first (and only) expression is `a`, success! - - ``` - I v - Input: (a + a) - - I v - Production: (a + F) - ``` - - The middle characters " + " are matched and at the second `F` we check it's expressions, it has only `a`, success, replace, end of input, we're done. - - Another LL(1) example can be found in [Karl R. Abrahamson notes](http://www.cs.ecu.edu/karl/5220/spr16/Notes/Top-down/LL1.html). - -- The grammar - - ```grammar - B -> b - C -> c - S -> aaB | aaC - ``` - - is LL(3). - For the input `aab`, if we look at the first two "a"s, we still don't know which rule to use: `aaB` or `aaC`. - However if we look at the third symbol, "b", then we can determine that we need `aaB`. - -- Usually parsers that implement this procedure are called [recursive descent parsers](https://en.wikipedia.org/wiki/Recursive_descent_parser) - -##### LR - -[LR](https://en.wikipedia.org/wiki/LR_parser): bottom-up right-most derivations algorithm. -Conceptually, LR works in the exact opposite way to LL: for every character in the input, we find a rule that substitutes it (or that substitutes the current collection of names and character) and do so until we've reached the starting name. - -Figuring out an approach isn't as intuitive and easy as with LL, but it still isn't too hard. -It all boils down to using a whole bunch of conditional statements and tracing where we "came" from. - -- Let's look at the first LL example: - - ```grammar - F -> a - S -> F | (S + F) - ``` - - We need to track "how the current string looks", because if we read an "a", it could either be from the left handside of the "a + a" or from the right handside. - We're going to track where we came from with numbers, which I will define like this: - - |Number|Current expression ends with| - |------|---------------| - |0 |Nothing; this is the start| - |1 |The name `S`; the final number should be this| - |2 |The name `F`| - |3 |The character "("| - |4 |The character "a"| - |5 |"(S"| - |6 |"(S + "| - |7 |"(S + F"| - |8 |"(S + F)"; this is the one before the final| - - You can think of every number as the valid, but "unfinished" state of the current string. - For now don't think about how I've defined those numbers, it'll make sense later. - But you could make a table for literally every valid state: "(", "(a", "(F", "(S", ..., there is no problem. - - Keep in mind that the way I'll show the algorithm step by step isn't really correct, but will suffice for the current moment. - We'll be working with a string, where reading a character from the input means putting the latest one in the String: - - ``` - String : ( - Number : 0 - ``` - - We're reading "(", so our string "ends" on a "(" - - ``` - String : (a - Number : 3 - ``` - - We've read "a", our string "ends" on an "a". - - ``` - String : (a - Number : 4 - ``` - - Here comes the clever bit, for certain numbers, we'll stop reading forward and do something else. - If we're on the number 4, our string ends on an "a", so we're going to go backward and replace it with an F, meaning now the number is 2. - - ``` - String : (F - Number : 2 - ``` - - Here is another such rule, if our number is 2, our string ends with an "F" and we replace it with an S, now the number is 5. - That's why we have a different number for "(S + F", if we didn't, our number would become 2 and we would make "(S + S", which isn't valid. - So, think of 2 as "this is the first F". - - ``` - String : (S - Number : 5 - ``` - - We have a different number for "(S", because if we didn't, we would've gone to number 1, and could've ended the algorithm then and there, without reading the rest of the input. - Otherwise, we continue as normal, we read the `+` and the spaces around it, going to number 6. - - ``` - String : (S + a - Number : 6 - ``` - - Now, our string ends with an "a", it's tempting to change our number to 4, but we shouldn't, this would remove our progress so far! - Better yet, this number will also be special, if we have a 6 and we end with "a", rather than going to 4, we'll substitute "a" with F now and change number to 7. - - ``` - String : (S + F - Number : 7 - ``` - - And now it's trivial, we read ")", so we go to number 8. - But if we're at number 8, don't continue reading, replace with number 1. - Now that we're at number 1, if we read any character (including end of string), we'll say the string upto now matches and we're done! - - It's also helpful to put what we do in different situations in another table: - - |Number|If ends on|Change number to|Also do| - |------|----------|----------------|-------| - |0 |"(" |3 | | - |1 | | |Nothing, we matched| - |2 | |5 |Replace "F" with "S"| - |3 |"a" |4 || - |4 | |2 |Replace "a" with "F"| - |5 |" + " |6 | | - |6 |"a" |7 |Replace "a" with "F"| - |7 |")" |8 | | - |8 | |1 |Replace "(S + F)" with "S"| - - where, if there is a value in "If ends on", we read the next character, while otherwise we don't and we just execute "Change number to" and "Also do". - -- You're probably wondering why the table works so weird, like why on number 3 we don't directly replace "a" with "S" and change to number 5 for example. - The reason is that the way I showed the algorithm isn't exactly how it normally works. - Rather than tracing the current number in a variable, we trace it with a [stack](https://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29). - - When you read a character and have to go to another number, the number is added to the stack (this operation is called "shift"). - When we have to change characters from String (without reading anything), with a string (expression) of length j, we remove the last j added numbers and do a normal shift from the last number and character in String (this operation is called "reduce"). - -- Let's look at the same example, done with shift and reduce operations (without me showing the table): - - ``` - String : ( - Number : [0] - ``` - - We've read "(", add 3 on top of the stack aka shift(3). - Then we read the "a", shift(4). - - ``` - String : (a - Number : [0, 3, 4] - ``` - - With 4 we'll do a reduction, "a" gets replaced by F, 4 is removed: - - ``` - String : (F - Number : [0, 3] - ``` - - If last number is 3 and last character is "F", we're doing shift(2). - - ``` - String : (F - Number : [0, 3, 2] - ``` - - Now, we'll be doing a reduction, where F is replaced by S: - - ``` - String : (S - Number : [0, 3] - ``` - - If last number is 3 and last character is "S", we're dong shift(5). - - And so on, we continue. - As you can see, we go back and forth, from 3 to 4, back to 3, then to 2, back to 3, then to 5. - This way we avoid doing different things on different numbers. - Additionally, in the real world nobody makes this table by hand, it is generated by a program, and this method makes table generation easier. - -- As for the complete table, you can view it on the [Context Free Grammar Checker](https://smlweb.cpsc.ucalgary.ca/lr0.php?grammar=S+-%3E+F+%7C+%28+S+%2B+F+%29.%0AF+-%3E+a.&substs=) by [](TODO), - or with a more pretty styling on [Grammophone](https://mdaines.github.io/grammophone/#/), where you input on the left: - - ``` - S -> F | "(" S "+" F ")". - F -> a. - ``` - - press "Analyze", then click the link "Parsing table" at the bottom, on the row "LR(0)". - - To read the table, remember that: - - - our numbers are formally called states - - on every row you have each state - - on every column you have each possible value in the string and "$" which signifies the end of the string - - with sr or shift (or just with a number) you go to another state - - with r or reduce you make the substitution in the current string and go back one state - - acc or accept means you've reached the end - -##### LR's family - -LR is more of a family of algorithms, because there are multiple different ways to generate the table, each with it's own benefits and drawbacks. -This subject is a really big can of beans, which I'm not knowlegeable enough to talk about. -What you need to know is that there are 3 often used types: [CLR](https://en.wikipedia.org/wiki/Canonical_LR_parser), [SLR](https://en.wikipedia.org/wiki/Simple_LR_parser) and [LALR](https://en.wikipedia.org/wiki/LALR_parser). - -- CLR is an LR parser with 1 character lookahead (LR(1)), following [Knuth](TODO)'s original theory. - It requires a lot of memory for table generation, so Frank DeRemer created two simplifications: -- the SLR and LALR, which use singificantly less memory but work with a bit less grammars - -LALR is the most commonly used LR parser, however most compilers are custom-tailored pieces of software that very loosely follow the methods of LL and LR. - -##### More info - -If you want to learn more, I would highly suggest: - -- [LL and LR Parsing Demystified](https://blog.reverberate.org/2013/07/ll-and-lr-parsing-demystified.html) and [LL and LR in Context: Why Parsing Tools Are Hard](https://blog.reverberate.org/2013/09/ll-and-lr-in-context-why-parsing-tools.html) by [Josh Haberman](https://blog.reverberate.org/about/) -- [Parsing: Top-down versus bottom-up](http://jeffreykegler.github.io/Ocean-of-Awareness-blog/individual/2014/11/ll.html) by [Jeffrey Kegler](https://jeffreykegler.github.io/personal/) -- [Which Parsing Approach?](https://tratt.net/laurie/blog/2020/which_parsing_approach.html) by [Laurence Tratt](https://tratt.net/laurie/) -- [A Guide to Parsing: Algorithms and Terminology](https://tomassetti.me/guide-parsing-algorithms-terminology/) by [Gabriele Tomassetti](https://inre.me/) -- [Parsing](http://www.cs.ecu.edu/karl/5220/spr16/Notes/Parsing/index.html), [Top-Down Parsers](http://www.cs.ecu.edu/karl/5220/spr16/Notes/Top-down/index.html) and [Bottom-Up Parsers](http://www.cs.ecu.edu/karl/5220/spr16/Notes/Bottom-up/index.html) from [Karl R. Abrahamson](http://www.cs.ecu.edu/karl/5220/spr16/Notes/Bottom-up/index.html)'s notes -- [How to Impement an LR(1) Parser](https://serokell.io/blog/how-to-implement-lr1-parser) by Kirill Andreev - -#### Abstract syntax tree - -We already decided that the lexer will output tokens (and characters) to the parser, but we didn't talk about what the parser is supposed to output. -It definetly has to be some sort of structural representation of the overall code, for example, for `3 + 1 * 2` we have to be able to easily find out what the left and right handsides of the `+` and `*` are. - -Let's draw out[^nomnoml] this relationship, where the left arrow connects to the left handside and the right accordingly: - -![](./img/tree-simple.svg) - -Hey, that looks an awful lot like a [tree](https://en.wikipedia.org/wiki/Tree_%28data_structure%29)! -Trees are nodes, some sort of elements, where there is a connection from one element to some other elements, with the only rule being that cycles aren't allowed: - -![](./img/tree-cycle.svg) - -Great, but can we represent everything else with a tree? -Why, of course, for example we can represent: - -```cpp -if (a > b) - c = 5; -else - d += 10; -``` - -as - -![](./img/tree-if.svg) - -And trust me, we can represent the whole code structure with a tree. -Now, compilers are made in low-level languages like C++, so we need to think about the data type of each node (element) in our tree. -We'll definetly need [object polymorphism](https://en.wikipedia.org/wiki/Subtyping#Examples) to be able to represent different nodes. - -At a later stage we'll need to be running/evaluating the whole code with this tree, so how are we going to work with it? -When we navigate to the node `<`, we'll do "if left element is less than right, do body when true, otherwise do body when false" but are we going to implement every single operator and language feature by hand? -Or alteratively we could have a virtual method "evaluate" which changes - - - -### Implementing a front-end - -If you want, you could implement your own lexer and parser manually, but as a start, it's better to try and use already created stuff. -[Compiler-compilers](https://en.wikipedia.org/wiki/Compiler-compiler) are tools that create parsers (and more) from their normal formal definition. - -The two popular ones from the old days are lex and yacc. -lex is a lexer generator and yacc is a LALR parser generator, both of which generate a corresponding C implementation of the given regular expressions and grammars. - -#### lex - -Lex is the original program, from 1975, in the modern day it's successor/implementation is the opensource [flex](https://github.com/westes/flex). - -A lex source file is divided into three parts: - -```lex -%{ -// C code that will be put in the program verbatim -%} - -/* Definitions */ - -%% - - /* Rules */ - -%% - -// C code -``` - -where `%{%}` is used for includes and declarations, the rules are your regular expressions and the C code is the general logic of the lexer. -Usually you wouldn't write anything in the C code section, the defaults are fine, but you'll probably need to do one or two includes in the `%{%}` section. - -Rules are in the form `regex { C_code }`. -To simplify your life, you can write only the regex or a part of it inside the "definitions" part of the file, and give it a name to use later. -Referencing those names in later regexes is done by surrounding them in curly braces. -Usually the `C_code` in the regex would be a return (more commonly called "emit") of a token, which will be available in a header file, but more on that later. - -Let's look at a very simple example program: every whole number is printed as "NUMBER", while everything else is printed as-is: - -```lex -%{ -%} - -%% - -[0-9]+ { printf("NUMBER"); } -[A-z]+ { printf("%s", yytext); } - -%% -``` - -The syntax `[0-9]` is the same as `(0 | 1 | ... | 9)`, it works for any letters and is available in all modern regexes. -Note that inside every regex's "body" you have an assortment of variables already set, one of them being `yytext` which is just the whole match. -Additionally lex matches the longest possible match, so if we had a rule `[0-z]`, only it will be matched. - -If this file is located in `lexer.l`, we can compile it into a working lexer like this: - -```bash -flex lexer.l && gcc lex.yy.c -lfl -``` - -Of course, you can use your lex implementation or C compiler of choice. -Now, if you run `./a.out` you would get a prompt, every line you write will be lexically analyzed and in our case, everything will be printed out. -Entering - -``` -The number 10 changed to 8, 38, and 19 sequentially, before becoming 0. -``` - -will output - -``` -The number NUMBER changed to NUMBER, NUMBER, and NUMBER sequentially, before becoming NUMBER. -``` - -Now let's try something more sophisticated, let's surround numbers and strings in HTML tags, the stuff that power webpages. -We would want numbers to be in the format: - -``` -number -``` - -and strings: - -``` -string -``` - -We'll define numbers as both whole digits and floating point numbers (with sign) and strings can be surrounded in either single or double quotes. - -```lex -%{ -%} - -/* Only multiline comments are supported, not comments that start with // */ -/* This is a definition, it's in the format "NAME regex" */ -DIGIT [0-9] - -%% - /* Comments in here have to be indented, otherwise you'll get an error */ - /* ? means 0 or 1 of the preceding group*/ - /* + means 1 or more of the preceding group*/ - /* the backward slashes are used because . and + have special meaning in regexes*/ -[\+-]?{DIGIT}+(\.{DIGIT}+)? { printf("%s", yytext); } - - /* [^] is a group of characters, like [], however it specifies "all characters except the ones given"*/ - /* this way if we have "This is a string with " three quotes" it's not going to match the whole thing*/ -\"[^"]*\"|'[^']*' { printf("%s", yytext); } - -%% -``` - -With the input - -``` -John said 10 times "2 + 2 = 5" but '2 + 2 = 4'! -``` - -we'll get - -``` -John said 10 times "2 + 2 = 5" but '2 + 2 = 4'! -``` - -You've probably already noticed that the number inside the strings aren't matched, because the string rule results in a longer match. -In programming languages this is fine, since strings are quite often "self-contained" objects, there isn't anything in them that you would need to match. - -#### yacc - -Similarly to lex, yacc originates from 1975, and it's modern replacement is [GNU Bison](https://www.gnu.org/software/bison/). - -A yacc file looks very similar to a lex one: - -```yacc -%{ -// C code that will be put in the program verbatim -%} - -/* Settings */ - -%% - - /* Rules */ - -%% - -// C code -``` - -however rather than definitions you have settings, and the rules are in a completely different format (because they're grammars). - - -## II. How can we improve the code? - - - -## III. Virtual machines - -[^how-did-we-get-here]: Though it's obvious, I would like to point out that modern compilers are most often written in languages that are themselves compiled. You might ask yourself "where did the first compiler come from?" The answer is simple: it was written with "numbers", with direct instructions to the processor, from the time when computers were simple enough that *all* programming was done with CPU instructions. - -[^terminals-and-nonterminals]: Formally, we call the rule "names" nonterminals, the idea being that all normal characters, that could appear in our string, are called terminals, since they would terminate replacement and string generation. For the purposes of this post, I won't use the formal names, with the hope that using less terminology will increase understandability. - -[^grammar-syntax]: This is pretty much the mathematical notation, often in CS the Backus-Naur form is used, but I find that a bit harder to read. You might also make the argument that I should use a proper unicode arrow symbol, like `→`, but `->` is way more convinient. - -[^regular-grammars]: Such grammars are called [regular grammars](https://en.wikipedia.org/wiki/Regular_grammar), more formally, every rule has to contain at most one name and that name must be at the start or end of the string characters. - -[^context-free-grammars]: Be careful about cases that are too complicated, the grammar I'm showing is "context-free", but that topic is way beyond the scope of this post. - -[^static-typing]: Yeah yeah, in a statically typed language you might not be able to do operations on doubles and integers at the same time, but you get the point. - -[^nomnoml]: The graphics are made with [nomnoml](https://nomnoml.com/) by [Daniel Kallin](https://github.com/skanaar) diff --git a/src/blog/sane-explanation-of-compilers/part-1.md b/src/blog/sane-explanation-of-compilers/part-1.md new file mode 100644 index 0000000..250d9d2 --- /dev/null +++ b/src/blog/sane-explanation-of-compilers/part-1.md @@ -0,0 +1,851 @@ +# Sane explanation of compilers: Part 1 + +## Contents + +1. [Preface](#preface) +2. [I. How do we understand code?](#i.-how-do-we-understand-code) + 1. [Math](#math) + 1. [Regular expressions](#regular-expressions) + 2. [Grammars](#grammars) + 2. [Lexers and parsers](#lexers-and-parsers) + 1. [Implementational difficulties with grammars](#implementational-difficulties-with-grammars) + 2. [Usage in the real world](#usage-in-the-real-world) + 3. [Parsing algorithms](#parsing-algorithms) + 1. [LL](#ll) + 2. [LR](#lr) + 3. [LR's family](#lrs-family) + 4. [Abstract syntax tree](#abstract-syntax-tree) + 3. [Implementing a front-end](#implementing-a-front-end) + 1. [lex](#lex) + 2. [yacc](#yacc) + +Recently I signed up for a small university course about compilers. +As I found out, most materials on the topic are either so surface level you barely learn anything, or so specific you need to already know the subject. +My goal is to try and fill that void, explaning everything in a detailed way that is understandable for beginners. + +Originally I planned to put everything in one blogpost, but only this main component took me 2 weeks (slightly inconsistently) to write. +Additionally, while doing research, I found out we actually skiped over a lot of important topics. +Future parts will be linked right below the title at the very top, but it will probably be quite a while until I write them. + +## Preface + +Processors work with numbers, every action (instruction) a processor can do is defined by numbers. +However, writing code only with numbers is tedious, error-prone and simple stuff sometimes take ages to implement. +That is why, over time, programmers have tried to abstract sets of instructions into words and text constructions that are easier to work with. + +Thanks to abstraction, programmers have been able to create more and more complicated projects with less and less work, that is more portable and compatible with different machines. +The tradeoff is that we need to translate our nice programmer code to numbers a CPU would understand. +This job is delegated to a special type of program, called a compiler[^how-did-we-get-here], which is separated into three main layers/components: + +1. Front-end: it understands the program, what the code is trying to do +2. Middle: does optimizations and simplifications, though this part is often inside the back-end +3. Back-end: generates the actual machine instructions + +In this post, we'll be looking only at the first one. + +## I. How do we understand code? + +Syntax in current programming languages can be quite sophisticated and ambiguous. For example (taken from [wikipedia](https://en.wikipedia.org/wiki/Most_vexing_parse)) this C++ snippet + +``` +void f(double d) { + int i(int(d)); +} +``` + +could be interpreted either as a: + +1. declaration of variable `i`, which is initialized with the value of `int(d)` (which just casts `d` to an integer), or +2. function declaration, since superfluous parenthesis around function parameter declarations are allowed (meaning it is treated as `int i(int d)`) + +Note that I'm talking about syntax, the valid selection and layouts of characters, and not semantics, the underlying meaning. +Compiled programming languages associate specific templates of code (text) to their "corresponding" machine instructions, there isn't anything special you need to understand in a piece of code. +In natural languages, you could construct a sentence which follows all gramatical rules, but is absolute nonsence, like ["Colorless green ideas sleep furiously"](https://en.wikipedia.org/wiki/Colorless_green_ideas_sleep_furiously). + +The problem of semtantics is extremely difficult, however in our case we only care about syntax. +And this is where math comes into play. + +### Math + +A word of caution, I'll use a decent amount of fancy names, so I have a way to more easily refer to different concepts. +Don't be scared and skip over them if they're confusing you. + +There is a special field in mathematics that deals with syntactical analysis: [formal language theory](https://en.wikipedia.org/wiki/Formal_language). +Although even the basics merit a whole university course, I'll still try to roughly explain what's important, for those that haven't studied it. +This field works primarily with strings via the help of two (relevant for our purposes) instruments: regular expressions and grammars. + +#### Regular expressions + +You might've heard or even already used regexes in a text editor. +They're small text expressions which specify a text pattern. +When a word can be "generated" from the pattern, we say the regex matches the word. + +At their very base, such a pattern is created with the following rules: + +- [concatenation](https://en.wikipedia.org/wiki/Concatenation) - you can put characters next to each other to form strings, so a normal string like `accent` is also a regex. + With braces we can group stuff. + For example, in `a(cc)ent` the two "c"s are grouped together. + This is used to form more sophisticated structures later on, but currently it doesn't alter anything, like the braces in `(1+2)+3` and `1+(2+3)` don't alter the result sum. +- [alternation](https://en.wikipedia.org/wiki/Alternation_%28formal_language_theory%29) - allow different (alternative) strings in the same spot. + We do so with vertical bars (which signify an "or" relationship), the group can be "replaced" with either value. + For example `acce(n | p)t`, matches both "acce**n**t" or "acce**p**t". + There is no limit on how many alternatives you can have and what their lengths are: + + ```regex + acc(ordingly | ent | urate) + ``` + + matches + + + "acc**ordingly**" + + "acc**ent**" and + + "acc**urate**". + + There is no limit on how many groups (with alternation) you can have: + + ```regex + ac(quirem | c | hievem)en(t | ts) + ``` + + matches + + + "ac**quirem**en**t**" + + "ac**quirem**en**ts**" + + "ac**c**en**t** + + "ac**c**en**ts** + + "ac**hievem**en**t**" and + + "ac**hievem**en**ts**". + +- [Kleene star](https://en.wikipedia.org/wiki/Kleene_star) - repeat the preceding letter or group, 0 or more times. + An asterisk is used to mark this operation (hence the name, "Kleene **star**"). + + ```regex + accents* + ``` + will match + + + "accent" + + "accent**s** + + "accent**ss** + + "accent**sss** + + and so on + + Of course, the asterisk could also be in the middle of the regex, like + + ```regex + ac*ent + ``` + + which matches + + + "acent" + + "ac**c**ent" + + "ac**cc**ent" + + ... + + With a group we can repeat entire strings, + + ```regex + acc(ent)*s + ``` + + matches + + + "accs" + + "acc**ent**s" + + "acc**entent**s + + "acc**ententent**s" + + ... + + An alternation allows any alternative to be chosen at any point, so + + ```regex + acce(n | p)*t + ``` + + matches + + + "accet" + + "acce**n**t + + "acce**p**t + + "acce**nn**t + + "acce**np**t" + + "acce**pn**t" + + "acce**pp**t" + + "acce**nnn**t" + + ... + +In the modern day, regular expressions permit [additional constructions](https://en.wikipedia.org/wiki/Regular_expression#Syntax) like matching the start or end of a string, matching character groups or character classes. +There are also sometimes features which significantly increase the matching capabilities of normal regexes, like [lookahead and lookbehind assertions](https://en.wikipedia.org/wiki/Regular_expression#Patterns_for_non-regular_languages). + +#### Grammars + +However, even then regular expressions are fairly weak, they can't match recursive structures. +Let's say you want to be able to have math expressions in your language, you can have braces inside braces as much as you like, but in a certain manner: + +- `1+2` is a valid expression +- `(9-8)+2` also is valid +- `((3*3)-(2^3))+2` is too +- however `()3*3)-(2^3()+2` isn't valid + +Such a structure is recursive, because it can contain "itself", `1+2` can be a standalone math expression, but it can also be contained in another expression, like `(1+2)*3`, which itself could be inside another bigger expressions and so on. +For this task we have a whole separate tool: grammars. + +The syntax is different from regexes: a grammar is divided into (production) rules, each rule is named and specifies an expression. +Expressions are a concatenation of strings and/or names[^terminals-and-nonterminals]. +Names won't appear in our matched strings, the idea is that a name will be replaced with it's expression, kind of like a placeholders. +Additionally, there can be multiple rules with the same name, meaning a rule can be replaced by different stuff at any point of the string generation. + +Always one name is chosen to be the starting point, and generation continues from there. +In math literature, generally we write rules in the form `Name -> Expression`[^grammar-syntax], and often names are a single capital letter. +Additionally, often the starting name is called `S`. +Finally, in future examples, I'll use the thick arrow `🡆` to show derivations, how the generated string looks after one or two replacements of the name with one of it's expressions. + +For an example, with the grammar + +```grammar +S -> aSb +S -> cc +``` + +we can generate the string `aaaaccbbbb` (remember, our starting point is `S`): + +```grammar+ +S 🡆 aSb 🡆 aaSbb 🡆 aaaSbbb 🡆 aaaaSbbbb 🡆 aaaaccbbbb +``` + +or `accb`: + +```grammar+ +S 🡆 aSb 🡆 accb +``` + +where a, b and c are just english characters. +To simplify our lives, often rules with the same name are merged into one rule, separated by vertical bars (`S -> aSb | cc`). +This is practically alternation but in a different context. + +As for our math expressions, we could create something like this: + +```grammar +N -> 0 | 1 | 2 | ... all possible numbers +E -> N | (E) | E + E | E - E | E * E | E / E | E ^ E +``` + +which will sucessfully be able to match (generate) `((3 * 3) - (2 ^ 3)) + 2`: + +```grammar+ +E 🡆 E + E 🡆 (E) + N 🡆 (E - E) + 2 🡆 ((E) - (E)) + 2 🡆 ((E * E) - (E ^ E)) + 2 🡆 ((N * N) - (N ^ N)) + 2 🡆 ((3 * 3) - (2 ^ 3)) + 2 +``` + +but there are no expressions (rules) that allow `()3+3()` or `)3(-6` to be "matched". + +### Lexers and parsers + +You might've noticed that for `N` I use three dots and the note "all possible numbers" to signify that N can be any positive whole number. +In practice we need formally define that grammar: + +```grammar +N -> 0 | 1 | 2 | ... | 9 | 0N | 1N | 2N | ... | 9N +``` + +With this you might've realised that grammars can do anything a regular expressions can: concatenation and alternation are "built-in", and the Kleene star can be done with another rule in the form `R -> strR | str`[^regular-grammars]. +The reason we use both is that grammars are significantly slower and more complicated in code than regexes. + +#### Implementational difficulties with grammars + +Implementing (very roughly) the regular expression `acce(n | p)*t` is quite easy: + +```cpp +bool matchesp(string str) { + string regex = "acce_t"; + + for (int si = 0, ri = 0; si < str.size() && ri < regex.size(); si++, ri++) { + while (regex[ri] == '_') + if (str[si] == 'n' || str[si] == 'p') + si++; + else + ri++; + } + + if (str[si] != regex[ri]) + return false; + } + return true; +} +``` + +In brief, for concatenated characters we do a simple comparison per character. +When we reach "\_", which I use to specify we're in the `(n | p)*` part of the regex, we do comparisons with the characters n and p as much as we can, after which we continue as normal. + +Of course, this version only supports one regular expressions, however a "proper" implementation would look conceptually similar: a couple of different loops and equality checks, with maybe an additional array or two. +The huge benefit is that that loops and arrays are stupid fast, a (simple) C++ for loop could be translated into [a handful of processor instructions](https://godbolt.org/#g:!%28%28g:!%28%28g:!%28%28h:codeEditor,i:%28filename:'1',fontScale:14,fontUsePx:'0',j:1,lang:c%2B%2B,selection:%28endColumn:16,endLineNumber:6,positionColumn:16,positionLineNumber:6,selectionStartColumn:16,selectionStartLineNumber:6,startColumn:16,startLineNumber:6%29,source:'//+Type+your+code+here,+or+load+an+example.%0Aint+f%28int+num%29+%7B%0A++++for+%28int+i+%3D+1%3B+i+%3C+100%3B+i%2B%2B%29+%7B%0A++++++++num+*%3D+100%3B%0A++++%7D%0A++++return+num%3B%0A%7D'%29,l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0'%29%29,k:50,l:'4',n:'0',o:'',s:0,t:'0'%29,%28g:!%28%28h:compiler,i:%28compiler:g122,deviceViewOpen:'1',filters:%28b:'0',binary:'1',binaryObject:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'0',trim:'1'%29,flagsViewOpen:'1',fontScale:14,fontUsePx:'0',j:1,lang:c%2B%2B,libs:!%28%29,options:'',selection:%28endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1%29,source:1%29,l:'5',n:'0',o:'+x86-64+gcc+12.2+%28Editor+%231%29',t:'0'%29%29,k:50,l:'4',n:'0',o:'',s:0,t:'0'%29%29,l:'2',n:'0',o:'',t:'0'%29%29,version:4). + +On the other hand, usually grammars are more complicated and resource-intensive. +Certain ones are simple enough to implement, like `S -> aSb | cc`: + +```cpp +bool matchesp(string str) { + if (str == "cc") + return true; + else if (str[0] == 'a' && str[str.size() - 1] == 'b') + return matchesp(str.substr(1, str.size() - 2)); + else + return false; +} +``` + +However think about more complicated cases[^context-free-grammars], like `S -> aSbSa | cc`. +Implementing this one is quite a bit more difficult, since we don't know where `b` is located on the first iteration, it could either be the 4th character `accb...a` or the 9th `aaccbccab...a`. +Searching for it is also complicated, it could be the first, the last or any other `b` in the middle of the string. + +Another difficulty with grammars is ambiguity, let's look at + +```grammar +E -> E + E | E * E | n +``` + +how would it generate `n + n * n`? +There are two completely valid ways to do so: + +```grammar+ +E 🡆 E + E 🡆 n + E * E 🡆 n + n * n +``` + +```grammar+ +E 🡆 E * E 🡆 E + E * n 🡆 n + n * n +``` + +How exactly we deal with these problems comes later, for now the takeaway is that we have to try and use regular expressions wherever we can, and leave grammars as a bit of a last resort. + +#### Usage in the real world + +Let's think a bit more about grammars: they're really good at handling structure, especially recursive structure, so it's best if we use them only for that. +Our math expression grammar (from [here](#grammars)) shouldn't really care if we're trying to sum integers or floats or chars[^static-typing], it's important how everything is layed out and that our operations are done with numbers. + +This is why we're going to separate and generalize the code into [tokens](https://en.wikipedia.org/wiki/Lexical_analysis#Token), basically into building blocks. +As a rough example, we want `1 + (2 * 3)` to be transformed into `NUMBER + (NUMBER * NUMBER)`, `int var = 13;` into `TYPE NAME = NUMBER;` and so on, where "TYPE", "NUMBER" and "NAME" are tokens. +Now we're reducing the amount of "objects" our grammars need to work on: from all characters to many (but significantly fewer) tokens and some really small amount of characters. +Of course, each token will contain it's name (NUMBER, TYPE, ...) and it's value, since we aren't trying to change the code, but our grammars will work with the token names directly and just output the values at the very end. +Usually we identify at least six token types: + +- identifiers: variable and function names for example +- keywords: `if`, `while`, `for`, `return`, ... +- separators: braces, `;` +- operators: `+`, `-`, `<=` +- literals: numbers, strings, characters +- comments + +As you might've noticed, here we can use regular expressions, grouping consequtive characters is what regexes are good for. +Additionally, we're going to be reading the file, a decently slow operation, only once and for a comparatively very little time. + +In the compiler front-end, the part that implementes our regular expressions is called the "lexer", and the part that implements our grammars - the "parser". +In the last section we already talked about how easy implementing regexes (lexers) is and how difficult implementing grammars (parsers) is, let's look at the latter. + +#### Parsing algorithms + +Proper algorithms that "implement" grammars are kind of complicated, and most can handle only specific types of grammars. +Generally we categorize them into: + +- [top-down](https://en.wikipedia.org/wiki/Top-down_parsing) algorithms, which work in the way we've been talking about grammars: start with a name and replace it with it's expression, and continue replacements until we have no more names +- [bottom-up](https://en.wikipedia.org/wiki/Bottom-up_parsing) algorithms, where we do the opposite: for each substring we find from which rule it could've come from, replace it with the corresponding name, and continue upwards like that, until we reach the starting name + +Furthermore, if our algorithms allow for ambiguity (meaning we can replace a name with any one of multiple expressions), we divide them into: + +- left-most derivation algirithms, where we choose the left-most valid expression +- right-most derivation algorithms, where we chose the right-most valid expression + +The advantage and disadvantages of every type kind of depend on the exact algorithm and grammar. +Looking at some of the more famous ones: + +##### LL + +[LL](https://en.wikipedia.org/wiki/LL_parser): top-down left-most derivations algorithm that can parse only specific types of grammars. +In these grammars, every expression is uniquely identifiable by just looking at the characters (tokens) in the very beginning. +The amount of token we need to look for is very important, so we usually define LL(k) as an LL grammar that needs to look at k amount of tokens. +An "LL(k) grammar" is, by extension, a grammar which can be parsed with an LL(k) parser. + +So, the way we'll check if an expression matches our grammar, is by starting with the start name and reading the next k character from the input. +We check the first k character of all expressions, and if anyone of them is a name, we try with substitution for every possibility with that name, essentially peeking into the name's possibilities. + +- As an example, the grammar: + + ```grammar + F -> a + S -> F | (S + F) + ``` + + is LL(1). + Let's read the input `(a + a)` (the "v" points to the symbol we're looking/peeking at): + + ``` + I v + Input: (a + a) + + I v + Production: S + ``` + + we start with `S`, we peek and get the `(`, in our production we're looking at a name, S. + Let's check the first character of every expression of S. + In the first expression, the first "character" is `F`, a name, so we look at every expression for `F`. + There is only one, which is "a", different than "(", no dice. + Now we check the second expression for S, it's first character is "(", success! + We replace: + + ``` + I v + Input: (a + a) + + I v + Production: (S + F) + ``` + + Now the first symbol in our production is also `(`, so we incremenet the symbols we're looking/peeking at + + ``` + I v + Input: (a + a) + + I v + Production: (S + F) + ``` + + we peek and get the `a`, in our production the second "character" is the name `S`, `S` has to become `a`. + We do that same check from before, first expression for `S` is `F`, whose first (and only) expression is `a`, success! + + ``` + I v + Input: (a + a) + + I v + Production: (a + F) + ``` + + The middle characters " + " are matched and at the second `F` we check it's expressions, it has only `a`, success, replace, end of input, we're done. + + Another LL(1) example can be found in [Karl R. Abrahamson notes](http://www.cs.ecu.edu/karl/5220/spr16/Notes/Top-down/LL1.html). + +- The grammar + + ```grammar + B -> b + C -> c + S -> aaB | aaC + ``` + + is LL(3). + For the input `aab`, if we look at the first two "a"s, we still don't know which rule to use: `aaB` or `aaC`. + However if we look at the third symbol, "b", then we can determine that we need `aaB`. + +- Usually parsers that implement this procedure are called [recursive descent parsers](https://en.wikipedia.org/wiki/Recursive_descent_parser) + +##### LR + +[LR](https://en.wikipedia.org/wiki/LR_parser): bottom-up right-most derivations algorithm. +Conceptually, LR works in the exact opposite way to LL: for every character in the input, we find a rule that substitutes it (or that substitutes the current collection of names and character) and do so until we've reached the starting name. + +Figuring out an approach isn't as intuitive and easy as with LL, but it still isn't too hard. +It all boils down to using a whole bunch of conditional statements and tracing where we "came" from. + +- Let's look at the first LL example: + + ```grammar + F -> a + S -> F | (S + F) + ``` + + We need to track "how the current string looks", because if we read an "a", it could either be from the left handside of the "a + a" or from the right handside. + We're going to track where we came from with numbers, which I will define like this: + + |Number|Current expression ends with| + |------|---------------| + |0 |Nothing; this is the start| + |1 |The name `S`; the final number should be this| + |2 |The name `F`| + |3 |The character "("| + |4 |The character "a"| + |5 |"(S"| + |6 |"(S + "| + |7 |"(S + F"| + |8 |"(S + F)"; this is the one before the final| + + You can think of every number as the valid, but "unfinished" state of the current string. + For now don't think about how I've defined those numbers, it'll make sense later. + But you could make a table for literally every valid state: "(", "(a", "(F", "(S", ..., there is no problem. + + Keep in mind that the way I'll show the algorithm step by step isn't really correct, but will suffice for the current moment. + We'll be working with a string, where reading a character from the input means putting the latest one in the String: + + ``` + String : ( + Number : 0 + ``` + + We're reading "(", so our string "ends" on a "(" + + ``` + String : (a + Number : 3 + ``` + + We've read "a", our string "ends" on an "a". + + ``` + String : (a + Number : 4 + ``` + + Here comes the clever bit, for certain numbers, we'll stop reading forward and do something else. + If we're on the number 4, our string ends on an "a", so we're going to go backward and replace it with an F, meaning now the number is 2. + + ``` + String : (F + Number : 2 + ``` + + Here is another such rule, if our number is 2, our string ends with an "F" and we replace it with an S, now the number is 5. + That's why we have a different number for "(S + F", if we didn't, our number would become 2 and we would make "(S + S", which isn't valid. + So, think of 2 as "this is the first F". + + ``` + String : (S + Number : 5 + ``` + + We have a different number for "(S", because if we didn't, we would've gone to number 1, and could've ended the algorithm then and there, without reading the rest of the input. + Otherwise, we continue as normal, we read the `+` and the spaces around it, going to number 6. + + ``` + String : (S + a + Number : 6 + ``` + + Now, our string ends with an "a", it's tempting to change our number to 4, but we shouldn't, this would remove our progress so far! + Better yet, this number will also be special, if we have a 6 and we end with "a", rather than going to 4, we'll substitute "a" with F now and change number to 7. + + ``` + String : (S + F + Number : 7 + ``` + + And now it's trivial, we read ")", so we go to number 8. + But if we're at number 8, don't continue reading, replace with number 1. + Now that we're at number 1, if we read any character (including end of string), we'll say the string upto now matches and we're done! + + It's also helpful to put what we do in different situations in another table: + + |Number|If ends on|Change number to|Also do| + |------|----------|----------------|-------| + |0 |"(" |3 | | + |1 | | |Nothing, we matched| + |2 | |5 |Replace "F" with "S"| + |3 |"a" |4 || + |4 | |2 |Replace "a" with "F"| + |5 |" + " |6 | | + |6 |"a" |7 |Replace "a" with "F"| + |7 |")" |8 | | + |8 | |1 |Replace "(S + F)" with "S"| + + where, if there is a value in "If ends on", we read the next character, while otherwise we don't and we just execute "Change number to" and "Also do". + +- You're probably wondering why the table works so weird, like why on number 3 we don't directly replace "a" with "S" and change to number 5 for example. + The reason is that the way I showed the algorithm isn't exactly how it normally works. + Rather than tracing the current number in a variable, we trace it with a [stack](https://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29). + + When you read a character and have to go to another number, the number is added to the stack (this operation is called "shift"). + When we have to change characters from String (without reading anything), with a string (expression) of length j, we remove the last j added numbers and do a normal shift from the last number and character in String (this operation is called "reduce"). + +- Let's look at the same example, done with shift and reduce operations (without me showing the table): + + ``` + String : ( + Number : [0] + ``` + + We've read "(", add 3 on top of the stack aka shift(3). + Then we read the "a", shift(4). + + ``` + String : (a + Number : [0, 3, 4] + ``` + + With 4 we'll do a reduction, "a" gets replaced by F, 4 is removed: + + ``` + String : (F + Number : [0, 3] + ``` + + If last number is 3 and last character is "F", we're doing shift(2). + + ``` + String : (F + Number : [0, 3, 2] + ``` + + Now, we'll be doing a reduction, where F is replaced by S: + + ``` + String : (S + Number : [0, 3] + ``` + + If last number is 3 and last character is "S", we're dong shift(5). + + And so on, we continue. + As you can see, we go back and forth, from 3 to 4, back to 3, then to 2, back to 3, then to 5. + This way we avoid doing different things on different numbers. + Additionally, in the real world nobody makes this table by hand, it is generated by a program, and this method makes table generation easier. + +- As for the complete table, you can view it on the [Context Free Grammar Checker](https://smlweb.cpsc.ucalgary.ca/lr0.php?grammar=S+-%3E+F+%7C+%28+S+%2B+F+%29.%0AF+-%3E+a.&substs=) by [](TODO), + or with a more pretty styling on [Grammophone](https://mdaines.github.io/grammophone/#/), where you input on the left: + + ``` + S -> F | "(" S "+" F ")". + F -> a. + ``` + + press "Analyze", then click the link "Parsing table" at the bottom, on the row "LR(0)". + + To read the table, remember that: + + - our numbers are formally called states + - on every row you have each state + - on every column you have each possible value in the string and "$" which signifies the end of the string + - with sr or shift (or just with a number) you go to another state + - with r or reduce you make the substitution in the current string and go back one state + - acc or accept means you've reached the end + +##### LR's family + +LR is more of a family of algorithms, because there are multiple different ways to generate the table, each with it's own benefits and drawbacks. +This subject is a really big can of beans, which I'm not knowlegeable enough to talk about. +What you need to know is that there are 3 often used types: [CLR](https://en.wikipedia.org/wiki/Canonical_LR_parser), [SLR](https://en.wikipedia.org/wiki/Simple_LR_parser) and [LALR](https://en.wikipedia.org/wiki/LALR_parser). + +- CLR is an LR parser with 1 character lookahead (LR(1)), following [Knuth](TODO)'s original theory. + It requires a lot of memory for table generation, so Frank DeRemer created two simplifications: +- the SLR and LALR, which use singificantly less memory but work with a bit less grammars + +LALR is the most commonly used LR parser, however most compilers are custom-tailored pieces of software that very loosely follow the methods of LL and LR. + +##### More info + +If you want to learn more, I would highly suggest: + +- [LL and LR Parsing Demystified](https://blog.reverberate.org/2013/07/ll-and-lr-parsing-demystified.html) and [LL and LR in Context: Why Parsing Tools Are Hard](https://blog.reverberate.org/2013/09/ll-and-lr-in-context-why-parsing-tools.html) by [Josh Haberman](https://blog.reverberate.org/about/) +- [Parsing: Top-down versus bottom-up](http://jeffreykegler.github.io/Ocean-of-Awareness-blog/individual/2014/11/ll.html) by [Jeffrey Kegler](https://jeffreykegler.github.io/personal/) +- [Which Parsing Approach?](https://tratt.net/laurie/blog/2020/which_parsing_approach.html) by [Laurence Tratt](https://tratt.net/laurie/) +- [A Guide to Parsing: Algorithms and Terminology](https://tomassetti.me/guide-parsing-algorithms-terminology/) by [Gabriele Tomassetti](https://inre.me/) +- [Parsing](http://www.cs.ecu.edu/karl/5220/spr16/Notes/Parsing/index.html), [Top-Down Parsers](http://www.cs.ecu.edu/karl/5220/spr16/Notes/Top-down/index.html) and [Bottom-Up Parsers](http://www.cs.ecu.edu/karl/5220/spr16/Notes/Bottom-up/index.html) from [Karl R. Abrahamson](http://www.cs.ecu.edu/karl/5220/spr16/Notes/Bottom-up/index.html)'s notes +- [How to Impement an LR(1) Parser](https://serokell.io/blog/how-to-implement-lr1-parser) by Kirill Andreev + +#### Abstract syntax tree + +We already decided that the lexer will output tokens (and characters) to the parser, but we didn't talk about what the parser is supposed to output. +It definetly has to be some sort of structural representation of the overall code, for example, for `3 + 1 * 2` we have to be able to easily find out what the left and right handsides of the `+` and `*` are. + +Let's draw out[^nomnoml] this relationship, where the left arrow connects to the left handside and the right accordingly: + +![](./img/tree-simple.svg) + +Hey, that looks an awful lot like a [tree](https://en.wikipedia.org/wiki/Tree_%28data_structure%29)! +Trees are nodes, some sort of elements, where there is a connection from one element to some other elements, with the only rule being that cycles aren't allowed: + +![](./img/tree-cycle.svg) + +Great, but can we represent everything else with a tree? +Why, of course, for example we can represent: + +```cpp +if (a > b) + c = 5; +else + d += 10; +``` + +as + +![](./img/tree-if.svg) + +And trust me, we can represent the whole code structure with a tree. +Now, compilers are made in low-level languages like C++, so we need to think about the data type of each node (element) in our tree. +We'll definetly need [object polymorphism](https://en.wikipedia.org/wiki/Subtyping#Examples) to be able to represent different nodes. + +At a later stage we'll need to be running/evaluating the whole code with this tree, so how are we going to work with it? +When we navigate to the node `<`, we'll do "if left element is less than right, do body when true, otherwise do body when false" but are we going to implement every single operator and language feature by hand? +Or alteratively we could have a virtual method "evaluate" which changes + + + +### Implementing a front-end + +If you want, you could implement your own lexer and parser manually, but as a start, it's better to try and use already created stuff. +[Compiler-compilers](https://en.wikipedia.org/wiki/Compiler-compiler) are tools that create parsers (and more) from their normal formal definition. + +The two popular ones from the old days are lex and yacc. +lex is a lexer generator and yacc is a LALR parser generator, both of which generate a corresponding C implementation of the given regular expressions and grammars. + +#### lex + +Lex is the original program, from 1975, in the modern day it's successor/implementation is the opensource [flex](https://github.com/westes/flex). + +A lex source file is divided into three parts: + +```lex +%{ +// C code that will be put in the program verbatim +%} + +/* Definitions */ + +%% + + /* Rules */ + +%% + +// C code +``` + +where `%{%}` is used for includes and declarations, the rules are your regular expressions and the C code is the general logic of the lexer. +Usually you wouldn't write anything in the C code section, the defaults are fine, but you'll probably need to do one or two includes in the `%{%}` section. + +Rules are in the form `regex { C_code }`. +To simplify your life, you can write only the regex or a part of it inside the "definitions" part of the file, and give it a name to use later. +Referencing those names in later regexes is done by surrounding them in curly braces. +Usually the `C_code` in the regex would be a return (more commonly called "emit") of a token, which will be available in a header file, but more on that later. + +Let's look at a very simple example program: every whole number is printed as "NUMBER", while everything else is printed as-is: + +```lex +%{ +%} + +%% + +[0-9]+ { printf("NUMBER"); } +[A-z]+ { printf("%s", yytext); } + +%% +``` + +The syntax `[0-9]` is the same as `(0 | 1 | ... | 9)`, it works for any letters and is available in all modern regexes. +Note that inside every regex's "body" you have an assortment of variables already set, one of them being `yytext` which is just the whole match. +Additionally lex matches the longest possible match, so if we had a rule `[0-z]`, only it will be matched. + +If this file is located in `lexer.l`, we can compile it into a working lexer like this: + +```bash +flex lexer.l && gcc lex.yy.c -lfl +``` + +Of course, you can use your lex implementation or C compiler of choice. +Now, if you run `./a.out` you would get a prompt, every line you write will be lexically analyzed and in our case, everything will be printed out. +Entering + +``` +The number 10 changed to 8, 38, and 19 sequentially, before becoming 0. +``` + +will output + +``` +The number NUMBER changed to NUMBER, NUMBER, and NUMBER sequentially, before becoming NUMBER. +``` + +Now let's try something more sophisticated, let's surround numbers and strings in HTML tags, the stuff that power webpages. +We would want numbers to be in the format: + +``` +number +``` + +and strings: + +``` +string +``` + +We'll define numbers as both whole digits and floating point numbers (with sign) and strings can be surrounded in either single or double quotes. + +```lex +%{ +%} + +/* Only multiline comments are supported, not comments that start with // */ +/* This is a definition, it's in the format "NAME regex" */ +DIGIT [0-9] + +%% + /* Comments in here have to be indented, otherwise you'll get an error */ + /* ? means 0 or 1 of the preceding group*/ + /* + means 1 or more of the preceding group*/ + /* the backward slashes are used because . and + have special meaning in regexes*/ +[\+-]?{DIGIT}+(\.{DIGIT}+)? { printf("%s", yytext); } + + /* [^] is a group of characters, like [], however it specifies "all characters except the ones given"*/ + /* this way if we have "This is a string with " three quotes" it's not going to match the whole thing*/ +\"[^"]*\"|'[^']*' { printf("%s", yytext); } + +%% +``` + +With the input + +``` +John said 10 times "2 + 2 = 5" but '2 + 2 = 4'! +``` + +we'll get + +``` +John said 10 times "2 + 2 = 5" but '2 + 2 = 4'! +``` + +You've probably already noticed that the number inside the strings aren't matched, because the string rule results in a longer match. +In programming languages this is fine, since strings are quite often "self-contained" objects, there isn't anything in them that you would need to match. + +#### yacc + +Similarly to lex, yacc originates from 1975, and it's modern replacement is [GNU Bison](https://www.gnu.org/software/bison/). + +A yacc file looks very similar to a lex one: + +```yacc +%{ +// C code that will be put in the program verbatim +%} + +/* Settings */ + +%% + + /* Rules */ + +%% + +// C code +``` + +however rather than definitions you have settings, and the rules are in a completely different format (because they're grammars). + +## II. Virtual machines + +Let's skip over the middle layer for a second, and talk about machine instructions. +It should come as no surprise that transforming an AST to specific instructions isn't very fast or simple. +Additionally, there are thousands upon thousands of different + +[^how-did-we-get-here]: Though it's obvious, I would like to point out that modern compilers are most often written in languages that are themselves compiled. You might ask yourself "where did the first compiler come from?" The answer is simple: it was written with "numbers", with direct instructions to the processor, from the time when computers were simple enough that *all* programming was done with CPU instructions. + +[^terminals-and-nonterminals]: Formally, we call the rule "names" nonterminals, the idea being that all normal characters, that could appear in our string, are called terminals, since they would terminate replacement and string generation. For the purposes of this post, I won't use the formal names, with the hope that using less terminology will increase understandability. + +[^grammar-syntax]: This is pretty much the mathematical notation, often in CS the Backus-Naur form is used, but I find that a bit harder to read. You might also make the argument that I should use a proper unicode arrow symbol, like `→`, but `->` is way more convinient. + +[^regular-grammars]: Such grammars are called [regular grammars](https://en.wikipedia.org/wiki/Regular_grammar), more formally, every rule has to contain at most one name and that name must be at the start or end of the string characters. + +[^context-free-grammars]: Be careful about cases that are too complicated, the grammar I'm showing is "context-free", but that topic is way beyond the scope of this post. + +[^static-typing]: Yeah yeah, in a statically typed language you might not be able to do operations on doubles and integers at the same time, but you get the point. + +[^nomnoml]: The graphics are made with [nomnoml](https://nomnoml.com/) by [Daniel Kallin](https://github.com/skanaar) -- cgit v1.3.1-26-gb76a