From af4f9da6bc017a7b3278caaeebe22541d31476ac Mon Sep 17 00:00:00 2001 From: Syndamia Date: Thu, 30 Mar 2023 11:38:39 +0300 Subject: [blog/seoc] Created initial structure and added most of the first two sections --- .../index.md | 376 +++++++++++++++++++++ 1 file changed, 376 insertions(+) create mode 100644 src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md b/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md new file mode 100644 index 0000000..816e59f --- /dev/null +++ b/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md @@ -0,0 +1,376 @@ +# Sane explanation of compilers and lex+yacc + +## Contents + +1. [Preface](#preface) +2. [1. How do we understand code?](#1.-how-do-we-understand-code) + 1. [Math](#math) + 1. [Regex](#regex) + 2. [Grammars](#grammars) + 2. [Using regular expressions and grammars in the real world](#using-regular-expressions-and-grammars-in-the-real-world) + 1. [Practical problems with grammars](#practical-problems-with-grammars) + 2. [A middle ground](#a-middle-ground) + 3. [How do we use them for compiling code](#how-do-we-use-them-for-compiling-code) + 3. [Lexers and parsers](#lexers-and-parsers) + 1. [lex](#lex) + 2. [yacc](#yacc) +3. [2. How can we improve the code?] +4. [3. How do you generate machine instructions?] + 2. [Virtual machines] +5. [Compilation schemes] + 1. [AOT] + 2. [JIT] + + +Recently I signed up for a small university course about compilers. +The resources and lectors were really good, but when I sat down to study, I struggled finding simple understandable explanations for a lot of basic stuff. +Most material out there deals with specific issues or subparts, but nobody seemed to talk about the overall topic in a concise and simple manner. +Before I've forgotten everything, I'll try doing that. + +*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 requires a lot of manhours for not a lot of functionality. +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]. + +Though calling a compiler a "program" isn't necessaraly true, you could easily split it into it's main components and run each separately, feeding the output from one program to another. +Since it is more useful, I'll be talking about a compiler in the split sense, where each "layer" (and parts of layers) are separated into seprate programs. + +There are three main layers to a compiler: + +1. Front-end: it understands the program, what the code is trying to do +2. Middle: does optimizations and simplifications +3. Back-end: generates the actual machine instructions + +## 1. How do we understand code? + +The simplest programming languages would just assign names to different processor instructions, so writing "Store\_value\_from\_A\_into\_B" is actually instruction number 47, however this abstraction isn't high enough. + +Syntax in current programming languages can be quite sophisticated and ambiguous. A weird example (taken from [wikipedia](https://en.wikipedia.org/wiki/Most_vexing_parse)) with C++ would be: + +``` +void f(double d) { + int i(int(d)); +} +``` + +since it 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, not semantics. +Compiled programming languages are meant to associate specific templates of code to their corresponding machine instructions, there is no underlying meaning to code. +In natural languages, you could construct a sentence which follows all gramatical rules, but is absolute nonsence, devoid of any meaning, like ["Colorless green ideas sleep furiously"](https://en.wikipedia.org/wiki/Colorless_green_ideas_sleep_furiously). +The problem of semtantics, logical sense, is extremely difficult and isn't really "solved", however analyzing syntax is. +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 learning even the basics merits a whole university course, I'll still try to roughly explain what's important. +This field works primarily with strings via the help of two (relevant for our purposes) instruments: regular expressions and grammars. + +#### Regex + +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 cs 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. + Considering the name, this is specified with an asterisk, `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. +That is where grammars come into play, they allow us to define a structure which can "contain" itself. + +The syntax is different from regexes: a grammar is divided into rules, each rule is named and specifies an expression. +Expressions are a concatenation of strings and/or names. +Names aren't strings that will appear in our matched strings, the idea is that a name will be replaced with it's expression, they're a bit like 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. +Generally we write rules in the form `Name -> Expression`. + +For an example, with the grammar + +```grammar +S -> aSb +S -> cc +``` + +we can generate the string `aaaaccbbbb` (`🡆` shows every step, where a name is replaced): + +```grammar+ +S 🡆 aSb 🡆 aaSbb 🡆 aaaSbbb 🡆 aaaaSbbbb 🡆 aaaaccbbbb +``` + +or `accb`: + +```grammar+ +S 🡆 aSb 🡆 accb +``` + +where a and b are just characters. +To simplify our lives, usually rules with the same name are merged into one rule, separated by vertical bars (`S -> aSb | cc`), this is pretty much 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 (and rules) that allow `()3+3()` or `)3(-6` to be "matched". + +### Using regular expressions and grammars in the real world + +You might've noticed that for `N` we use three dots and the note "all possible numbers" to signify that N can be any positive whole number. +If we want to be more precise, we really should formally define the 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 a lot harder to implement, harder to work with and slower than regexes. + +#### Practical problems 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, we loop over the given string and the regex at the same time, checking if character values match on every index. +That is until we reach "\_", which I use to specify we're in the `(n | p)*` part of the regex. +Here, we loop until we've matched all "n"s and "p"s, after which we skip over this part and continue checking for equal characters. + +Even a programming novice could implement something like this, and it's pretty quick, simple, doesn't use a lot of resources. +Certain grammars have the same qualities too, `S -> aSb | cc` can be implemented with a very simple recursion: + +```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; +} +``` + +The only caveat here could be making sure the code is a tail recursion, as to not cause any stack overflow problems. + +However lets discuss the grammar `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 🡆 E + E * E 🡆 n + n * n +``` + +```grammar+ +E 🡆 E * E 🡆 E + E * E 🡆 n + n * n +``` + +#### A middle ground + +#### How do we use them for compiling code + + +#### Abstract syntax tree + +I briefly mentionted that grammers require more resources than regexes, why is that? +Well, + +### Lexers and parsers + +Now that we're armed with all of that math, we'll get to coding. +The program/part of a compiler front-end that handles the regular expresions is called a lexer, and the one that handles grammars - parser. +The job of the lexer is to split our code into strings the specify what it is (a string, a number, a type name, a function name, ...; those are called tokens) and then the grammar will use those strings in it's rules. + +So, our pipeline looks something like: + +``` +code -> LEXER -> tokens -> PARSER -> abstract syntax tree +``` + +#### lex + +How do we handle regular expressions? +The manual way is with a loop, we're going over the code and the regex at the same time. +We read both character by character, comparing them, but when we hit something special in the regex (`(,),*,|`), we handle it. +For example if we hit an opening brace, rather than compare it to the current character, we would read the regex forward until the closing brace, finding what our next possible character (string) could be, then comparing every option with the current character. + +However nobody does that, and you shouldn't too. +There is already a widely used tool called [lex](https://en.wikipedia.org/wiki/Lex_%28software%29), although usually [flex](https://en.wikipedia.org/wiki/Flex_%28lexical_analyser_generator%29) is used as an open-source alternative. + +A flex file is compiled into a C program, meaning if you want to change a regex you'll have to recompile. +It is divided into three parts: + +``` +%{ +// 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 grammars and the C code is the general logic of the lexer. +Usually you wouldn't write anything in the C code section, and do one or two includes in the `%{%}` section. + +Rules are in the form `regex { C_code }`. +To simplify your life, you can write a regex or a part of a regex inside the definitions part of the file, and give it a name to use later (you'll need to surround them in curly braces when wanting to reference them). +Usually the `C_code` in the regex would be a return for a token (more on that in yacc), which will be available in a header file, that you'll need to have included in the flex file. + +#### yacc + +[^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. + +[^empty-string-isnt-a-number]: The Kleene star specifies that something can be repeated **0** or more times, so in the case of this regex, the empty string "" will also be a number. In math, usually a plus as a supscript is defined, so 5* means 0 or more 5s, while 5^+ is 1 or more 5s. In regexes we just put a + next to the repeated string. -- cgit v1.3.1-26-gb76a From 7faf14cb34e5d9ff6ede1bb95e39fe9c62bea5f5 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Sat, 1 Apr 2023 17:01:53 +0300 Subject: [blog/seoc] Mostly finished the second section, and started on the third --- .../index.md | 317 +++++++++++++++++---- 1 file changed, 256 insertions(+), 61 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md b/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md index 816e59f..fea71ee 100644 --- a/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md +++ b/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md @@ -50,8 +50,6 @@ There are three main layers to a compiler: ## 1. How do we understand code? -The simplest programming languages would just assign names to different processor instructions, so writing "Store\_value\_from\_A\_into\_B" is actually instruction number 47, however this abstraction isn't high enough. - Syntax in current programming languages can be quite sophisticated and ambiguous. A weird example (taken from [wikipedia](https://en.wikipedia.org/wiki/Most_vexing_parse)) with C++ would be: ``` @@ -65,10 +63,11 @@ since it 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, not semantics. -Compiled programming languages are meant to associate specific templates of code to their corresponding machine instructions, there is no underlying meaning to code. -In natural languages, you could construct a sentence which follows all gramatical rules, but is absolute nonsence, devoid of any meaning, like ["Colorless green ideas sleep furiously"](https://en.wikipedia.org/wiki/Colorless_green_ideas_sleep_furiously). -The problem of semtantics, logical sense, is extremely difficult and isn't really "solved", however analyzing syntax is. +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 @@ -80,7 +79,7 @@ There is a special field in mathematics that deals with syntactical analysis: [f Although learning even the basics merits a whole university course, I'll still try to roughly explain what's important. This field works primarily with strings via the help of two (relevant for our purposes) instruments: regular expressions and grammars. -#### Regex +#### 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. @@ -123,7 +122,12 @@ At their very base, such a pattern is created with the following rules: + "ac**hievem**en**ts**". - [Kleene star](https://en.wikipedia.org/wiki/Kleene_star) - repeat the preceding letter or group, 0 or more times. - Considering the name, this is specified with an asterisk, `accents*` will match + An asterisk is used to mark this operation (hence the name, "Kleen **star**"). + + ```regex + accents* + ``` + will match + "accent" + "accent**s** @@ -190,13 +194,17 @@ Let's say you want to be able to have math expressions in your language, you can - 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. -That is where grammars come into play, they allow us to define a structure which can "contain" itself. +For this task we have a whole separate tool: grammars. -The syntax is different from regexes: a grammar is divided into rules, each rule is named and specifies an expression. -Expressions are a concatenation of strings and/or names. -Names aren't strings that will appear in our matched strings, the idea is that a name will be replaced with it's expression, they're a bit like placeholders. +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. -Generally we write rules in the form `Name -> Expression`. + +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 @@ -205,7 +213,7 @@ S -> aSb S -> cc ``` -we can generate the string `aaaaccbbbb` (`🡆` shows every step, where a name is replaced): +we can generate the string `aaaaccbbbb` (remember, our starting point is `S`): ```grammar+ S 🡆 aSb 🡆 aaSbb 🡆 aaaSbbb 🡆 aaaaSbbbb 🡆 aaaaccbbbb @@ -217,8 +225,9 @@ or `accb`: S 🡆 aSb 🡆 accb ``` -where a and b are just characters. -To simplify our lives, usually rules with the same name are merged into one rule, separated by vertical bars (`S -> aSb | cc`), this is pretty much alternation but in a different context. +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: @@ -233,21 +242,21 @@ which will sucessfully be able to match (generate) `((3 * 3) - (2 ^ 3)) + 2`: 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 (and rules) that allow `()3+3()` or `)3(-6` to be "matched". +but there are no expressions (rules) that allow `()3+3()` or `)3(-6` to be "matched". -### Using regular expressions and grammars in the real world +### Lexers and parsers -You might've noticed that for `N` we use three dots and the note "all possible numbers" to signify that N can be any positive whole number. -If we want to be more precise, we really should formally define the grammar: +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 a lot harder to implement, harder to work with and slower than regexes. +The reason we use both is that grammars are significantly slower and more complicated in code than regexes. -#### Practical problems with grammars +#### Implementational difficulties with grammars Implementing (very roughly) the regular expression `acce(n | p)*t` is quite easy: @@ -270,12 +279,14 @@ bool matchesp(string str) { } ``` -In brief, we loop over the given string and the regex at the same time, checking if character values match on every index. -That is until we reach "\_", which I use to specify we're in the `(n | p)*` part of the regex. -Here, we loop until we've matched all "n"s and "p"s, after which we skip over this part and continue checking for equal characters. +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. -Even a programming novice could implement something like this, and it's pretty quick, simple, doesn't use a lot of resources. -Certain grammars have the same qualities too, `S -> aSb | cc` can be implemented with a very simple recursion: +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) { @@ -288,9 +299,7 @@ bool matchesp(string str) { } ``` -The only caveat here could be making sure the code is a tail recursion, as to not cause any stack overflow problems. - -However lets discuss the grammar `S -> aSbSa | cc`. +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. @@ -304,73 +313,259 @@ how would it generate `n + n * n`? There are two completely valid ways to do so: ```grammar+ -E 🡆 E + E 🡆 E + E * E 🡆 n + n * n +E 🡆 E + E 🡆 n + E * E 🡆 n + n * n ``` ```grammar+ -E 🡆 E * E 🡆 E + E * E 🡆 n + n * n +E 🡆 E * E 🡆 E + E * n 🡆 n + n * n ``` -#### A middle ground +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 what grammars are supposed to do: they're really good at handling structure, especially recursive structure, so it's best if we use them only for that. +What I'm trying to say is, 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, but we didn't talk about actual impelementations of parsers. + +#### 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: + +1. [LL](https://en.wikipedia.org/wiki/LL_parser): top-down left-most derivations algorithm that can parse only specific types of grammars. + In these grammar, every expression is uniquely identifiable by just looking at the characters (tokens) in the very beginning. + If an LL(k) algorithm can parse the given grammar, we say the grammar is a "LL(k) grammar". + An "LL(k)" grammar, by extension, is any grammar where each expression is uniquely identifiable by just looking at the first k tokens. + As an example, the grammar: + + ```grammar + F -> a + S -> F | (S + F) + ``` + + is LL(1). + With the input `(a + a)`: + + - we start with S, we peek one symbol forward, to the `(`, and we find we need to match with the second expression for S + - after matching the one symbol, we peek at `a`, we find that only the first expression for S works + - and so on -#### How do we use them for compiling code + 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`. + +2. [LR](https://en.wikipedia.org/wiki/LR_parser): bottom-up right-most derivations algorithm. + It is slightly reminiscent to LL, parsing only specific grammars and needing to peek forward (lookahead; which also means LR(k) is similarly defined), but is significantly more powerful. + However, the "normal" LR parser requires a lot of memory, which spurred it's variations - the [SLR](https://en.wikipedia.org/wiki/Simple_LR_parser), [CLR](https://en.wikipedia.org/wiki/Canonical_LR_parser) and most importantly: + +3. [LALR](https://en.wikipedia.org/wiki/LALR_parser) + These memory optimizations, however, came at a cost: lower grammar parsing power, though LALR can work with the most grammars out of all the alternatives and still beats LL. #### Abstract syntax tree -I briefly mentionted that grammers require more resources than regexes, why is that? -Well, +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. -### Lexers and parsers +## Implementing a front-end + +If you want, you could implement your own lexer and parser manually, but few people do, there are already very well made tools for that. +Furthermore, at the end of the day, we want our compiler to be a singular program, or at least every layer to be a singular program. +[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: + +``` +%{ +// 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. + +#### Example 1 + +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 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. +``` + +#### Example 2 -Now that we're armed with all of that math, we'll get to coding. -The program/part of a compiler front-end that handles the regular expresions is called a lexer, and the one that handles grammars - parser. -The job of the lexer is to split our code into strings the specify what it is (a string, a number, a type name, a function name, ...; those are called tokens) and then the grammar will use those strings in it's rules. +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: -So, our pipeline looks something like: +``` +number +``` + +and strings: ``` -code -> LEXER -> tokens -> PARSER -> abstract syntax tree +string ``` -#### lex +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. -How do we handle regular expressions? -The manual way is with a loop, we're going over the code and the regex at the same time. -We read both character by character, comparing them, but when we hit something special in the regex (`(,),*,|`), we handle it. -For example if we hit an opening brace, rather than compare it to the current character, we would read the regex forward until the closing brace, finding what our next possible character (string) could be, then comparing every option with the current character. +```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] -However nobody does that, and you shouldn't too. -There is already a widely used tool called [lex](https://en.wikipedia.org/wiki/Lex_%28software%29), although usually [flex](https://en.wikipedia.org/wiki/Flex_%28lexical_analyser_generator%29) is used as an open-source alternative. +%% + /* 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); } -A flex file is compiled into a C program, meaning if you want to change a regex you'll have to recompile. -It is divided into three parts: + /* [^] 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 %} -// Definitions +/* Settings */ %% - // Rules + /* Rules */ %% // C code ``` -where `%{%}` is used for includes and declarations, the rules are your grammars and the C code is the general logic of the lexer. -Usually you wouldn't write anything in the C code section, and do one or two includes in the `%{%}` section. +[^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. -Rules are in the form `regex { C_code }`. -To simplify your life, you can write a regex or a part of a regex inside the definitions part of the file, and give it a name to use later (you'll need to surround them in curly braces when wanting to reference them). -Usually the `C_code` in the regex would be a return for a token (more on that in yacc), which will be available in a header file, that you'll need to have included in the flex file. +[^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. -#### yacc +[^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. -[^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. +[^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. -[^empty-string-isnt-a-number]: The Kleene star specifies that something can be repeated **0** or more times, so in the case of this regex, the empty string "" will also be a number. In math, usually a plus as a supscript is defined, so 5* means 0 or more 5s, while 5^+ is 1 or more 5s. In regexes we just put a + next to the repeated string. +[^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. -- cgit v1.3.1-26-gb76a From 1f73c281d0613285addf8c797f3e6f14d07e5ac7 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Sat, 1 Apr 2023 17:11:55 +0300 Subject: [blog/seoc] Reworked contents --- .../index.md | 26 ++++++++++++---------- 1 file changed, 14 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md b/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md index fea71ee..9a551eb 100644 --- a/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md +++ b/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md @@ -5,19 +5,21 @@ 1. [Preface](#preface) 2. [1. How do we understand code?](#1.-how-do-we-understand-code) 1. [Math](#math) - 1. [Regex](#regex) + 1. [Regular expressions](#regular-expressions) 2. [Grammars](#grammars) - 2. [Using regular expressions and grammars in the real world](#using-regular-expressions-and-grammars-in-the-real-world) - 1. [Practical problems with grammars](#practical-problems-with-grammars) - 2. [A middle ground](#a-middle-ground) - 3. [How do we use them for compiling code](#how-do-we-use-them-for-compiling-code) - 3. [Lexers and parsers](#lexers-and-parsers) - 1. [lex](#lex) - 2. [yacc](#yacc) -3. [2. How can we improve the code?] -4. [3. How do you generate machine instructions?] - 2. [Virtual machines] -5. [Compilation schemes] + 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) + 4. [Abstract syntax tree](#abstract-syntax-tree) +3. [Implementing a front-end](#implementing-a-front-end) + 1. [lex](#lex) + 1. [Example 1](#example-1) + 2. [Example 2](#example-2) + 2. [yacc](#yacc) +4. [2. How can we improve the code?] +5. [3. Virtual machines] +6. [Compilation schemes] 1. [AOT] 2. [JIT] -- cgit v1.3.1-26-gb76a From 89c8c3a395e738f2c55644774c61a7d304093aa0 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Mon, 3 Apr 2023 10:14:55 +0300 Subject: [blog/seoc] Renamed title and finished parsing algorithms section --- .../index.md | 573 -------------------- src/blog/sane-explanation-of-compilers/index.md | 580 +++++++++++++++++++++ 2 files changed, 580 insertions(+), 573 deletions(-) delete mode 100644 src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md create mode 100644 src/blog/sane-explanation-of-compilers/index.md (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md b/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md deleted file mode 100644 index 9a551eb..0000000 --- a/src/blog/sane-explanation-of-compilers-and-lex-yacc/index.md +++ /dev/null @@ -1,573 +0,0 @@ -# Sane explanation of compilers and lex+yacc - -## Contents - -1. [Preface](#preface) -2. [1. How do we understand code?](#1.-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) - 4. [Abstract syntax tree](#abstract-syntax-tree) -3. [Implementing a front-end](#implementing-a-front-end) - 1. [lex](#lex) - 1. [Example 1](#example-1) - 2. [Example 2](#example-2) - 2. [yacc](#yacc) -4. [2. How can we improve the code?] -5. [3. 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 really good, but when I sat down to study, I struggled finding simple understandable explanations for a lot of basic stuff. -Most material out there deals with specific issues or subparts, but nobody seemed to talk about the overall topic in a concise and simple manner. -Before I've forgotten everything, I'll try doing that. - -*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 requires a lot of manhours for not a lot of functionality. -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]. - -Though calling a compiler a "program" isn't necessaraly true, you could easily split it into it's main components and run each separately, feeding the output from one program to another. -Since it is more useful, I'll be talking about a compiler in the split sense, where each "layer" (and parts of layers) are separated into seprate programs. - -There are three main layers to a compiler: - -1. Front-end: it understands the program, what the code is trying to do -2. Middle: does optimizations and simplifications -3. Back-end: generates the actual machine instructions - -## 1. How do we understand code? - -Syntax in current programming languages can be quite sophisticated and ambiguous. A weird example (taken from [wikipedia](https://en.wikipedia.org/wiki/Most_vexing_parse)) with C++ would be: - -``` -void f(double d) { - int i(int(d)); -} -``` - -since it 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 learning even the basics merits a whole university course, I'll still try to roughly explain what's important. -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 cs 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, "Kleen **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 what grammars are supposed to do: they're really good at handling structure, especially recursive structure, so it's best if we use them only for that. -What I'm trying to say is, 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, but we didn't talk about actual impelementations of parsers. - -#### 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: - -1. [LL](https://en.wikipedia.org/wiki/LL_parser): top-down left-most derivations algorithm that can parse only specific types of grammars. - In these grammar, every expression is uniquely identifiable by just looking at the characters (tokens) in the very beginning. - If an LL(k) algorithm can parse the given grammar, we say the grammar is a "LL(k) grammar". - An "LL(k)" grammar, by extension, is any grammar where each expression is uniquely identifiable by just looking at the first k tokens. - As an example, the grammar: - - ```grammar - F -> a - S -> F | (S + F) - ``` - - is LL(1). - With the input `(a + a)`: - - - we start with S, we peek one symbol forward, to the `(`, and we find we need to match with the second expression for S - - after matching the one symbol, we peek at `a`, we find that only the first expression for S works - - and so on - - 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`. - -2. [LR](https://en.wikipedia.org/wiki/LR_parser): bottom-up right-most derivations algorithm. - It is slightly reminiscent to LL, parsing only specific grammars and needing to peek forward (lookahead; which also means LR(k) is similarly defined), but is significantly more powerful. - However, the "normal" LR parser requires a lot of memory, which spurred it's variations - the [SLR](https://en.wikipedia.org/wiki/Simple_LR_parser), [CLR](https://en.wikipedia.org/wiki/Canonical_LR_parser) and most importantly: - -3. [LALR](https://en.wikipedia.org/wiki/LALR_parser) - These memory optimizations, however, came at a cost: lower grammar parsing power, though LALR can work with the most grammars out of all the alternatives and still beats LL. - -#### 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. - -## Implementing a front-end - -If you want, you could implement your own lexer and parser manually, but few people do, there are already very well made tools for that. -Furthermore, at the end of the day, we want our compiler to be a singular program, or at least every layer to be a singular program. -[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: - -``` -%{ -// 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. - -#### Example 1 - -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 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. -``` - -#### Example 2 - -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 -``` - -[^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. diff --git a/src/blog/sane-explanation-of-compilers/index.md b/src/blog/sane-explanation-of-compilers/index.md new file mode 100644 index 0000000..bfd4eeb --- /dev/null +++ b/src/blog/sane-explanation-of-compilers/index.md @@ -0,0 +1,580 @@ +# Sane explanation of compilers + +## Contents + +1. [Preface](#preface) +2. [1. How do we understand code?](#1.-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) + 4. [Abstract syntax tree](#abstract-syntax-tree) +3. [Implementing a front-end](#implementing-a-front-end) + 1. [lex](#lex) + 1. [Example 1](#example-1) + 2. [Example 2](#example-2) + 2. [yacc](#yacc) +4. [2. How can we improve the code?] +5. [3. 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 really good, but when I sat down to study, I struggled finding simple understandable explanations for a lot of basic stuff. +Most material out there deals with specific issues or subparts, but nobody seemed to talk about the overall topic in a concise and simple manner. +Before I've forgotten everything, I'll try doing that. + +*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 requires a lot of manhours for not a lot of functionality. +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]. + +Though calling a compiler a "program" isn't necessaraly true, you could easily split it into it's main components and run each separately, feeding the output from one program to another. +Since it is more useful, I'll be talking about a compiler in the split sense, where each "layer" (and parts of layers) are separated into seprate programs. + +There are three main layers to a compiler: + +1. Front-end: it understands the program, what the code is trying to do +2. Middle: does optimizations and simplifications +3. Back-end: generates the actual machine instructions + +## 1. How do we understand code? + +Syntax in current programming languages can be quite sophisticated and ambiguous. A weird example (taken from [wikipedia](https://en.wikipedia.org/wiki/Most_vexing_parse)) with C++ would be: + +``` +void f(double d) { + int i(int(d)); +} +``` + +since it 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 learning even the basics merits a whole university course, I'll still try to roughly explain what's important. +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 cs 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, "Kleen **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 what grammars are supposed to do: they're really good at handling structure, especially recursive structure, so it's best if we use them only for that. +What I'm trying to say is, 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, but we didn't talk about actual impelementations of parsers. + +#### 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: + +1. [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. + As an example, the grammar: + + ```grammar + F -> a + S -> F | (S + F) + ``` + + is LL(1). + With the input `(a + a)`: + + - we start with S, we peek one symbol forward, to the `(`, and we find we need to match with the second expression for S + - after matching the one symbol, we peek at `a`, we find that only the first expression for S works + - and so on + + 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`. + +2. [LR](https://en.wikipedia.org/wiki/LR_parser): bottom-up right-most derivations algorithm. + Also parses only specific grammars and needs to peek forward (lookahead; which also means LR(k) is similarly defined), but is significantly more powerful. + However, the "normal" LR parser requires a lot of memory, which spurred it's variations - the [SLR](https://en.wikipedia.org/wiki/Simple_LR_parser), [CLR](https://en.wikipedia.org/wiki/Canonical_LR_parser) and most importantly: + +3. [LALR](https://en.wikipedia.org/wiki/LALR_parser). + These memory optimizations, however, came at a cost: lower grammar parsing power, though LALR can work with the most grammars out of all the alternatives and still beats LL. + +Unfortunately, these algorithms are way out of my area of knowledge, and furthermore a lot of parsers are custom-tailored for their language. +If you want to dive deeper, I would 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/) +- [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/) + +#### 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. + +## Implementing a front-end + +If you want, you could implement your own lexer and parser manually, but few people do, there are already very well made tools for that. +Furthermore, at the end of the day, we want our compiler to be a singular program, or at least every layer to be a singular program. +[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: + +``` +%{ +// 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. + +#### Example 1 + +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 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. +``` + +#### Example 2 + +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 +``` + +[^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. -- cgit v1.3.1-26-gb76a From b68669d9707d59be7c4764f1a3ef19ed011b5352 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Mon, 3 Apr 2023 10:28:19 +0300 Subject: [blog/seoc] Added more links to parsing algorithms section --- src/blog/sane-explanation-of-compilers/index.md | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/index.md b/src/blog/sane-explanation-of-compilers/index.md index bfd4eeb..828d849 100644 --- a/src/blog/sane-explanation-of-compilers/index.md +++ b/src/blog/sane-explanation-of-compilers/index.md @@ -405,8 +405,11 @@ Unfortunately, these algorithms are way out of my area of knowledge, and further If you want to dive deeper, I would 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 -- cgit v1.3.1-26-gb76a From a41055a02138df7cc234dc6643aa805dc5d48ae5 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Mon, 3 Apr 2023 23:13:50 +0300 Subject: [blog/seoc] Minor wording changes --- src/blog/sane-explanation-of-compilers/index.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/index.md b/src/blog/sane-explanation-of-compilers/index.md index 828d849..9fe11af 100644 --- a/src/blog/sane-explanation-of-compilers/index.md +++ b/src/blog/sane-explanation-of-compilers/index.md @@ -401,7 +401,7 @@ Looking at some of the more famous ones: 3. [LALR](https://en.wikipedia.org/wiki/LALR_parser). These memory optimizations, however, came at a cost: lower grammar parsing power, though LALR can work with the most grammars out of all the alternatives and still beats LL. -Unfortunately, these algorithms are way out of my area of knowledge, and furthermore a lot of parsers are custom-tailored for their language. +Unfortunately, these algorithms are way out of my area of knowledge, and furthermore most parsers are custom-tailored for their language. If you want to dive deeper, I would 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/) @@ -417,8 +417,7 @@ We already decided that the lexer will output tokens (and characters) to the par ## Implementing a front-end -If you want, you could implement your own lexer and parser manually, but few people do, there are already very well made tools for that. -Furthermore, at the end of the day, we want our compiler to be a singular program, or at least every layer to be a singular program. +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. @@ -470,7 +469,7 @@ Let's look at a very simple example program: every whole number is printed as "N %% ``` -The syntax `[0-9]` is the same as `(0 | 1 | ... | 9)`, it is available in all modern regexes. +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. -- cgit v1.3.1-26-gb76a From 981a98a316c813eb2ac3ec98625b0909b1e50974 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Tue, 4 Apr 2023 21:28:23 +0300 Subject: [blog/seoc] Explained parsing algorithms in more detail and started work on AST --- src/blog/sane-explanation-of-compilers/index.md | 318 ++++++++++++++++++++---- 1 file changed, 276 insertions(+), 42 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/index.md b/src/blog/sane-explanation-of-compilers/index.md index 9fe11af..eb65f9c 100644 --- a/src/blog/sane-explanation-of-compilers/index.md +++ b/src/blog/sane-explanation-of-compilers/index.md @@ -25,9 +25,8 @@ Recently I signed up for a small university course about compilers. -The resources and lectors were really good, but when I sat down to study, I struggled finding simple understandable explanations for a lot of basic stuff. -Most material out there deals with specific issues or subparts, but nobody seemed to talk about the overall topic in a concise and simple manner. -Before I've forgotten everything, I'll try doing that. +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). @@ -39,12 +38,7 @@ That is why, over time, programmers have tried to abstract sets of instructions 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]. - -Though calling a compiler a "program" isn't necessaraly true, you could easily split it into it's main components and run each separately, feeding the output from one program to another. -Since it is more useful, I'll be talking about a compiler in the split sense, where each "layer" (and parts of layers) are separated into seprate programs. - -There are three main layers to a compiler: +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 @@ -52,7 +46,7 @@ There are three main layers to a compiler: ## 1. How do we understand code? -Syntax in current programming languages can be quite sophisticated and ambiguous. A weird example (taken from [wikipedia](https://en.wikipedia.org/wiki/Most_vexing_parse)) with C++ would be: +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) { @@ -60,13 +54,13 @@ void f(double d) { } ``` -since it could be interpreted either as a: +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. +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. @@ -78,7 +72,7 @@ A word of caution, I'll use a decent amount of fancy names, so I have a way to m 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 learning even the basics merits a whole university course, I'll still try to roughly explain what's important. +Although learning even the basics merits a whole university course, I'll still try to roughly explain what's important, for those that haven't studyied it. This field works primarily with strings via the help of two (relevant for our purposes) instruments: regular expressions and grammars. #### Regular expressions @@ -91,7 +85,7 @@ 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 cs are grouped together. + 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. @@ -364,45 +358,273 @@ Furthermore, if our algorithms allow for ambiguity (meaning we can replace a nam The advantage and disadvantages of every type kind of depend on the exact algorithm and grammar. Looking at some of the more famous ones: -1. [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. - As an example, the grammar: +##### 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) + ``` - ```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 ``` - is LL(1). - With the input `(a + a)`: + 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: - - we start with S, we peek one symbol forward, to the `(`, and we find we need to match with the second expression for S - - after matching the one symbol, we peek at `a`, we find that only the first expression for S works - - and so on + ``` + I v + Input: (a + a) + + I v + Production: (S + F) + ``` - The grammar + Now the first symbol in our production is also `(`, so we incremenet the symbols we're looking/peeking at - ```grammar - B -> b - C -> c - S -> aaB | aaC ``` + 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 check and the second expression won't do, so we replace with the first + + ``` + I v + Input: (a + a) + + I v + Production: (F + F) + ``` + + We're still peaking at `a`, in the current production we're looking at the name `F`, which can be replaced with `a` (or a string that starts with `a`, we only check the first character of each rule). + We replace, then incremenet the symbols, matches the middle characters, when at the second `F` we do the same, replace with `a`, then match `)` and 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 - 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`. +[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. -2. [LR](https://en.wikipedia.org/wiki/LR_parser): bottom-up right-most derivations algorithm. - Also parses only specific grammars and needs to peek forward (lookahead; which also means LR(k) is similarly defined), but is significantly more powerful. - However, the "normal" LR parser requires a lot of memory, which spurred it's variations - the [SLR](https://en.wikipedia.org/wiki/Simple_LR_parser), [CLR](https://en.wikipedia.org/wiki/Canonical_LR_parser) and most importantly: +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. -3. [LALR](https://en.wikipedia.org/wiki/LALR_parser). - These memory optimizations, however, came at a cost: lower grammar parsing power, though LALR can work with the most grammars out of all the alternatives and still beats LL. +- Let's look at the first LL example. + 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: -Unfortunately, these algorithms are way out of my area of knowledge, and furthermore most parsers are custom-tailored for their language. -If you want to dive deeper, I would suggest: + |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. + It's important to note that this table is the most compact one possible, you could make a table for literally every valid state: "(", "(a", "(F", "(S", ... + + 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", so we should 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. + + 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 | | |Finished| + |2 | |5 |Replace "F" with "S"| + |3 |"a" |4 |Decrement reading| + |4 | |2 |Replace "a" with "F"| + |5 |" + " |6 | | + |6 | |7 |Replace "a" with "F"| + |7 |")" |8 | | + |8 | |1 |Replace "(S + F)" with "S"| + +- What you might notice is that + + 1. this "isn't" the smallest amount of number that work, we could remove 2 and in rule 4 directly replace "a" with "S", and + 2. we're replacing "a" with "F" in two different rules, isn't there a way to do it in only one? + + The reason for both is that the way I showed the algorithm isn't exactly the way it normally works. + Rather than tracing the current number in a variable, we trace it with a stack, essentially an array. + + When you read the character and have to go to another number, the number is now added to the array (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 is how we avoid doing the same thing on different numbers and why the initial amount of numbers is the smallest amount. + +- 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 what I didn't touch on and is very important was generation of the table. +This subject is really big can of beans, but generally 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/) @@ -414,6 +636,18 @@ If you want to dive deeper, I would suggest: #### 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 `1 * 2 + 3` we have to be able to easily find out what the left and right handsides of the `+` and `*` are. +Drawing out this relationship, where the left line connects to the left handside and the right accordingly: + +``` + + + / \ + * 3 + / \ +1 2 +``` + +We notice it looks awfully a lot like a tree! ## Implementing a front-end -- cgit v1.3.1-26-gb76a From a9b1b1b1a698cd56902f913a58b96c9017b39b55 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Tue, 11 Apr 2023 08:57:09 +0300 Subject: [styles] Updated code and pre line-height --- src/styles.css | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/styles.css b/src/styles.css index cf639fd..f30dbb9 100644 --- a/src/styles.css +++ b/src/styles.css @@ -208,6 +208,7 @@ pre { code, pre { font-family: monospace; font-size: 1em; + line-height: 1em; } code { -- cgit v1.3.1-26-gb76a From beda446222759a5b9978f3fff45a2ec963cfc71f Mon Sep 17 00:00:00 2001 From: Syndamia Date: Wed, 12 Apr 2023 14:50:25 +0300 Subject: [styles] Some minor modifications and removal of custom selection --- src/styles.css | 72 ++++++++++++++++++++-------------------------------------- 1 file changed, 24 insertions(+), 48 deletions(-) (limited to 'src') diff --git a/src/styles.css b/src/styles.css index f30dbb9..88db27a 100644 --- a/src/styles.css +++ b/src/styles.css @@ -74,18 +74,6 @@ --tr-bg-color: #fff; } -/* Custom mouse text selection colors */ - -::selection { - background: var(--bg-selection-color); - color: var(--fg-selection-color); - } - ::-moz-selection { - background: var(--bg-selection-color); - color: var(--fg-selection-color); - } - - /* Global */ body { @@ -109,7 +97,7 @@ img { .file-icon { min-width: 1.3em; vertical-align: text-bottom; } .borderless, .oldschool-badge, .file-icon { border: none; } - .setting-btn { border: none !important; vertical-align: middle; } + .setting-btn { border: none; vertical-align: middle; } .btn:hover { cursor: pointer; } /* image-show.js */ @@ -118,8 +106,8 @@ img { border: none; height: 100vh; left: 0; - max-width: none !important; - max-height: none !important; + max-width: none; + max-height: none; object-fit: contain; padding: 1em; position: fixed; @@ -131,7 +119,6 @@ img { strong { color: var(--strong-color); } - a, a strong { border-bottom: 1px dashed; color: var(--a-color); @@ -196,42 +183,33 @@ h1, h2, h3, h4, h5, h6, b { h3::after { content: " \2550"; } /* The following CSS is a modified version of sindresorhus's github-markdown-css repo: https://github.com/sindresorhus/github-markdown-css */ -pre { - background-color: var(--pre-bg-color); - font-size: 85%; - line-height: 1.45; - overflow: auto; - padding: 16px; - word-break: normal; - word-wrap: normal; - } - code, pre { - font-family: monospace; - font-size: 1em; - line-height: 1em; +code, pre { + background-color: var(--pre-bg-color); + font-family: monospace; + line-height: 1em; +} + pre { + overflow: auto; + padding: 0.9em; + word-break: normal; + word-wrap: normal; } - code { - background-color: var(--code-bg-color); - font-size: 85%; margin: 0; - padding: 0 .4em; + font-size: 85%; + padding: 0 0.4em; } pre code { - background-color: var(--code-bg-color); border: 0; display: inline; - line-height: inherit; - margin: 0; overflow: visible; padding: 0; word-wrap: normal; } pre > code { - background-color: inherit; white-space: pre; word-break: normal; - padding-right: 16px; + padding-right: 0.9em; } table code { font-size: 0.7em; @@ -242,8 +220,7 @@ pre { table { border-spacing: 0; border-collapse: collapse; - margin-top: 10px; - margin-bottom: 10px; + margin: 0.6em 0; overflow: auto; width: 100%; } @@ -251,11 +228,10 @@ table { table td:not(:first-of-type), table th:not(:first-of-type) { border-left: 2px dashed var(--table-border-color); } - table td:not(:empty) { padding: 0.5em; } + table td:not(:empty), table th:not(:empty) { padding: 0.5em; } table th:not(:empty) { font-size: 1.1em; - font-weight: 600; - padding: 0.2em; + font-weight: bold; } table tr:not(:first-of-type) { @@ -291,17 +267,17 @@ dt { font-size: 1.2em; } /* Main elements: content-wrapper, sidebar, article, header, footer */ -#content-wrapper { +#content-wrapper, .sidebar { border-right: 3px solid var(--accent-line-color); display: flex; - flex-direction: row; - min-height: calc(100vh - 16px); } + #content-wrapper { + flex-direction: row; + min-height: calc(100vh - 16px); + } .sidebar { - border: 3px solid var(--accent-line-color); border-top: none; border-right: none; - display: flex; flex-direction: column; font-size: 1.2em; max-width: 11.2em; -- cgit v1.3.1-26-gb76a From 9442627e595bf67e17d1cdd6793bacb707b86207 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Wed, 12 Apr 2023 15:00:18 +0300 Subject: [styles] Fixed sidebar border and imrpoved small screen looks --- src/styles.css | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/styles.css b/src/styles.css index 88db27a..5857b46 100644 --- a/src/styles.css +++ b/src/styles.css @@ -270,14 +270,14 @@ dt { font-size: 1.2em; } #content-wrapper, .sidebar { border-right: 3px solid var(--accent-line-color); display: flex; + flex-direction: row; + min-height: calc(100vh - 16px); } - #content-wrapper { - flex-direction: row; - min-height: calc(100vh - 16px); - } .sidebar { + border: 3px solid var(--accent-line-color); border-top: none; border-right: none; + display: flex; flex-direction: column; font-size: 1.2em; max-width: 11.2em; @@ -378,7 +378,10 @@ dt { font-size: 1.2em; } /* Small screen support */ @media screen and (max-width: 610px) { - article { max-width: calc(100vw - 16px - 3px); } + article { + border-top: none; + max-width: calc(100vw - 16px - 3px); + } table td, table th { word-break: break-all; } #content-wrapper { flex-direction: column; } @@ -389,7 +392,6 @@ dt { font-size: 1.2em; } #index-contents-img { max-width: 4.38em; } .sidebar { - margin-right: 8px; max-width: initial; padding-right: 1em; } -- cgit v1.3.1-26-gb76a From 2b2cbc4eb7cc6499327bee6b3ec19f1544c4f842 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Wed, 12 Apr 2023 16:53:53 +0300 Subject: [blog/seoc] Restructuring, minor changes to LR parsers and added more stuff for AST --- .../img/tree-cycle.svg | 55 +++++++ .../sane-explanation-of-compilers/img/tree-if.svg | 178 +++++++++++++++++++++ .../img/tree-simple.svg | 80 +++++++++ src/blog/sane-explanation-of-compilers/index.md | 154 +++++++++++------- 4 files changed, 409 insertions(+), 58 deletions(-) create mode 100644 src/blog/sane-explanation-of-compilers/img/tree-cycle.svg create mode 100644 src/blog/sane-explanation-of-compilers/img/tree-if.svg create mode 100644 src/blog/sane-explanation-of-compilers/img/tree-simple.svg (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/img/tree-cycle.svg b/src/blog/sane-explanation-of-compilers/img/tree-cycle.svg new file mode 100644 index 0000000..408177e --- /dev/null +++ b/src/blog/sane-explanation-of-compilers/img/tree-cycle.svg @@ -0,0 +1,55 @@ + + [A]->[B] + [B]->[C] + [C]->[A] + + + + + + + + + + + + + + + + + + + + A + + + + + + + + + + + B + + + + + + + + + + + C + + + + + + + + + \ No newline at end of file diff --git a/src/blog/sane-explanation-of-compilers/img/tree-if.svg b/src/blog/sane-explanation-of-compilers/img/tree-if.svg new file mode 100644 index 0000000..4b8ae1d --- /dev/null +++ b/src/blog/sane-explanation-of-compilers/img/tree-if.svg @@ -0,0 +1,178 @@ + + [if]->[>] + [>]->[a] + [>]->[b] + [if]->[body when true] + [body when true]->[=] + [=]->[c] + [=]->[5] + [if]->[body when false] + [body when false]->[+=] + [+=]->[d] + [+=]->[10] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + if + + + + + + + + + + + > + + + + + + + + + + + a + + + + + + + + + + + b + + + + + + + + + + + body when true + + + + + + + + + + + = + + + + + + + + + + + c + + + + + + + + + + + 5 + + + + + + + + + + + body when false + + + + + + + + + + + += + + + + + + + + + + + d + + + + + + + + + + + 10 + + + + + + + + + \ No newline at end of file diff --git a/src/blog/sane-explanation-of-compilers/img/tree-simple.svg b/src/blog/sane-explanation-of-compilers/img/tree-simple.svg new file mode 100644 index 0000000..172472c --- /dev/null +++ b/src/blog/sane-explanation-of-compilers/img/tree-simple.svg @@ -0,0 +1,80 @@ + + [+]->[*] + [*]->[1] + [*]->[2] + [+]->[3] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + * + + + + + + + + + + + 1 + + + + + + + + + + + 2 + + + + + + + + + + + 3 + + + + + + + + + \ No newline at end of file diff --git a/src/blog/sane-explanation-of-compilers/index.md b/src/blog/sane-explanation-of-compilers/index.md index eb65f9c..21a6b64 100644 --- a/src/blog/sane-explanation-of-compilers/index.md +++ b/src/blog/sane-explanation-of-compilers/index.md @@ -3,7 +3,7 @@ ## Contents 1. [Preface](#preface) -2. [1. How do we understand code?](#1.-how-do-we-understand-code) +2. [I. How do we understand code?](#i.-how-do-we-understand-code) 1. [Math](#math) 1. [Regular expressions](#regular-expressions) 2. [Grammars](#grammars) @@ -11,14 +11,15 @@ 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) - 1. [Example 1](#example-1) - 2. [Example 2](#example-2) - 2. [yacc](#yacc) -4. [2. How can we improve the code?] -5. [3. Virtual machines] + 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] @@ -33,7 +34,7 @@ Before I've forgotten everything, I'll try to hit that middle spot, generally co ## 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 requires a lot of manhours for not a lot of functionality. +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. @@ -41,10 +42,10 @@ The tradeoff is that we need to translate our nice programmer code to numbers a 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 +2. Middle: does optimizations and simplifications, though this part is often inside the back-end 3. Back-end: generates the actual machine instructions -## 1. How do we understand code? +## 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 @@ -72,7 +73,7 @@ A word of caution, I'll use a decent amount of fancy names, so I have a way to m 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 learning even the basics merits a whole university course, I'll still try to roughly explain what's important, for those that haven't studyied it. +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 @@ -118,7 +119,7 @@ At their very base, such a pattern is created with the following rules: + "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, "Kleen **star**"). + An asterisk is used to mark this operation (hence the name, "Kleene **star**"). ```regex accents* @@ -320,8 +321,8 @@ How exactly we deal with these problems comes later, for now the takeaway is tha #### Usage in the real world -Let's think a bit more about what grammars are supposed to do: they're really good at handling structure, especially recursive structure, so it's best if we use them only for that. -What I'm trying to say is, 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. +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. @@ -340,7 +341,7 @@ As you might've noticed, here we can use regular expressions, grouping consequti 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, but we didn't talk about actual impelementations of parsers. +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 @@ -388,7 +389,7 @@ We check the first k character of all expressions, and if anyone of them is a na 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. + 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: @@ -412,18 +413,17 @@ We check the first k character of all expressions, and if anyone of them is a na ``` we peek and get the `a`, in our production the second "character" is the name `S`, `S` has to become `a`. - We check and the second expression won't do, so we replace with the first + 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: (F + F) + Production: (a + F) ``` - We're still peaking at `a`, in the current production we're looking at the name `F`, which can be replaced with `a` (or a string that starts with `a`, we only check the first character of each rule). - We replace, then incremenet the symbols, matches the middle characters, when at the second `F` we do the same, replace with `a`, then match `)` and we're done. + 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). @@ -449,7 +449,13 @@ Conceptually, LR works in the exact opposite way to LL: for every character in t 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. +- 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: @@ -466,7 +472,8 @@ It all boils down to using a whole bunch of conditional statements and tracing w |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. - It's important to note that this table is the most compact one possible, you could make a table for literally every valid state: "(", "(a", "(F", "(S", ... + 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: @@ -515,7 +522,7 @@ It all boils down to using a whole bunch of conditional statements and tracing w Number : 6 ``` - Now, our string ends with an "a", so we should change our number to 4, but we shouldn't, this would remove our progress so far! + 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. ``` @@ -525,31 +532,29 @@ It all boils down to using a whole bunch of conditional statements and tracing w 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. + 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 | | |Finished| + |1 | | |Nothing, we matched| |2 | |5 |Replace "F" with "S"| - |3 |"a" |4 |Decrement reading| + |3 |"a" |4 || |4 | |2 |Replace "a" with "F"| |5 |" + " |6 | | - |6 | |7 |Replace "a" with "F"| + |6 |"a" |7 |Replace "a" with "F"| |7 |")" |8 | | |8 | |1 |Replace "(S + F)" with "S"| -- What you might notice is that - - 1. this "isn't" the smallest amount of number that work, we could remove 2 and in rule 4 directly replace "a" with "S", and - 2. we're replacing "a" with "F" in two different rules, isn't there a way to do it in only one? + 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". - The reason for both is that the way I showed the algorithm isn't exactly the way it normally works. - Rather than tracing the current number in a variable, we trace it with a stack, essentially an array. +- 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 the character and have to go to another number, the number is now added to the array (this operation is called "shift"). + 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): @@ -592,9 +597,11 @@ It all boils down to using a whole bunch of conditional statements and tracing w 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 is how we avoid doing the same thing on different numbers and why the initial amount of numbers is the smallest amount. + 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: +- 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 ")". @@ -614,11 +621,13 @@ It all boils down to using a whole bunch of conditional statements and tracing w ##### LR's family -LR is more of a family of algorithms, because what I didn't touch on and is very important was generation of the table. -This subject is really big can of beans, but generally 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). +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. +- 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. @@ -636,20 +645,42 @@ If you want to learn more, I would highly suggest: #### 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 `1 * 2 + 3` we have to be able to easily find out what the left and right handsides of the `+` and `*` are. -Drawing out this relationship, where the left line connects to the left handside and the right accordingly: +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; ``` - + - / \ - * 3 - / \ -1 2 -``` -We notice it looks awfully a lot like a tree! +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 + +### 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. @@ -657,13 +688,13 @@ If you want, you could implement your own lexer and parser manually, but as a st 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 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 %} @@ -687,8 +718,6 @@ To simplify your life, you can write only the regex or a part of it inside the " 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. -#### Example 1 - Let's look at a very simple example program: every whole number is printed as "NUMBER", while everything else is printed as-is: ```lex @@ -727,8 +756,6 @@ will output The number NUMBER changed to NUMBER, NUMBER, and NUMBER sequentially, before becoming NUMBER. ``` -#### Example 2 - 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: @@ -781,7 +808,7 @@ John said 10 times "2 + 2 = 5" 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 +#### yacc Similarly to lex, yacc originates from 1975, and it's modern replacement is [GNU Bison](https://www.gnu.org/software/bison/). @@ -803,6 +830,15 @@ A yacc file looks very similar to a lex one: // 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. @@ -814,3 +850,5 @@ A yacc file looks very similar to a lex one: [^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 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 From 5e1e496ccc2141fdab53c7033611e8b590a6c104 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Thu, 13 Apr 2023 13:53:27 +0300 Subject: [blog/seoc] Index page as a contents listing --- src/blog/sane-explanation-of-compilers/index.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 src/blog/sane-explanation-of-compilers/index.md (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/index.md b/src/blog/sane-explanation-of-compilers/index.md new file mode 100644 index 0000000..cd0cf4b --- /dev/null +++ b/src/blog/sane-explanation-of-compilers/index.md @@ -0,0 +1,6 @@ +# Sane explanation of compilers + +This blogpost is split into multiple parts. +More information is available in the first part. + +- [Part 1](./part-1.html): Introduction and The frontend (aka How do we understand code) -- cgit v1.3.1-26-gb76a From 087af3f9d69618d3a9ab070347e13c52870c3da9 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Thu, 13 Apr 2023 14:21:04 +0300 Subject: [blog/seoc] Added background to trees --- src/blog/sane-explanation-of-compilers/img/tree-cycle.svg | 5 +++-- src/blog/sane-explanation-of-compilers/img/tree-if.svg | 5 +++-- src/blog/sane-explanation-of-compilers/img/tree-simple.svg | 5 +++-- 3 files changed, 9 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/img/tree-cycle.svg b/src/blog/sane-explanation-of-compilers/img/tree-cycle.svg index 408177e..f679b0e 100644 --- a/src/blog/sane-explanation-of-compilers/img/tree-cycle.svg +++ b/src/blog/sane-explanation-of-compilers/img/tree-cycle.svg @@ -1,10 +1,11 @@ - [A]->[B] + #background: #fdf6e3 + [A]->[B] [B]->[C] [C]->[A] - + diff --git a/src/blog/sane-explanation-of-compilers/img/tree-if.svg b/src/blog/sane-explanation-of-compilers/img/tree-if.svg index 4b8ae1d..06ddcf6 100644 --- a/src/blog/sane-explanation-of-compilers/img/tree-if.svg +++ b/src/blog/sane-explanation-of-compilers/img/tree-if.svg @@ -1,5 +1,6 @@ - [if]->[>] + #background: #fdf6e3 + [if]->[>] [>]->[a] [>]->[b] [if]->[body when true] @@ -12,7 +13,7 @@ [+=]->[10] - + diff --git a/src/blog/sane-explanation-of-compilers/img/tree-simple.svg b/src/blog/sane-explanation-of-compilers/img/tree-simple.svg index 172472c..9f978a7 100644 --- a/src/blog/sane-explanation-of-compilers/img/tree-simple.svg +++ b/src/blog/sane-explanation-of-compilers/img/tree-simple.svg @@ -1,11 +1,12 @@ - [+]->[*] + #background: #fdf6e3 + [+]->[*] [*]->[1] [*]->[2] [+]->[3] - + -- cgit v1.3.1-26-gb76a From 01e91bc3caf59f23c28ee0630c3d9b65363fe753 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Thu, 13 Apr 2023 14:21:19 +0300 Subject: [blog/seoc] Finalized contents and wrote a bit --- src/blog/sane-explanation-of-compilers/part-1.md | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/part-1.md b/src/blog/sane-explanation-of-compilers/part-1.md index 250d9d2..24c87fd 100644 --- a/src/blog/sane-explanation-of-compilers/part-1.md +++ b/src/blog/sane-explanation-of-compilers/part-1.md @@ -9,15 +9,17 @@ 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) + 2. [Practical usage](#practical-usage) 3. [Parsing algorithms](#parsing-algorithms) 1. [LL](#ll) 2. [LR](#lr) 3. [LR's family](#lrs-family) + 4. [More info](#more-info) 4. [Abstract syntax tree](#abstract-syntax-tree) 3. [Implementing a front-end](#implementing-a-front-end) 1. [lex](#lex) 2. [yacc](#yacc) + 3. [Using them together](#using-them-together) 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. @@ -317,7 +319,7 @@ 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 +#### Practical usage 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. @@ -650,7 +652,7 @@ Let's draw out[^nomnoml] this relationship, where the left arrow connects to the ![](./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: +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) @@ -680,7 +682,7 @@ 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. +If you want, you could implement your own lexer and parser manually, but as a start, it's worthwhile 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. @@ -804,7 +806,7 @@ John said 10 times "2 + 2 = 5" ``` 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. +In certain programming languages, that don't have [string interpolation](https://en.wikipedia.org/wiki/String_interpolation) this is fine, but for the others our regexes have to be a lot more complicated. #### yacc @@ -830,11 +832,10 @@ A yacc file looks very similar to a lex one: however rather than definitions you have settings, and the rules are in a completely different format (because they're grammars). -## II. Virtual machines +#### Using them together -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 +Let's now make our own "proper" front-end. +The lexer will need to return (emit) it's token to the [^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. -- cgit v1.3.1-26-gb76a From 786343ae5bccfd6415e48298bc3b59ae73891d8b Mon Sep 17 00:00:00 2001 From: Syndamia Date: Sat, 15 Apr 2023 10:07:22 +0300 Subject: [blog/seoc] Replaced thick arrow with an arrow that is more readily available on mobile --- src/blog/sane-explanation-of-compilers/part-1.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/part-1.md b/src/blog/sane-explanation-of-compilers/part-1.md index 24c87fd..1682807 100644 --- a/src/blog/sane-explanation-of-compilers/part-1.md +++ b/src/blog/sane-explanation-of-compilers/part-1.md @@ -201,7 +201,7 @@ Additionally, there can be multiple rules with the same name, meaning a rule can 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. +Finally, in future examples, I'll use the 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 @@ -213,13 +213,13 @@ S -> cc we can generate the string `aaaaccbbbb` (remember, our starting point is `S`): ```grammar+ -S 🡆 aSb 🡆 aaSbb 🡆 aaaSbbb 🡆 aaaaSbbbb 🡆 aaaaccbbbb +S ⇒ aSb ⇒ aaSbb ⇒ aaaSbbb ⇒ aaaaSbbbb ⇒ aaaaccbbbb ``` or `accb`: ```grammar+ -S 🡆 aSb 🡆 accb +S ⇒ aSb ⇒ accb ``` where a, b and c are just english characters. @@ -236,7 +236,7 @@ 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 +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". @@ -310,11 +310,11 @@ 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 +E ⇒ E + E ⇒ n + E * E ⇒ n + n * n ``` ```grammar+ -E 🡆 E * E 🡆 E + E * n 🡆 n + n * n +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. -- cgit v1.3.1-26-gb76a From 70a5c36c26987847d2e0952e215943645c6d3452 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Sat, 15 Apr 2023 10:34:12 +0300 Subject: [blog/seoc] Changed number to state in LR explanations --- src/blog/sane-explanation-of-compilers/part-1.md | 89 ++++++++++++------------ 1 file changed, 44 insertions(+), 45 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/part-1.md b/src/blog/sane-explanation-of-compilers/part-1.md index 1682807..1ddaab4 100644 --- a/src/blog/sane-explanation-of-compilers/part-1.md +++ b/src/blog/sane-explanation-of-compilers/part-1.md @@ -456,10 +456,10 @@ It all boils down to using a whole bunch of conditional statements and tracing w 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: + We need to track the current state of the string, because imagine we've just read an "a", it could either be from the left or right handside of "a + a", and that changes what character to expect next. + We're going to track the state with different numbers, defined like this: - |Number|Current expression ends with| + |State (number)|Current expression ends with| |------|---------------| |0 |Nothing; this is the start| |1 |The name `S`; the final number should be this| @@ -471,72 +471,72 @@ It all boils down to using a whole bunch of conditional statements and tracing w |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. + You can think of every state number as the valid, but "unfinished" state of the current string. + For now don't think about the way this table is defined, it'll make sense later. + But you could make a state for literally every valid string composition: "(", "(a", "(F", "(S", .... 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: + Reading a character from the input means appending it to the right of String: ``` String : ( - Number : 0 + State : 0 ``` - We're reading "(", so our string "ends" on a "(" + We've read "(", so our string "ends" on a "(". ``` String : (a - Number : 3 + State : 3 ``` We've read "a", our string "ends" on an "a". ``` String : (a - Number : 4 + State : 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. + Here comes the clever bit, for certain states, we'll stop reading forward and do something else. + If we're on state 4, our string ends on an "a", so we're going to go backwards and replace it with an F, meaning the current state should be 2. ``` String : (F - Number : 2 + State : 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. + Here is another such rule, if our state is 2, our string ends with an "F" and we replace it with an S, now the state is 5. + That's why we have a different state for "(S + F", if we didn't, our state 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 + State : 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. + We have a different state for "(S", because if we didn't, we would've gone to state 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 state 6. ``` String : (S + a - Number : 6 + State : 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. + Now, our string ends with an "a", it's tempting to change our state to 4, but we shouldn't, this would remove our progress so far! + Better yet, this state 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 state to 7. ``` String : (S + F - Number : 7 + State : 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! + And now it's trivial, we read ")", so we go to state 8. + But if we're at state 8, don't continue reading, replace with state 1. + Now that we're at state 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| + |State|If ends on|Change state to|Also do| |------|----------|----------------|-------| |0 |"(" |3 | | |1 | | |Nothing, we matched| @@ -548,20 +548,20 @@ It all boils down to using a whole bunch of conditional statements and tracing w |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". + 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 state 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. +- You're probably wondering why the table works so weird, like why on state 3 we don't directly replace "a" with "S" and change to state 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). + Rather than tracing the current state 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"). + When you read a character and have to go to another state, the state 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 states and do a normal shift from the last state 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): +- Let's look at the same example, done with shift and reduce operations (without me showing the proper table), where pushing and popping items from the stack is done from the right side of the array: ``` String : ( - Number : [0] + State : [0] ``` We've read "(", add 3 on top of the stack aka shift(3). @@ -569,35 +569,35 @@ It all boils down to using a whole bunch of conditional statements and tracing w ``` String : (a - Number : [0, 3, 4] + State : [0, 3, 4] ``` With 4 we'll do a reduction, "a" gets replaced by F, 4 is removed: ``` String : (F - Number : [0, 3] + State : [0, 3] ``` - If last number is 3 and last character is "F", we're doing shift(2). + If last state is 3 and last character is "F", we're doing shift(2). ``` String : (F - Number : [0, 3, 2] + State : [0, 3, 2] ``` Now, we'll be doing a reduction, where F is replaced by S: ``` String : (S - Number : [0, 3] + State : [0, 3] ``` - If last number is 3 and last character is "S", we're dong shift(5). + If last state 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. + This way we avoid doing different things on different states. 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), @@ -612,12 +612,11 @@ It all boils down to using a whole bunch of conditional statements and tracing w 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 + - 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 and the string is valid ##### LR's family -- cgit v1.3.1-26-gb76a From 6594ce7cc47d4d7f286de1d4ce0e82ca1ca05668 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Sat, 15 Apr 2023 10:34:40 +0300 Subject: [blog/seoc] Tokenization is now done entirely with tokens and without characters --- src/blog/sane-explanation-of-compilers/part-1.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/part-1.md b/src/blog/sane-explanation-of-compilers/part-1.md index 1ddaab4..282d315 100644 --- a/src/blog/sane-explanation-of-compilers/part-1.md +++ b/src/blog/sane-explanation-of-compilers/part-1.md @@ -325,9 +325,10 @@ Let's think a bit more about grammars: they're really good at handling structure 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. +As a rough example, we want `1 + (2 * 3)` to be transformed into `NUMBER MATHOP LBRACE NUMBER MATHOP NUMBER RBRACE`, `int var = 13;` into `TYPE NAME ASSIGNMENT NUMBER` and so on, where "TYPE", "NUMBER", "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. +Also we're simplifying our work, since we're trying to figure out the overall structure, it doesn't matter if we're multiplying or summing numbers, it's important that we're doing a mathematical operation on them. +Of course, each token will actually be a pair, containing it's name (NUMBER, TYPE, ...) and it's value, but our grammars will work with the names only and output the actual values at the very end. Usually we identify at least six token types: - identifiers: variable and function names for example -- cgit v1.3.1-26-gb76a From 1345e120c9f8e3bcf2524c8c9ba382f3f92a544c Mon Sep 17 00:00:00 2001 From: Syndamia Date: Mon, 17 Apr 2023 08:42:05 +0300 Subject: [blog/seoc] Crossed out tree-cycle --- .../img/tree-cycle.svg | 290 +++++++++++++++++---- 1 file changed, 237 insertions(+), 53 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/img/tree-cycle.svg b/src/blog/sane-explanation-of-compilers/img/tree-cycle.svg index f679b0e..9a7371c 100644 --- a/src/blog/sane-explanation-of-compilers/img/tree-cycle.svg +++ b/src/blog/sane-explanation-of-compilers/img/tree-cycle.svg @@ -1,56 +1,240 @@ - - #background: #fdf6e3 + + + + + #background: #fdf6e3 [A]->[B] [B]->[C] [C]->[A] - - - - - - - - - - - - - - - - - - - - A - - - - - - - - - - - B - - - - - - - - - - - C - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + A + + + + + + + + + + B + + + + + + + + + + C + + + + + + + + + + + -- cgit v1.3.1-26-gb76a From f53f28c22e58844a90cdf00700cec325cfb7be53 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Mon, 17 Apr 2023 09:24:52 +0300 Subject: [blog/seoc] Finished AST section --- .../img/tree-building-1.svg | 26 +++++++ .../img/tree-building-2.svg | 53 ++++++++++++++ .../img/tree-building-3.svg | 53 ++++++++++++++ .../img/tree-building-ex1.svg | 39 +++++++++++ .../img/tree-building-ex2.svg | 67 ++++++++++++++++++ .../img/tree-building-ex3.svg | 53 ++++++++++++++ .../img/tree-building-ex4.svg | 81 ++++++++++++++++++++++ src/blog/sane-explanation-of-compilers/part-1.md | 61 ++++++++++++++-- 8 files changed, 426 insertions(+), 7 deletions(-) create mode 100644 src/blog/sane-explanation-of-compilers/img/tree-building-1.svg create mode 100644 src/blog/sane-explanation-of-compilers/img/tree-building-2.svg create mode 100644 src/blog/sane-explanation-of-compilers/img/tree-building-3.svg create mode 100644 src/blog/sane-explanation-of-compilers/img/tree-building-ex1.svg create mode 100644 src/blog/sane-explanation-of-compilers/img/tree-building-ex2.svg create mode 100644 src/blog/sane-explanation-of-compilers/img/tree-building-ex3.svg create mode 100644 src/blog/sane-explanation-of-compilers/img/tree-building-ex4.svg (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/img/tree-building-1.svg b/src/blog/sane-explanation-of-compilers/img/tree-building-1.svg new file mode 100644 index 0000000..174f003 --- /dev/null +++ b/src/blog/sane-explanation-of-compilers/img/tree-building-1.svg @@ -0,0 +1,26 @@ + + #background: #fdf6e3 + [2] + + + + + + + + + + + + + + 2 + + + + + + + + + \ No newline at end of file diff --git a/src/blog/sane-explanation-of-compilers/img/tree-building-2.svg b/src/blog/sane-explanation-of-compilers/img/tree-building-2.svg new file mode 100644 index 0000000..48e2636 --- /dev/null +++ b/src/blog/sane-explanation-of-compilers/img/tree-building-2.svg @@ -0,0 +1,53 @@ + + #background: #fdf6e3 + [*]->[2] + [*]->[<abstract>...] + + + + + + + + + + + + + + + + + + * + + + + + + + + + + + 2 + + + + + + + + + + + ... + + + + + + + + + \ No newline at end of file diff --git a/src/blog/sane-explanation-of-compilers/img/tree-building-3.svg b/src/blog/sane-explanation-of-compilers/img/tree-building-3.svg new file mode 100644 index 0000000..ea526df --- /dev/null +++ b/src/blog/sane-explanation-of-compilers/img/tree-building-3.svg @@ -0,0 +1,53 @@ + + #background: #fdf6e3 + [*]->[2] + [*]->[()] + + + + + + + + + + + + + + + + + + * + + + + + + + + + + + 2 + + + + + + + + + + + () + + + + + + + + + \ No newline at end of file diff --git a/src/blog/sane-explanation-of-compilers/img/tree-building-ex1.svg b/src/blog/sane-explanation-of-compilers/img/tree-building-ex1.svg new file mode 100644 index 0000000..d5addd2 --- /dev/null +++ b/src/blog/sane-explanation-of-compilers/img/tree-building-ex1.svg @@ -0,0 +1,39 @@ + + #background: #fdf6e3 + [()]->[<abstract>...] + + + + + + + + + + + + + + + + () + + + + + + + + + + + ... + + + + + + + + + \ No newline at end of file diff --git a/src/blog/sane-explanation-of-compilers/img/tree-building-ex2.svg b/src/blog/sane-explanation-of-compilers/img/tree-building-ex2.svg new file mode 100644 index 0000000..fcf84a1 --- /dev/null +++ b/src/blog/sane-explanation-of-compilers/img/tree-building-ex2.svg @@ -0,0 +1,67 @@ + + #background: #fdf6e3 + [*]->[()] + [*]->[<abstract>....] + [()]->[<abstract>...] + + + + + + + + + + + + + + + + + + + + * + + + + + + + + + + + () + + + + + + + + + + + .... + + + + + + + + + + + ... + + + + + + + + + \ No newline at end of file diff --git a/src/blog/sane-explanation-of-compilers/img/tree-building-ex3.svg b/src/blog/sane-explanation-of-compilers/img/tree-building-ex3.svg new file mode 100644 index 0000000..d15267e --- /dev/null +++ b/src/blog/sane-explanation-of-compilers/img/tree-building-ex3.svg @@ -0,0 +1,53 @@ + + #background: #fdf6e3 + [+]->[1] + [+]->[2] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + + + 2 + + + + + + + + + \ No newline at end of file diff --git a/src/blog/sane-explanation-of-compilers/img/tree-building-ex4.svg b/src/blog/sane-explanation-of-compilers/img/tree-building-ex4.svg new file mode 100644 index 0000000..7642a42 --- /dev/null +++ b/src/blog/sane-explanation-of-compilers/img/tree-building-ex4.svg @@ -0,0 +1,81 @@ + + #background: #fdf6e3 + [+]->[1] + [+]->[*] + [*]->[2] + [*]->[<abstract>...] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + + + * + + + + + + + + + + + 2 + + + + + + + + + + + ... + + + + + + + + + \ No newline at end of file diff --git a/src/blog/sane-explanation-of-compilers/part-1.md b/src/blog/sane-explanation-of-compilers/part-1.md index 282d315..e847bc3 100644 --- a/src/blog/sane-explanation-of-compilers/part-1.md +++ b/src/blog/sane-explanation-of-compilers/part-1.md @@ -598,7 +598,7 @@ It all boils down to using a whole bunch of conditional statements and tracing w 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 states. + This way we avoid doing different things on different states and we don't need to store the whole string, only the last few characters. 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), @@ -670,15 +670,62 @@ 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. +You might ask how we generate the tree, and the answer is simple: on every step we add nodes to the tree, depending on the situation. +Let's look at a familiar example: -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 +```grammar +N -> 1 | 2 | 3 +E -> N | (E) | E + E | E * E +``` + +Let's look at the input string `2 * (1 + 3)`, while abstracting ourselves from any particular algorithm: + +- we read the `2`, that is a number, we add it as a node + + ![](./img/tree-building-1.svg) + +- then we read the `*`, we now know our expression is in the form `E * E`. + If you think about it, up to this point, we've basically been building a tree for the left handside. + + **If** the topmost element in that tree is a brace, + + ![](./img/tree-building-ex1.svg) + + we connect it to the left handside of `*`: + + ![](./img/tree-building-ex2.svg) + + **Otherwise** (when it's `+` or `*` or a number), because of precedence, we'll attach the latest number to the left handside. + However we have to be careful, if something connects to the number, we now need it to connect to the `*`. + For example, let's say we had `1 + 2 * 3`, and we've just read the `*`. + The tree up to this point would look like, + + ![](./img/tree-building-ex3.svg) + + where the latest number we've found was `2`, but the `+` connects to it. + So, we need to make the `2` connect to the left handside of `*`, and make `+` connect to `*` instead of `2` + + ![](./img/tree-building-ex4.svg) + + In our original case, nothing connects to the `2` in `2 * (1 + 3)`, so we can just connect it to the left handside of `*` + + ![](./img/tree-building-2.svg) + + where the three dots singify there isn't anything there (but we expect there to be). + Somewhere we'll store that the next element we find has to be connected to the right handside. + +- now we read `(`, we cannot have it by itself, so we directly decide we're working with `(E)` (in our full algorithm we would need a check for existance of matching brace). + We'll create a `()` node and because of the last step, we'll connect it to the right handside. + + ![](./img/tree-building-3.svg) + + Now, moving forward, we'll be creating a subtree, essentially making a second tree, and after that is done, we'll connect it's topmost element (root) to the `()` node. + +- and so on. +The overall algorithm is to add and change nodes every time you match something with a grammar rule, and the adding and changing is done, depending on the language, the current structure and so on. +When discussing the middle and back-end layers, we'll talk about how to work with a generated AST, but for now your clue is the [visitor pattern](https://en.wikipedia.org/wiki/Visitor_pattern). ### Implementing a front-end -- cgit v1.3.1-26-gb76a From 9d13ee0b6ab191c3394962a0b0edaaa629921085 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Mon, 17 Apr 2023 09:56:25 +0300 Subject: [blog/seoc] Added an appendix --- src/blog/sane-explanation-of-compilers/part-1.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/part-1.md b/src/blog/sane-explanation-of-compilers/part-1.md index e847bc3..3fa79c8 100644 --- a/src/blog/sane-explanation-of-compilers/part-1.md +++ b/src/blog/sane-explanation-of-compilers/part-1.md @@ -20,15 +20,12 @@ 1. [lex](#lex) 2. [yacc](#yacc) 3. [Using them together](#using-them-together) +3. [Appendinx](#appendix) 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. @@ -884,6 +881,14 @@ however rather than definitions you have settings, and the rules are in a comple Let's now make our own "proper" front-end. The lexer will need to return (emit) it's token to the +## Appendix + +Originally I planned to put everything in one blogpost, but writing the front-end (this part) alone took me 2 and a half weeks of (inconsistent, I was suddenly hit with multiple exams and homeworks in uni) writing. +Additionally, while doing research, I found out the course actually skipped over a lot of important topics, which I'll first need to research. +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. + +I want to thank [Dimitar Tagarev](https://github.com/dtagarev) for his review and feedback on drafts of this post. + [^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. -- cgit v1.3.1-26-gb76a From 752b4fb998d8b5e9943f098e23585061dbbaa7dc Mon Sep 17 00:00:00 2001 From: Syndamia Date: Mon, 17 Apr 2023 15:00:27 +0300 Subject: [blog/seoc] Finished yacc section --- src/blog/sane-explanation-of-compilers/part-1.md | 147 ++++++++++++++++++++++- 1 file changed, 141 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/part-1.md b/src/blog/sane-explanation-of-compilers/part-1.md index 3fa79c8..712bebe 100644 --- a/src/blog/sane-explanation-of-compilers/part-1.md +++ b/src/blog/sane-explanation-of-compilers/part-1.md @@ -850,20 +850,20 @@ John said 10 times "2 + 2 = 5" ``` You've probably already noticed that the number inside the strings aren't matched, because the string rule results in a longer match. -In certain programming languages, that don't have [string interpolation](https://en.wikipedia.org/wiki/String_interpolation) this is fine, but for the others our regexes have to be a lot more complicated. +In certain programming languages, that don't have [string interpolation](https://en.wikipedia.org/wiki/String_interpolation) this is fine, but for others our regexes have to be a lot more complicated. #### 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: +A yacc file looks very similarly to a lex one: ```yacc %{ // C code that will be put in the program verbatim %} -/* Settings */ +/* Declarations */ %% @@ -874,12 +874,145 @@ A yacc file looks very similar to a lex one: // C code ``` -however rather than definitions you have settings, and the rules are in a completely different format (because they're grammars). +however rather than definitions you have declarations, and the rules are in a completely different format (because they're grammars). + +Token names are defined in `declarations`, in the format + +```yacc +%token NAME1 NAME2 ... +``` + +You can also define precedence with `%left` and `%right`. +There are also other options you can set, like the start name with `%start`. + +Grammars are in the form + +```yacc +name : TOKEN1 TOKEN2 ... + ; +``` + +where alternation is defined like + +```yacc +name : TOKEN1 + | TOKEN2 + | TOKEN3 + ; +``` + +and it always must end with a `;`. +On each alternation, you can (should) specify a body, which will contain C code to be executed, if this rule is reached + +```yacc +name : TOKEN1 { C code here } + | TOKEN2 + | TOKEN3 { C code here } + ; +``` + +Another difference is that, since the parser needs a list of tokens, you cannot run it by itself, you'll also need to setup a lexer. + +Let's implement a parser for the grammar[^shift-reduce-conflicts]: + +```grammar +N -> 1 | 2 | 3 +S -> N | (S + S) | (S * S) +``` + +First, our tokens, we want to replace all characters with a token. +For 1, 2 and 3, let's use the token name "NUMBER", for "(" and ")", LBRACE and RBRACE accordingly, and since there is no precedence with this grammar, we don't actually care if we have `(S + S)` or `(S * S)`, so we can assign both `+` and `*` to the token MATHOP. +Meaning, our grammar would behave more like this: + +```grammar +N -> 1 | 2 | 3 +M -> + | * +S -> N | (S M S) +``` + +First, we need to make our `lexer.l`, it is going to be very simple: + +```lex +%{ +#include "parser.tab.h" +%} + +%% + + /* Remember, [] is a group, [abcd] behaves like "(a | b | c | d)" and "\" escapes characters */ +[123] { return NUMBER: } +[\+\*] { return MATHOP; } +\( { return LBRACE; } +\) { return RBRACE: } + +%% +``` + +Now, tokens (names) are defined inside grammars, however our lexer needs to emit (return) them. +That's why, when running bison on our `parser.y`, we'll also create a C header file, which contains those names already defined, so they're accessible inside `lexer.l`. +This file is in the format `FILENAME.tab.h`, where `FILENAME.y` is our source yacc file. + +Second, we need to make our `parser.y`: + +```yacc +%{ +#include "stdio.h" +int yylex(); +int yyerror(char *s); +%} + +%token NUMBER MATHOP LBRACE RBRACE + +%% + +expr : NUMBER + | LBRACE expr MATHOP expr RBRACE + ; + +%% + +int yyerror(char *s) { + printf("Error: %s\n", s); + return 0; +} + +int main() { + yyparse(); +} +``` + +A quirk with GNU Bison is that you need to declare the function `yylex` and `yyerror` beforehand, manually define `yyerror` and run `yyparse` in the main function. +These are precisely the first 5 and the last 8 lines of code, but for now you don't need to think about them. + +Let's get to compiling. +First, the lexer: + +```bash +flex lexer.l +``` + +then our parser: + +```bash +bison -d parser.y +``` + +where the `-d` option means we'll also output the `parser.tab.h` header file. +Finally, we compile both of them together into one executable: + +```bash +gcc lex.yy.c parse.tab.c -lfl +``` + +Now when you run `./a.out`, if you enter a valid string, you'll see a blank line, but if it isn't valid, you'll get "Error: syntax error". #### Using them together -Let's now make our own "proper" front-end. -The lexer will need to return (emit) it's token to the +The way we created that lexer and parser worked, but it wasn't very useful. +Ideally, we want the lexer to also return the exact value the regex matched and we need to be creating our AST in the parser. + +Regarding the first problem, we've already returned a value, we could return some sort of structure, but that wouldn't work with the way our code is generated. +What we can do is set a variable ## Appendix @@ -902,3 +1035,5 @@ I want to thank [Dimitar Tagarev](https://github.com/dtagarev) for his review an [^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) + +[^shift-reduce-conflicts]: You might be tempted to try and make one for the grammar inside the [AST](#abstract-syntax-tree) section, but that one is ever so slightly problematic, because it's ambiguous (I showed why at the end of [Implementational difficulties with grammars](#implementational-difficulties-with-grammars)). Bison [can handle ambiguity by always choosing to shift](https://www.gnu.org/software/bison/manual/html_node/Shift_002fReduce.html), but I didn't want to complicate things. -- cgit v1.3.1-26-gb76a From db518ce607d467e2ec89531b8ae5ba73a81e6f57 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Mon, 17 Apr 2023 16:29:53 +0300 Subject: [blog/seoc] Added information in together section --- src/blog/sane-explanation-of-compilers/part-1.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/part-1.md b/src/blog/sane-explanation-of-compilers/part-1.md index 712bebe..e949e39 100644 --- a/src/blog/sane-explanation-of-compilers/part-1.md +++ b/src/blog/sane-explanation-of-compilers/part-1.md @@ -1011,8 +1011,19 @@ Now when you run `./a.out`, if you enter a valid string, you'll see a blank line The way we created that lexer and parser worked, but it wasn't very useful. Ideally, we want the lexer to also return the exact value the regex matched and we need to be creating our AST in the parser. -Regarding the first problem, we've already returned a value, we could return some sort of structure, but that wouldn't work with the way our code is generated. -What we can do is set a variable +Regarding the first problem, we've already returned a value, we could return some sort of `struct`, but that wouldn't work with the way our code is generated. +Since everything is compiled into one program, we could use a global variable, which we set in the lexer and use in the parser code. +That variable is [already defined](https://www.gnu.org/software/bison/manual/html_node/Token-Values.html) and is called `yylval`. + +As with everything else, we define it's properties inside our grammar (yacc/bison) file. +By default it's type is `int` (in Bison), but usually you would want it to be a [union](https://en.wikipedia.org/wiki/Union_type#C/C++). +For now let's simplify our lives and make it a union of int and char[^yylval-type]. + +Second, we need to make a tree. +I'll not go into details, but we'll use a normal C `struct`ure for a node, and every node has it's value (a character) and two pointers, one to the left and one to the right. +After we've matched a string, I'll print the tree in a nice to view format. + +All in all, we'll have: ## Appendix -- cgit v1.3.1-26-gb76a From a919c5bb04ac0ab55a78b66fa76a0eccbadb142e Mon Sep 17 00:00:00 2001 From: Syndamia Date: Tue, 18 Apr 2023 16:41:12 +0300 Subject: [blog/seoc] Finished lex and yacc sections --- src/blog/sane-explanation-of-compilers/part-1.md | 369 ++++++++++++++++++++++- 1 file changed, 353 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/part-1.md b/src/blog/sane-explanation-of-compilers/part-1.md index e949e39..da1b718 100644 --- a/src/blog/sane-explanation-of-compilers/part-1.md +++ b/src/blog/sane-explanation-of-compilers/part-1.md @@ -780,13 +780,34 @@ The syntax `[0-9]` is the same as `(0 | 1 | ... | 9)`, it works for any letters 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: +If this file is located in `lexer.l`, we can transform it into a C file with: ```bash -flex lexer.l && gcc lex.yy.c -lfl +flex lexer.l ``` -Of course, you can use your lex implementation or C compiler of choice. +Usually the result file is always named `lex.yy.c`. +Afterwards, we can compile the C code into a working compiler: + +```bash +gcc lex.yy.c -lfl +``` + +Without the `-lfl` flag, we would get a linking error, because of the `main` and `yywrap` function, which are required but aren't defined in our generated code. +There are three ways to fix this problem: + +1. The one I've opted for, use the `-lfl` flag to compile our C code with a (flex) library which provides both functions. + Usually the lexer isn't meant to be ran by itself, so for the current time being, `-lfl` is the best option, the other two are fine when we get to `yacc`. +2. Put `%option noyywrap` in the definitions section, which means the lexer will only read one file. +3. Define it ourselves. + It should return 0 if our lexer should continue with the next given file, after finishing with the current one, or 1 if it should stop execution. + The function could be written in either "C code" section, but I personally prefer the last one. + + ```lex + int yywrap() { return 0; } + ``` + +Of course, you can use your lex implementation or C compiler of choice, and there this might not be a problem. 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 @@ -1006,24 +1027,338 @@ gcc lex.yy.c parse.tab.c -lfl Now when you run `./a.out`, if you enter a valid string, you'll see a blank line, but if it isn't valid, you'll get "Error: syntax error". -#### Using them together +#### Making a proper front-end + +The way we created that lexer and parser worked, but it wasn't very useful and has multiple issues we have to address: + +1. When entering a string that isn't matched at all, it gets printed back like nothing happend. + For example, if we enter the letter `a` or any string which doesn't have `(`, `)`, `1`, `2`, `3`, `+` or `-` characters, it will just get printed back. + Ideally, we want to raise an error, so we're going to add one rule which catches any (non-special) character and throws an error with the built-in `yy_fatal_error`: + + ```lex + . { yy_fatal_error("Bad character"); } + ``` + + This rule must be the last rule, since we don't want it to be matched, if there is another rule that matches. + Remember that lex matches the longest possible string and if there are multiple rules which match the same amount of characters, only the first one is matched. + +2. For every token name, returned by the lexer, we also need to have it's actual value. + We could make a `struct`, which holds both a token name and it's value, but there is another ["built-in" mechanism](https://www.gnu.org/software/bison/manual/html_node/Token-Values.html) for that in yacc/Bison. + We would set the global variable `yylval` to the token value, and it will be changed for every token. + + By default it's type is `int` (in Bison), but usually you would want it to be a [union](https://en.wikipedia.org/wiki/Union_type#C/C++). + Let's make it a union of int and char, though the first part is kind of useless, since we're only working with single digit numbers. + + ```yacc + %union { + int num; + char chr; + } + ``` + + Now, inside our lexer, rules would look like: + + ```yacc + RULE1 { yylval.num = 129; return TOKEN; } + RULE2 { yylval.chr = 'a'; return TOKEN; } + ``` + + Inside C blocks for grammar rules we can reference the token values with `$i`, where `i` is the i'th "token" in the expression. + For example, in this rule, `$1` would be `(`, `$3` would be value of token `B` and `$5` would be the value of the rule name: + + ```yacc + rule : ( A B ) rule + ; + ``` + + You can set rule "return" values by setting the variable `$$`: + + ```yacc + rule : LBRACE rule RBRACE { $$ = 10; } + ``` + + The way you set it's type is discussed later. + However, `$i` isn't of type union, we cannot do something like `$i.num`, it is the precise value that was set for the token. + Therefore, we also need to define which value from the union every token will set, which is done by adding `` before every defined token (and `PROPERTY` is a property name inside the union): + + ```yacc + %token NUMBER MATHOP LBRACE RBRACE + ``` + +3. If we enter one valid math expression, we'll get no error, but when we enter another, we'll get a "syntax error"[^better-bison-errors]. + That is because we try to match only one expression, after it is matched our parser is waiting for an end of file character. + Let's make it so we would try to match an expression on every line: + + ```yacc + start : expr + | expr start + ; + ``` + + A rule like `expr : expr expr` will produce shift/reduce conflicts. + Another option is duplicating our `expr` rules and adding `expr` in the beginning or end, but that is cumbersome if we want to make changes. + +4. We're getting input from the user, but our source text (code) will be in a file. + First, our `main` function need to take program parameters: + + ```yacc + int main(int argc, char* argv[]) + ``` + + Then we need to take the first argument, and open a file. + Additionally, we have to check if the file was successfully opened, and print an error and stop execution if so: + + ```yacc + FILE* input = fopen(argv[1], "r"); + if (input == NULL) { + yyerror("cannot read input file!"); + return 1; + } + ``` + + Now for the clever bit, actual parsing in generated code is done on the file `yyin`, which by default is the standard user input. + To read a file, all we need to do is change the value of that variable. + Also, that variable is defined externally, so first we need to add to (the top) C section: + + ```yacc + extern FILE* yyin; + ``` + + and then put in our `main`: + + ```yacc + yyin = input; + ``` + + On \*NIX systems (Linux, MacOS, OpenBSD, ...) you can still use user input by passing the file `/dev/stdin`. + If you want your front-end to support multiple files, you would just need to wrap the whole body of main in a `for` loop, iterating over the whole `argv` array (remember that `argc` is the length of the array). + +5. We need to construct an AST. + Since the exact tree structure depends on your needs, I'll make the simplest possible tree in pure C that works for this grammar. + I won't explain this in much detail, since it is just normal C code. + + ```c + #include + #include + + typedef struct node { + char val; + struct node *left; + struct node *right; + } node; + + node* newNode(char val, node *left, node *right) { + node* out = malloc(sizeof(node)); + out->val = val; + out->left = left; + out->right = right; + return out; + } + + void printTree(node *n, int level) { + if (n == NULL) return; + // %*s will add level amounts of spaces (but with the "" string) + printf("%*s|-%c\n", level, "", n->val); + printTree(n->left, level + 1); + printTree(n->right, level + 1); + } + + void freeNode(node *n) { + if (n == NULL) return; + freeNode(n->left); + freeNode(n->right); + free(n); + } + ``` + + However, all of this is quite a lot, and it would take a lot of space in `parser.y`, so let's separate it into `tree.c` and add a header file `tree.h` which contains the definitions: + + ```c + #include + #include + + typedef struct node { + char val; + struct node *left; + struct node *right; + } node; + + node* newNode(char val, node *left, node *right); + void printTree(node *n, int level); + void freeNode(node *n); + ``` + + Of course, we should add some ifndef-def precompiler code, but that isn't relevant for now. + + The way we're going to use trees in our grammar is as follows: for the `NUMBER` expression of `expr`, we'll create a node with the (char) value of the number and "return" it. + For the expression of `expr` we'll "return" a node with the value of the math opeartor and left and right will be the returned values. + Inside start, after we've parsed an `expr`, we'll print out the "returned" tree and free it's memory. + + I'm putting returned in quotes, because (as mentioned), we'll just be setting the value of `$$`. + `$$`'s type is set with the `%type` option, which works exactly like `%token`, but with grammar rule names. + However, this means that `node` must be available in `%union`, which is unfortunate but isn't a problem, we'll just add it. + + Now, finally, it's time to include our `tree.h` in `parser.y`, but we'll also need to include it in `lexer.l`. + The reason is that the `%union` appears in `parser.tab.h`, which means our node structure is referenced in `parser.tab.h`, but `tree.h` isn't included there. + +All in all, we'll have 4 source files for our simple front-end: + +- `lexer.l` + + ```lex + %{ + #include "tree.h" + #include "parser.tab.h" + %} + + %option noyywrap + + %% + + [123] { yylval.num = atoi(yytext); return NUMBER; } + [\+\*] { yylval.chr = yytext[0] ; return MATHOP; } + \( { yylval.chr = '(' ; return LBRACE; } + \) { yylval.chr = ')' ; return RBRACE; } + \ { } /* Don't do anything on spaces */ + + . { yy_fatal_error("Bad character"); } + + %% + ``` + +- `parser.y` + + ```yacc + %{ + #include + #include "tree.h" + + extern FILE* yyin; + + int yylex(); + int yyerror(const char *s); + %} + + %union { + int num; + char chr; + node *n; + } + %token NUMBER MATHOP LBRACE RBRACE + %type expr + + %% + + start : expr { printTree($1, 0); freeNode($1); } + | expr start { printTree($1, 0); freeNode($1); } + ; + + expr : NUMBER { $$ = newNode($1 + '0', NULL, NULL); } + | LBRACE expr MATHOP expr RBRACE { $$ = newNode($3, $2, $4); } + ; + + %% + + int yyerror(const char *s) { + printf("Error: %s\n", s); + return 0; + } + + int main(int argc, char* argv[]) { + FILE* input = fopen(argv[1], "r"); + if (input == NULL) { + yyerror("reading input file!"); + return 1; + } + + yyin = input; + yyparse(); + } + ``` + +- `tree.h` + + ```c + #ifndef TREE + #define TREE + + #include + #include + + typedef struct node { + char val; + struct node *left; + struct node *right; + } node; + + node* newNode(char val, node *left, node *right); + void printTree(node *n, int level); + void freeNode(node *n); + + #endif + ``` -The way we created that lexer and parser worked, but it wasn't very useful. -Ideally, we want the lexer to also return the exact value the regex matched and we need to be creating our AST in the parser. +- `tree.c` -Regarding the first problem, we've already returned a value, we could return some sort of `struct`, but that wouldn't work with the way our code is generated. -Since everything is compiled into one program, we could use a global variable, which we set in the lexer and use in the parser code. -That variable is [already defined](https://www.gnu.org/software/bison/manual/html_node/Token-Values.html) and is called `yylval`. + ```c + #include "tree.h" -As with everything else, we define it's properties inside our grammar (yacc/bison) file. -By default it's type is `int` (in Bison), but usually you would want it to be a [union](https://en.wikipedia.org/wiki/Union_type#C/C++). -For now let's simplify our lives and make it a union of int and char[^yylval-type]. + node* newNode(char val, node *left, node *right) { + node* out = malloc(sizeof(node)); + out->val = val; + out->left = left; + out->right = right; + return out; + } + + void printTree(node *n, int level) { + if (n == NULL) return; + printf("%*s|-%c\n", level, "", n->val); + printTree(n->left, level + 1); + printTree(n->right, level + 1); + } + + void freeNode(node *n) { + if (n == NULL) return; + freeNode(n->left); + freeNode(n->right); + free(n); + } + ``` -Second, we need to make a tree. -I'll not go into details, but we'll use a normal C `struct`ure for a node, and every node has it's value (a character) and two pointers, one to the left and one to the right. -After we've matched a string, I'll print the tree in a nice to view format. +We compile everything: + +```bash +flex lexer.l && bison parser.y && gcc lex.yy.c parse.tab.c tree.c +``` -All in all, we'll have: +Now, let's create the file `test.txt`: + +``` +((1+1) * ((3+3) * 2)) +``` + +and run our front-end on it: + +```bash +./a.out test.txt +``` + +Our output will be: + +``` +|-* + |-+ + |-1 + |-1 + |-* + |-+ + |-3 + |-3 + |-2 +``` + +Perfect, we have a good looking tree! ## Appendix @@ -1048,3 +1383,5 @@ I want to thank [Dimitar Tagarev](https://github.com/dtagarev) for his review an [^nomnoml]: The graphics are made with [nomnoml](https://nomnoml.com/) by [Daniel Kallin](https://github.com/skanaar) [^shift-reduce-conflicts]: You might be tempted to try and make one for the grammar inside the [AST](#abstract-syntax-tree) section, but that one is ever so slightly problematic, because it's ambiguous (I showed why at the end of [Implementational difficulties with grammars](#implementational-difficulties-with-grammars)). Bison [can handle ambiguity by always choosing to shift](https://www.gnu.org/software/bison/manual/html_node/Shift_002fReduce.html), but I didn't want to complicate things. + +[^better-yacc-errors]: You can add `%define parse.error verbose` inside definitions of your yacc file, and it will tell you what character was expected and what character was read. -- cgit v1.3.1-26-gb76a From b2377649aded6e17bc9c5aff60eafc5f963aad0d Mon Sep 17 00:00:00 2001 From: Syndamia Date: Tue, 18 Apr 2023 17:21:59 +0300 Subject: [blog/seoc] Rewording --- src/blog/sane-explanation-of-compilers/part-1.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/part-1.md b/src/blog/sane-explanation-of-compilers/part-1.md index da1b718..6dd80af 100644 --- a/src/blog/sane-explanation-of-compilers/part-1.md +++ b/src/blog/sane-explanation-of-compilers/part-1.md @@ -19,7 +19,7 @@ 3. [Implementing a front-end](#implementing-a-front-end) 1. [lex](#lex) 2. [yacc](#yacc) - 3. [Using them together](#using-them-together) + 3. [Doing it properly](#doing-it-properly) 3. [Appendinx](#appendix) Recently I signed up for a small university course about compilers. @@ -1027,7 +1027,7 @@ gcc lex.yy.c parse.tab.c -lfl Now when you run `./a.out`, if you enter a valid string, you'll see a blank line, but if it isn't valid, you'll get "Error: syntax error". -#### Making a proper front-end +#### Doing it properly The way we created that lexer and parser worked, but it wasn't very useful and has multiple issues we have to address: @@ -1099,7 +1099,7 @@ The way we created that lexer and parser worked, but it wasn't very useful and h Another option is duplicating our `expr` rules and adding `expr` in the beginning or end, but that is cumbersome if we want to make changes. 4. We're getting input from the user, but our source text (code) will be in a file. - First, our `main` function need to take program parameters: + First, our `main` function needs to take program parameters: ```yacc int main(int argc, char* argv[]) @@ -1366,7 +1366,7 @@ Originally I planned to put everything in one blogpost, but writing the front-en Additionally, while doing research, I found out the course actually skipped over a lot of important topics, which I'll first need to research. 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. -I want to thank [Dimitar Tagarev](https://github.com/dtagarev) for his review and feedback on drafts of this post. +Many thanks to [Dimitar Tagarev](https://github.com/dtagarev) for his help with reviewing this post. [^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. @@ -1384,4 +1384,4 @@ I want to thank [Dimitar Tagarev](https://github.com/dtagarev) for his review an [^shift-reduce-conflicts]: You might be tempted to try and make one for the grammar inside the [AST](#abstract-syntax-tree) section, but that one is ever so slightly problematic, because it's ambiguous (I showed why at the end of [Implementational difficulties with grammars](#implementational-difficulties-with-grammars)). Bison [can handle ambiguity by always choosing to shift](https://www.gnu.org/software/bison/manual/html_node/Shift_002fReduce.html), but I didn't want to complicate things. -[^better-yacc-errors]: You can add `%define parse.error verbose` inside definitions of your yacc file, and it will tell you what character was expected and what character was read. +[^better-bison-errors]: You can add `%define parse.error verbose` inside definitions of your yacc file, and it will tell you what character was expected and what character was read. -- cgit v1.3.1-26-gb76a From 8edab5edc351724fa05c9cce7e64e74197e2a41d Mon Sep 17 00:00:00 2001 From: Syndamia Date: Tue, 18 Apr 2023 17:26:41 +0300 Subject: [blog/seoc] Fixed typos --- src/blog/sane-explanation-of-compilers/part-1.md | 40 ++++++++++++------------ 1 file changed, 20 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/blog/sane-explanation-of-compilers/part-1.md b/src/blog/sane-explanation-of-compilers/part-1.md index 6dd80af..fb6da4c 100644 --- a/src/blog/sane-explanation-of-compilers/part-1.md +++ b/src/blog/sane-explanation-of-compilers/part-1.md @@ -24,7 +24,7 @@ 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. +My goal is to try and fill that void, explaining everything in a detailed way that is understandable for beginners. ## Preface @@ -33,7 +33,7 @@ However, writing code only with numbers is tedious, error-prone and simple stuff 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. +The trade-off 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 @@ -59,9 +59,9 @@ could be interpreted either as a: 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). +In natural languages, you could construct a sentence which follows all grammatical rules, but is absolute nonsense, 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. +The problem of semantics is extremely difficult, however in our case we only care about syntax. And this is where math comes into play. ### Math @@ -219,7 +219,7 @@ or `accb`: S ⇒ aSb ⇒ accb ``` -where a, b and c are just english characters. +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. @@ -230,7 +230,7 @@ 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`: +which will successfully 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 @@ -319,7 +319,7 @@ How exactly we deal with these problems comes later, for now the takeaway is tha #### Practical usage 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. +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 laid 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 MATHOP LBRACE NUMBER MATHOP NUMBER RBRACE`, `int var = 13;` into `TYPE NAME ASSIGNMENT NUMBER` and so on, where "TYPE", "NUMBER", "NAME", ... are tokens. @@ -335,10 +335,10 @@ Usually we identify at least six token types: - 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. +As you might've noticed, here we can use regular expressions, grouping consecutive 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 compiler front-end, the part that implements 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 @@ -351,7 +351,7 @@ Generally we categorize them into: 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 +- left-most derivation algorithms, 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. @@ -400,7 +400,7 @@ We check the first k character of all expressions, and if anyone of them is a na Production: (S + F) ``` - Now the first symbol in our production is also `(`, so we incremenet the symbols we're looking/peeking at + Now the first symbol in our production is also `(`, so we increment the symbols we're looking/peeking at ``` I v @@ -530,7 +530,7 @@ It all boils down to using a whole bunch of conditional statements and tracing w And now it's trivial, we read ")", so we go to state 8. But if we're at state 8, don't continue reading, replace with state 1. - Now that we're at state 1, if we read any character (including end of string), we'll say the string upto now matches and we're done! + Now that we're at state 1, if we read any character (including end of string), we'll say the string up to now matches and we're done! It's also helpful to put what we do in different situations in another table: @@ -619,12 +619,12 @@ It all boils down to using a whole bunch of conditional statements and tracing w ##### 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. +This subject is a really big can of beans, which I'm not knowledgeable 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 +- the SLR and LALR, which use significantly 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. @@ -642,7 +642,7 @@ If you want to learn more, I would highly suggest: #### 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. +It definitely 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: @@ -708,7 +708,7 @@ Let's look at the input string `2 * (1 + 3)`, while abstracting ourselves from a ![](./img/tree-building-2.svg) - where the three dots singify there isn't anything there (but we expect there to be). + where the three dots signify there isn't anything there (but we expect there to be). Somewhere we'll store that the next element we find has to be connected to the right handside. - now we read `(`, we cannot have it by itself, so we directly decide we're working with `(E)` (in our full algorithm we would need a check for existance of matching brace). @@ -734,7 +734,7 @@ lex is a lexer generator and yacc is a LALR parser generator, both of which gene #### 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). +Lex is the original program, from 1975, in the modern day it's successor/implementation is the open-source [flex](https://github.com/westes/flex). A lex source file is divided into three parts: @@ -1031,7 +1031,7 @@ Now when you run `./a.out`, if you enter a valid string, you'll see a blank line The way we created that lexer and parser worked, but it wasn't very useful and has multiple issues we have to address: -1. When entering a string that isn't matched at all, it gets printed back like nothing happend. +1. When entering a string that isn't matched at all, it gets printed back like nothing happened. For example, if we enter the letter `a` or any string which doesn't have `(`, `)`, `1`, `2`, `3`, `+` or `-` characters, it will just get printed back. Ideally, we want to raise an error, so we're going to add one rule which catches any (non-special) character and throws an error with the built-in `yy_fatal_error`: @@ -1191,7 +1191,7 @@ The way we created that lexer and parser worked, but it wasn't very useful and h Of course, we should add some ifndef-def precompiler code, but that isn't relevant for now. The way we're going to use trees in our grammar is as follows: for the `NUMBER` expression of `expr`, we'll create a node with the (char) value of the number and "return" it. - For the expression of `expr` we'll "return" a node with the value of the math opeartor and left and right will be the returned values. + For the expression of `expr` we'll "return" a node with the value of the math operator and left and right will be the returned values. Inside start, after we've parsed an `expr`, we'll print out the "returned" tree and free it's memory. I'm putting returned in quotes, because (as mentioned), we'll just be setting the value of `$$`. @@ -1362,7 +1362,7 @@ Perfect, we have a good looking tree! ## Appendix -Originally I planned to put everything in one blogpost, but writing the front-end (this part) alone took me 2 and a half weeks of (inconsistent, I was suddenly hit with multiple exams and homeworks in uni) writing. +Originally I planned to put everything in one blog post, but writing the front-end (this part) alone took me 2 and a half weeks of (inconsistent, I was suddenly hit with multiple exams and homeworks in uni) writing. Additionally, while doing research, I found out the course actually skipped over a lot of important topics, which I'll first need to research. 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. -- cgit v1.3.1-26-gb76a