diff options
33 files changed, 3897 insertions, 0 deletions
diff --git a/website/content/page/about.md b/website/content/page/about.md new file mode 100644 index 0000000..af0b6f5 --- /dev/null +++ b/website/content/page/about.md @@ -0,0 +1,10 @@ +--- +title: "About" +date: 2018-08-02T17:38:31+03:00 +draft: false +--- + +# About this website + +This is the website of a course on implementing programming languages. + diff --git a/website/content/post/2018/midterm.md b/website/content/post/2018/midterm.md new file mode 100644 index 0000000..f29a375 --- /dev/null +++ b/website/content/post/2018/midterm.md @@ -0,0 +1,16 @@ +--- +title: "Midterm Test 2018 edition" +date: 2018-12-08T19:01:49+02:00 +edition: 2018 +expiryDate: 2020-09-30 +draft: false +--- +# + +The midterm test will be on 13th of December, 2019 in hall 325, from 19:00 till +20:30. + +- It will cover everything up to representing values in the VM, including that. +- The test will account for 50% of your final marks. The project will bring in + another 50% and all the homeworks are a bonus. + diff --git a/website/content/post/2018/midterm_results.md b/website/content/post/2018/midterm_results.md new file mode 100644 index 0000000..1d78e8e --- /dev/null +++ b/website/content/post/2018/midterm_results.md @@ -0,0 +1,11 @@ +--- +title: "Midterm Test Results - 2018 edition" +date: 2019-01-08T19:01:49+02:00 +edition: 2018 +expiryDate: 2020-09-30 +draft: false +--- + +<!--more--> + +[Results](https://docs.google.com/spreadsheets/d/1xD-cR76s-R24ME73okHY7S3rEvohyNjhIw5l2BtIfUg/) diff --git a/website/content/post/2018/project_presentation.md b/website/content/post/2018/project_presentation.md new file mode 100644 index 0000000..d8b4c94 --- /dev/null +++ b/website/content/post/2018/project_presentation.md @@ -0,0 +1,10 @@ +--- +title: "Project Presentations - 2018 edition" +date: 2019-01-25T19:01:49+02:00 +edition: 2018 +expiryDate: 2020-09-30 +draft: false +--- + +Projects will be presented on 9th of February, 2019 from 11:00 till 15:00 at hall 501. + diff --git a/website/content/post/2018/projects.md b/website/content/post/2018/projects.md new file mode 100644 index 0000000..5499cde --- /dev/null +++ b/website/content/post/2018/projects.md @@ -0,0 +1,42 @@ +--- +title: "Projects - 2018 edition" +date: 2019-01-09T19:01:49+02:00 +edition: 2018 +expiryDate: 2020-09-30 +draft: false +--- + +Projects will be presented on 9th of February, 2019 at 11:00 at hall 501. + +<!--more--> + +## Projects + +### Transpiler + +Create a transpliler for any pair of the following languages: + +- Lua +- JavaScript +- Python + +### Static Analyzer + +Create a static analyzer for a language of your choice that allows adding custom +checks and has built-in checks for: + +- using undefined variables +- defining a variable that is not used +- calling a function with the wrong number of arguments + +### Code Refactoring Tool + +Create a tool that answers questions like *Where is X defined?*, *Where is X +used?* and can rename arbitrary identifier in a given program. + +### Define your own + +Email us with your own idea for a project. If it is relevant and comparable in +scope it just might get accepted :) + + diff --git a/website/content/post/2018/september.md b/website/content/post/2018/september.md new file mode 100644 index 0000000..97b5d60 --- /dev/null +++ b/website/content/post/2018/september.md @@ -0,0 +1,12 @@ +--- +title: "September Session Exam 2018 edition" +date: 2019-08-22T19:01:49+02:00 +edition: 2018 +expiryDate: 2020-09-30 +draft: false +--- + +The September exam will be on 29th of August, 2019 from 18:00. Hall - TBD. + +The exam is doing one of the project by choice. + diff --git a/website/content/post/contents.md b/website/content/post/contents.md new file mode 100644 index 0000000..6715f96 --- /dev/null +++ b/website/content/post/contents.md @@ -0,0 +1,74 @@ +--- +title: "Course Contents" +date: 2020-10-02T17:45:53+03:00 +draft: false +featured: true + +--- + +Table of contents for the course. + +<!--more--> + +## Contents + +0. Course introduction - [slides]({{< ref "/slides/00_intro" >}}), + [doc]({{< ref "/intro" >}}) + +0. Introduction - [slides]({{< ref "/slides/01_dragons" >}}), + [doc]({{< ref "/dragons" >}}) + +0. Lexical analysis - [slides]({{< ref "/slides/02_lexical_analysis" >}}), + [doc]({{< ref "/lexer" >}}) + +0. Parsing - [slides]({{< ref "/slides/03_parsing" >}}), + [doc]({{< ref "/parser" >}}) + +0. Parser generators - [slides]({{< ref "/slides/04_parser_generators" >}}), + [doc]({{< ref "/parser_generators" >}}) + + +0. Intro to virtual machines - [slides]({{< ref "/slides/05_vm_intro" >}}), + [doc]({{< ref "/vm_intro" >}}) + +0. Values in VMs - [slides]({{< ref "/slides/06_vm_values" >}}), + [doc]({{< ref "/vm_values" >}}) + +0. Objects in VMs - [slides]({{< ref "/slides/08_vm_objects" >}}), + [doc]({{< ref "/vm_objects" >}}) + +0. Garbage Collection Theory + + 0. [Theory](https://www.slideshare.net/eelcovisser/garbage-collection-69688448) + 0. [Barriers](https://www.cs.kent.ac.uk/pubs/2010/3011/content.pdf) + 0. [Lua GC](http://www.inf.puc-rio.br/~roberto/talks/gc-lua.pdf) + 0. [V8 GC](http://jayconrod.com/posts/55/a-tour-of-v8-garbage-collection) + 0. [Generational GC](https://www.ps.uni-saarland.de/courses/gc-ws01/slides/generational_gc.pdf) + 0. [Java Z GC](http://cr.openjdk.java.net/~pliden/slides/ZGC-FOSDEM-2018.pdf) + 0. [LuaJIT GC](http://wiki.luajit.org/New-Garbage-Collector) + +0. Garbage Collection in Spasm - [slides]({{< ref "/slides/10_vm_gc" >}}), + [doc]({{< ref "/gc" >}}) + +0. Just-In-Time Compilation - [slides]({{< ref "/slides/11_jit" >}}), + [doc]({{< ref "/jit" >}}) + +## Timeline + + +| Week | Date | Topic | +|------|------------|--------| +| 1 | 06.10.2020 | Intro | +| 2 | 13.10.2020 | Lexers | +| 3 | 20.10.2020 | Parser | +| 4 | 27.10.2020 | Parser | +| 5 | 03.11.2020 | AST | +| 6 | 10.11.2020 | Bytecode | +| 7 | 17.11.2020 | Bytecode | +| 8 | 24.11.2020 | VM | +| 9 | 01.12.2020 | GC | +| 10 | 15.12.2020 | JIT | +| 11 | 05.01.2021 | JIT | +| 12 | 12.01.2021 | AOT | +| 13 | 19.01.2021 | V8 | + diff --git a/website/content/post/dragons.md b/website/content/post/dragons.md new file mode 100644 index 0000000..937885b --- /dev/null +++ b/website/content/post/dragons.md @@ -0,0 +1,15 @@ +--- +title: "Programming Languages, Compilers, Interpreters" +date: 2020-10-05 +draft: false +--- + +Overview of compiler and interpreter architecture. + +<!--more--> + +[Slideshow]({{< ref "/slides/01_dragons" >}}) + +--- + +{{% readpost file="/slides/01_dragons/_index.md" markdown=true %}} diff --git a/website/content/post/facebook.md b/website/content/post/facebook.md new file mode 100644 index 0000000..f41b80e --- /dev/null +++ b/website/content/post/facebook.md @@ -0,0 +1,12 @@ +--- +title: "Facebook Group" +date: 2020-10-04 +draft: false +featured: true + +--- + +The course has a Facebook group - [Реализация на Езици за +Програмиране](https://facebook.com/groups/324327268145823) + + diff --git a/website/content/post/gc.md b/website/content/post/gc.md new file mode 100644 index 0000000..73b950e --- /dev/null +++ b/website/content/post/gc.md @@ -0,0 +1,18 @@ +--- +title: "Garbage Collection" +date: 2020-11-23 +draft: false +--- + +Garbage collection in theory and practice. + + +This lecture will be entirely online - see the [Facebook group]({{< ref "/facebook" >}}) + +<!--more--> + +[Slideshow]({{< ref "/slides/10_vm_gc" >}}) + +--- + +{{% readpost file="/slides/10_vm_gc/_index.md" markdown=true %}} diff --git a/website/content/post/homeworks.md b/website/content/post/homeworks.md new file mode 100644 index 0000000..18627e7 --- /dev/null +++ b/website/content/post/homeworks.md @@ -0,0 +1,13 @@ +--- +title: "Homeworks" +date: 2018-11-17T19:01:49+02:00 +draft: false +expiryDate: 2020-09-30 + +--- +# Virtual Machine and JSImpl related homeworks + +The tasks that can be used as homeworks are added as +[issues](https://github.com/SofiaCPP/IPL/issues). Their status can be monitored +on the [projects page](https://github.com/SofiaCPP/IPL/projects) as well. + diff --git a/website/content/post/intro.md b/website/content/post/intro.md new file mode 100644 index 0000000..06c5fe6 --- /dev/null +++ b/website/content/post/intro.md @@ -0,0 +1,15 @@ +--- +title: "Introduction to IPL course" +date: 2020-10-04 +draft: false +--- + +Introduction to the Implementation of Programming Languages course + +<!--more--> + +[Slideshow]({{< ref "/slides/00_intro" >}}) + +--- + +{{% readpost file="/slides/00_intro/_index.md" markdown=true %}} diff --git a/website/content/post/jit.md b/website/content/post/jit.md new file mode 100644 index 0000000..f1d3aab --- /dev/null +++ b/website/content/post/jit.md @@ -0,0 +1,18 @@ +--- +title: "Just-In-Time Compilation" +date: 2020-12-13 +draft: false +--- + +Just-In-Time Compilation in theory and practice. + + +This lecture will be entirely online - see the [Facebook group]({{< ref "/facebook" >}}) + +<!--more--> + +[Slideshow]({{< ref "/slides/11_jit" >}}) + +--- + +{{% readpost file="/slides/11_jit/_index.md" markdown=true %}} diff --git a/website/content/post/lexer.md b/website/content/post/lexer.md new file mode 100644 index 0000000..b32d0ee --- /dev/null +++ b/website/content/post/lexer.md @@ -0,0 +1,15 @@ +--- +title: "Lexical Analysis" +date: 2020-10-12 +draft: false +--- + +Overview of lexers and how to use them + +<!--more--> + +[Slideshow]({{< ref "/slides/02_lexical_analysis" >}}) + +--- + +{{% readpost file="/slides/02_lexical_analysis/_index.md" markdown=true %}} diff --git a/website/content/post/parser.md b/website/content/post/parser.md new file mode 100644 index 0000000..67887c0 --- /dev/null +++ b/website/content/post/parser.md @@ -0,0 +1,17 @@ +--- +title: "Parsing" +date: 2020-10-18 +draft: false +--- + +Overview of parsers and how to use them. + +This lecture will be entirely online - see the [Facebook group]({{< ref "/facebook" >}}) + +<!--more--> + +[Slideshow]({{< ref "/slides/03_parsing" >}}) + +--- + +{{% readpost file="/slides/03_parsing/_index.md" markdown=true %}} diff --git a/website/content/post/parser_generators.md b/website/content/post/parser_generators.md new file mode 100644 index 0000000..4320dcc --- /dev/null +++ b/website/content/post/parser_generators.md @@ -0,0 +1,17 @@ +--- +title: "Parser Generators" +date: 2020-10-26 +draft: false +--- + +Overview of parsers generators and how to use them. + +This lecture will be entirely online - see the [Facebook group]({{< ref "/facebook" >}}) + +<!--more--> + +[Slideshow]({{< ref "/slides/04_parser_generators" >}}) + +--- + +{{% readpost file="/slides/04_parser_generators/_index.md" markdown=true %}} diff --git a/website/content/post/projects.md b/website/content/post/projects.md new file mode 100644 index 0000000..7007188 --- /dev/null +++ b/website/content/post/projects.md @@ -0,0 +1,14 @@ +--- +title: "Projects" +date: 2020-12-22 +draft: false +--- + +The course projects for the 2020/2021 edition. + +<!--more--> + +The project definitions and any clarifications around them will happen in +[GitHub Discussions](https://github.com/SofiaCPP/IPL/discussions/categories/projects). + +--- diff --git a/website/content/post/resources.md b/website/content/post/resources.md new file mode 100644 index 0000000..43d39d9 --- /dev/null +++ b/website/content/post/resources.md @@ -0,0 +1,51 @@ +--- +title: "Resources" +date: 2018-09-29T00:24:06+03:00 +draft: false + +--- + +A general collection of resources on implementing programming languages and +virtual machines. + +<!--more--> + + +## General + +### Courses + +### Videos + +### Blogs + +### Twitter + +### Books + +- https://happi.github.io/theBeamBook/ +- https://the.gregor.institute/t/5k/842/ +- https://escholarship.org/uc/item/3025h4p9 +- https://www.winged.ch/language-fun/a_simple_virtual_machine/ + +## Lexer + +## Parser + +- https://github.com/christophevg/human-parser-generator + + +## Code + +- https://blog.quarkslab.com/frozen-an-header-only-constexpr-alternative-to-gperf-for-c14-users.html + +## Virtual Machines + +- https://github.com/rsms/sol +- https://github.com/skx/simple.vm +- https://github.com/feyeleanor/GoLightly +- https://github.com/andoma/vmir +- https://github.com/WAVM/WAVM +- https://github.com/kentdlee/CoCo +- https://the-ravi-programming-language.readthedocs.io/en/latest/lua_bytecode_reference.html +- https://opensource.com/article/18/4/introduction-python-bytecode diff --git a/website/content/post/vm_intro.md b/website/content/post/vm_intro.md new file mode 100644 index 0000000..aa5df6b --- /dev/null +++ b/website/content/post/vm_intro.md @@ -0,0 +1,17 @@ +--- +title: "Introduction to Virtual Machines" +date: 2020-11-02 +draft: false +--- + +Introduction to virtual machines as a model for computation. + +This lecture will be entirely online - see the [Facebook group]({{< ref "/facebook" >}}) + +<!--more--> + +[Slideshow]({{< ref "/slides/05_vm_intro" >}}) + +--- + +{{% readpost file="/slides/05_vm_intro/_index.md" markdown=true %}} diff --git a/website/content/post/vm_objects.md b/website/content/post/vm_objects.md new file mode 100644 index 0000000..c49fc16 --- /dev/null +++ b/website/content/post/vm_objects.md @@ -0,0 +1,17 @@ +--- +title: "Objects in the virtual machine" +date: 2020-11-16 +draft: false +--- + +Representing objects inside the virtual machine. + +This lecture will be entirely online - see the [Facebook group]({{< ref "/facebook" >}}) + +<!--more--> + +[Slideshow]({{< ref "/slides/06_vm_values" >}}) + +--- + +{{% readpost file="/slides/08_vm_objects/_index.md" markdown=true %}} diff --git a/website/content/post/vm_values.md b/website/content/post/vm_values.md new file mode 100644 index 0000000..48cdad0 --- /dev/null +++ b/website/content/post/vm_values.md @@ -0,0 +1,17 @@ +--- +title: "Values in Virtual Machines" +date: 2020-11-02 +draft: false +--- + +Representing values inside the virtual machine. + +This lecture will be entirely online - see the [Facebook group]({{< ref "/facebook" >}}) + +<!--more--> + +[Slideshow]({{< ref "/slides/06_vm_values" >}}) + +--- + +{{% readpost file="/slides/06_vm_values/_index.md" markdown=true %}} diff --git a/website/content/slides/00_intro/_index.md b/website/content/slides/00_intro/_index.md new file mode 100644 index 0000000..9341dfb --- /dev/null +++ b/website/content/slides/00_intro/_index.md @@ -0,0 +1,267 @@ +--- +title: "Introduction to Implementation of Programming Languages" +date: 2020-09-15T17:45:53+03:00 +draft: false +outputs: + - Reveal +--- +# Implementation of Programming Languages + +FMI 2020 + +--- +# Who are we? + +- Martin Dobrev +- Dimitar Trendafilov + +--- +# What is this? + +- An university course. +- A group of people that find it interesting how computers work and how they are + programmed. + +- https://sofiacpp.github.io/IPL + +--- + +## What we are going to talk about? + +- programming languages +- compilers +- interpreters +- virtual machines +- garbage collectors + +--- +## What are we not going to talk about? + +- virtualization of computer systems +- The theory of regular expressions and context free grammars +- compiler optimizations + +--- +## What are you going to learn about? + +- how a programming language works +- how to implement + - a compiler + - an interpreter + - a virtual machine for a language +- how programs in dynamically typed and statically type languages are executed +- how to automatically reclaim memory + +--- +## How are *WE* going to learn about VMs? + +We are going to study and enhance a JavaScript interpreter. + +- JSImpl (tm) + +--- +## Design goals for the JSImpl + +- understandable +- working +- extensible +- embeddable + +--- +## How you are going to be graded? + +- 50% mid-term test +- 50% course project + +Projects will be individual and there will be simpler and complex projects. + +--- +### Projects + +A few sample of projects are: + +- create a Lua interpreter based on JSImpl with generational, incremental + garbage collector +- create an AOT compiler for JavaScript +- create a static analyzer or a code refactoring tool + +--- +## Homework? + +- There will be homework assignments that will give you points. +- The assignments will be similar to the final projects, but simpler +- You don't have to do them, but if you do - you can choose a simpler project at + the end of the semester and still get 100%. + +--- +## Homework + +- Homeworks will be announced at the end of a lecture +- In two weeks on the lecture we will discuss the best homeworks +- You can submit the homework at any moment + - doing that after the two weeks, you will score less points +- Submitting your homework is done by issuing a pull request + +--- +## Homework + +- Make a folder inside the *homework* folder with your faculty number and a + folder inside that for each homework +- Sample - https://github.com/SofiaCPP/IPL/tree/master/homework/80095/js2html + +--- +## Sample homeworks + +- a minifier (with variable renaming, tree-shaking, etc) +- an obfuscator +- a beautifier +- a linter that detects usage of global variables, code complexity, etc +- code browser that allows for searching where a variable is defined and used +- transpiler + +--- +## Pull Requests + +You can make pull requests against the repository and get points based on their +contribution. + +- you can fix typos +- you can extend the VM we are implementing in a meaningful way + - i.e. add source location information to the AST + +--- +## Pull Requests + +- Follow the pull request template +- Add your faculty number in the description +--- + +## What are the requirements? + +1. Will to learn and time to experiment and write code +2. Programming with C++, fluent in C++ will be better +2. Programming with JavaScript or other dynamic language +3. Data structures +4. Languages, Finite Automata, Computability +5. How computers work - CPU, memory hierarchy, etc + +--- +# Contents of the course + +--- +## 1. Introduction + +0. Course information +1. Programming languages +2. Architectures of + - compilers + - interpreters + - virtual machines + +--- +## 2. Lexers + +How to recognize the words of a language? + +1. What is a lexer? +2. How to write one? +3. How to use [flex](https://github.com/westes/flex) + +--- +## 3. Parser + +How to recognize the sentences of a language? + +1. What is a parser? +2. How to write a parser? +3. How to use [bison](https://www.gnu.org/software/bison/) + +--- +## 4. AST + +Abstract Syntax Tree + +1. How to grow one? +2. What to do with it? +3. Evaluating the syntax tree +4. Transforming the syntax tree + +{{% note %}} +- language transformation at syntax level + - code formatting + - code minification +- syntactic macros + +{{% /note %}} + +--- +## 5. Bytecode + +1. Bytecode design +2. Bytecode generation +3. Bytecode interpretation + +--- +## 6. VMs + +Virtual machines + +1. What is a virtual machine? +2. Implementing the language features in the VM + - Library - arrays, hash maps, etc + - OOP + - Exception handling +3. Communicating with the "real" machine + +--- +## 7. GC + +Garbage collection + +1. How to manage the resources in a language + - manual + - automatic +2. Garbage Collection algorithms + - "conservative, generational and incremental" - will start to have meaning + for you + +--- +## 8. JIT & AOT code generation + +1. Machine code and generation +2. Just in Time +3. Ahead of Time + +--- +# Plan for the course + +1. Introduction - week 1 +2. Lexers - week 2 +3. Parser - week 2 +4. AST - week 3, 4 +5. Bytecode - weeks 5, 6 +6. VMs - weeks 7, 8, 10 +7. GC - weeks 10, 11 +8. JIT & AOT code generation - weeks 11, 12, 13 + +--- +## Resources + +- https://github.com/SofiaCPP/IPL + +- https://sofiacpp.github.io/IPL + +- Links to resources will be there too! + +--- +## Resources + +Real world virtual machines: + +- V8, SpiderMonkey, JavaScriptCore, ChakraCore and many more +- duktape +- lua, luajit +- cPython, PyPy, ... + +--- +# ? diff --git a/website/content/slides/01_dragons/_index.md b/website/content/slides/01_dragons/_index.md new file mode 100644 index 0000000..42bb8a5 --- /dev/null +++ b/website/content/slides/01_dragons/_index.md @@ -0,0 +1,418 @@ +--- +title: "The dragons" +date: 2018-08-02T17:45:53+03:00 +draft: false +outputs: ["Reveal"] +--- +# The dragons + +1. Programming languages +2. Architectures of + - compilers + - interpreters + - virtual machines + +--- +## Programming languages + +> A formal language, consisting of a set of instructions and used to implement +> programs. + +--- +## Program + +> A set of instructions used to control the behaviour of a machine. + +--- +## Formal language + +> Non human language. + +> A set of strings and symbols together with a set of rules. + +--- +### String and symbols + +- The language has alphabet and words. +- Also known as tokens. + +Most often the tokens are defined with regular grammar over the alphabet. +- regular grammars +- regular expressions +- finite automata + +--- +### Rules + +The rules for composing sentences from words. + +Most often the sentences are defined with context free grammar over the tokens. + +--- +## Compiler + +> Takes a program written in a high-level programming language and translates it +> to machine language. + +--- +### Building an executable + +Compiler + linker = executable + +--- +### Compiler + +1. Takes a program in a high-level language +2. Understands the program meaning +3. Generates a machine language program with the same meaning + +--- +### Compiler architecture + +Three-stage compiler structure + +1. Front end + - understands the program +2. Middle + - does the optimizations and removes syntactic sugar +3. Back end + - generates the machine code + +--- +#### Front end + +Understands the program? + +Builds an Abstract Syntax Tree (AST) of the program. + +1. Converts source to stream of token. + - Lexer +2. Converts the stream of tokens to a AST. + - Parser + +--- +##### Lexer + +Recognizes all the tokens in the program. Most often that involves regular +expressions and finite automata. + +- hand-written lexer +- lexer generation tool - takes a list of regular expressions and code to + execute + +--- +##### Parser + +Recognizes the rules from stream of tokens and builds the AST of the program. + +- hand-written parser +- parser generation tool + +--- +###### Grammars + +The grammar of a languages defines the structure of correct sentences and how to +derive their meaning. + +--- +###### CFG + +Context Free Grammars + + <expr> := <expr> <op> <expr> | (<expr>) | <term> + <op> := + | - | * | / + <term> := [0-9]+ + +--- +###### PEG + +Parser Expression Grammars are similar to CFG, but are more convenient for +parsing, since the `|` operator is not ambiguous. + +- CFG allows selecting any matching variant and can have more than one parse + tree. + - parsing algorithms try to resolve this +- PEG prioritizes the variants in the order that they are written. + +--- +###### PEG + + <expr> := <sum> + <sum> := <prod> ([+-] <prod>)* + <prod> := <value> ([*/] <value>)* + <value> := [0-9]+ / '(' <expr> ')' + +- That is a CFG as well, so for some grammars there is no difference. +- Some languages can be expressed only with ambiguous grammars. + +--- +###### CFG vs PEG + +Where the else goes? + + <if> := if <expr> <stmnt> else <stmnt> + | if <expr> <stmnt> + + + if x0 if x1 s1 else s2 + + if x0 { if x1 s1 } else s2 // 1 + if x0 { if x1 s1 else s2 } // 2 + +- CFG - it is ambiguous +- PEG - 2 - because it is the first option + +--- +###### LALR(n) + +LR(n) and LALR(n) are family of parsing algorithms for CFG + +- n is the number of look ahead terminals +- L - *left-to-right*, +- R - *right-most derivation* - the right most non-terminal is replaced + + +--- +###### Program + + function answer() { + return 6*7; + } + +--- +###### Tokens + +- keyword: `function` +- identifier: `answer` +- symbol: `(` +- symbol: `)` +- symbol: `{` +- keyword: `return` +- number: 6 +- symbol: `*` +- number: 7 +- symbol: `;` +- symbol: `}` + +--- +###### AST + +https://esprima.org/demo/parse.html?code=function%20answer()%20%7B%0A%20%20%20%20return%206%20*%207%3B%0A%7D + + { + "type": "FunctionDeclaration", + "id": { "type": "Identifier", "name": "answer" }, + "body": { + "type": "BlockStatement", + "body": [ + { + "type": "ReturnStatement", + "argument": { + "type": "BinaryExpression", + "operator": "*", + "left": { "type": "Literal", "value": 6 }, + "right": { "type": "Literal", "value": 7 } + } + } + ] + }, + } + +--- +### Middle + +Takes the AST and transforms that to some *Intermediate Representation* (IR) +that is convenient for: + +- optimization - constant propagation, loop unrolling, etc +- machine code generation - register allocation, etc + +--- +### IR + +- A compiler might have different levels and types of IR + - text and binary +- [Static Single Assignment form](https://en.wikipedia.org/wiki/Static_single_assignment_form) + +--- +### IR in LLVM - C + + int mul_add(int x, int y, int z) { + return x * y + z; + } + +--- +### IR in LLVM - IR + + define i32 @mul_add(i32 %x, i32 %y, i32 %z) { + entry: + %tmp = mul i32 %x, %y + %tmp2 = add i32 %tmp, %z + ret i32 %tmp2 + } + +--- +### WebAssembly + +WebAssembly is actually an IR. + + (module + (func (export "add") (param $n1 i32) (param $n2 i32) (result i32) + get_local $n1 + get_local $n2 + i32.add + ) + ) + +--- +### .NET CIL + +- C#, F#, Basic (some versions), etc target the .NET virtual machine +- Common Intermediate Language + + .class public Foo + { + .method public static int32 Add(int32, int32) cil managed + { + .maxstack 2 + ldarg.0 // load the first argument; + ldarg.1 // load the second argument; + add // add them; + ret // return the result; + } + } + +--- +### Back end + +> Takes the IR and produces native code for a particular machine + +--- +## Interpreter + +> Like the compiler, but instead of producing machine code, executes the program +> instruction by instruction translating from program instructions to machine +> instructions. + +--- +## Interpreter + +- Most interpreters have a REPL which makes them great for experiments. +- You don't need build an executable to run your program + +--- +### Compiler vs Interpreter + +- https://www.youtube.com/watch?v=_C5AHaS1mOA + +--- +### AOT compilation + +- Ahead of Time - the program is compiled before it is being run + +--- +### JIT compilation + +- Just in Time - the program is running (typically in an interpreter) and parts + of it are being compiled to native machine code while it is being executed + +--- +#### AOT vs JIT + +- AOT - less overhead, faster startup, generally better performance +- JIT - better chance for optimizations, since some of the program arguments + will be constants once the program has started, some of the virtual calls can + be devirtuallized at runtime + +--- +## Transpiler + +> Takes program written in one language and translates that to another language. + +- cfront +- CoffeScript, TypeScript +- nim + +--- +## Code transformation tools + +Lots of tools can be created based on the AST representation of a program + +- code formatting - *clang-format*, *gofmt*, *autopep8* +- code transformation - *clang-modernize* +- code analysis - *clang-tidy* + +--- +## Virtual Machine + +> Takes machine code and executes that on the real machine. + +Typically the VM implements most of the language features like automatic memory +collection and most of the standard library of the language. + +--- +### VMs + +- stack based + - all computations are done with operands pushed onto a stack, then popped + and the result is pushed back + - simple, but inefficient +- register based + - some of the computations are using registers (generally each local + variable gets a register) + - code generation is a bit harder, but the machine is more efficient + +--- +### RPN as an interperter + +Calculating an expression using postfix notation is actually an interpreter for +expressions. + +- Forth is a complete programming language based on that. + +--- +## What is a machine? + +- x86 is a virtual machine +- the CPU is an interpreter with microcode + +--- +# Tools + +- lex / flex +- re2c +- yacc / bison +- lemon +- antlr + +--- +### Crash course in JSImpl + +- repository organization +- continous integration +- pull requests + +--- +### Crash course in JSImpl + +- projects +- project generation +- allocators +- tests + +--- +### Architecture of JSImpl + +- frontend + - Lexer - text -> `vector<Token>` + - Parser - `vector<Token>` -> AST +- middle + - AST + - JSON + - Bytecode +- backend + - spasm + +--- +# ? +--- diff --git a/website/content/slides/02_lexical_analysis/_index.md b/website/content/slides/02_lexical_analysis/_index.md new file mode 100644 index 0000000..3caa107 --- /dev/null +++ b/website/content/slides/02_lexical_analysis/_index.md @@ -0,0 +1,301 @@ +--- +title: "Lexical Analysis" +date: 2018-09-30T13:45:53+03:00 +draft: false +outputs: ["Reveal"] +--- + +# Lexical Analysis + +> Converting the sequence of characters into a sequence of tokens for the +> language grammar. + +--- + +## Theory + +Programming languages have a finite set of keywords and rules for defining +numbers and identifiers. + +These are most easily modeled as a regular language, so you can use regex and +DFA to recognize the tokens. + +--- +## A short refresher on RE + +- *a* matches a +- *ab* matches ab +- *a|b* matches a or b +- `a*` matches a zero or more times +- *a?* matches a or *empty* +- *[0-9]* matches any digit +- *a{m,n}* matches between *m* and *n* *a*s + +--- +### What we can do with regular expressions + +- We can define regular language. +- We can recognize words from regular language. +- We can find patterns in sequence of characters. + +--- +### What we can't do with regular expressions + +- We can't recognize a{n}b{2n} +- We can't recognize if something is valid HTML +- We can't recognize if something is valid (place here almost every programing + language) + +--- +## Token + +> A token is a single terminal symbol for the language grammar. + +Tokens have type and value - i.e. `3.14` is a *number* and has value *3.14* + +--- +### Tokens + +Typical tokens are: + +- keyword - if, else, for, while, do, function +- number - integer - 42, double - 3.14, float - 3.14f +- string +- operator - `==`, `+`, +- symbol - `(`, `)`, + - it might be easier to split these into *LPAREN*, *RPAREN*. +- identifier - starts with a [a-zA-Z_]. Why? + +--- +### Because + +> it is easy to distinguish between identifiers, numbers, strings and symbols by +> looking at the first character + +--- +## How to implement a token? + +--- +### What goes into a token + +- type +- value +- file, line and column + +--- +#### Token Type + + enum TokenType + { + LeftParen, + RightParen, + // ... + While, + // ... + True, + False, + Eof, + }; + +--- +### Token struct + + struct Token + { + TokenType Type; + unsigned Line; + IPLString Lexeme; + double Number = 0.0; + }; + +--- +### double + string ~ wasteful + +- `std::variant<double, IPLString` will require *C++17* +- `union` does't work good with strings +- `union` with `string_view` -> *C++17* +- tokens can just keep strings and leave the parser to turn them into numbers + + +--- +## Lexer + +The lexer is the component of the compiler that does lexical analysis. + +--- +### How a lexer works + +Reads the source character by character and tries to match that against the +regexes that define the language. + +- Generally the longest match is preferred, so that `>=` is preferred over `>`. + +--- +### How to write a lexer + +- generate it with a tool +- write one by hand +- for an existing language + - search in google: "Lexical grammar for *language you prefer*" + - find an open-source implementation of the language + - it might be in a format ready for some tool +- for a custom language write down on paper the lexical grammar + - define your keywords + - rules for identifiers, numbers, strings, ... + - ... + +--- +#### Generate a lexer + +Tools use finite automata to recognize the tokens. When a token is recognized, +an user action code is executed, so that the type and the value of the token can +be stored. + +--- +#### Tools + +- *flex* - uses tables for the states of the automaton +- *re2c* - generates code for the automaton in *C* + - claims easier debuggability, but still the generated code is pretty + complex +- some parser generators have a built-in lexer as well + +--- +### Flex + + definitions + %% + rules + %% + user code + +--- + + %{ + /* include verbatim code */ + #include <math.h> + %} + + DIGIT [0-9] + ID [a-z][a-z0-9]* + + %% + +--- + + {DIGIT}+ { + printf("An int:%s:%d\n", yytext, atoi(yytext)); + } + + {DIGIT}+"."{DIGIT}* { + printf("A float:%s:%g\n", yytext, atof(yytext)); + } + + if|then|while|do|for|function { + printf("A keyword:%s\n", yytext); + } + + {ID} printf("An identifier:%s\n", yytext); + +--- +#### Input + +https://github.com/SofiaCPP/IPL/blob/master/demo/flex/JavaScript.flex + +--- +#### Output + +https://github.com/SofiaCPP/IPL/blob/master/demo/flex/lex.yy.c + +--- +#### Disclaimer + +> Default options used! + +`flex` is quite customizable, either by options, or by defines for the file. +We have used the default options for simplicity. + +--- +### re2c + +- re2c.org +- https://github.com/SofiaCPP/IPL/tree/master/spasm/src/asm + - lexer.re + - dfa.svg + +--- +## Debugging tool generated code + +- pretty much impossible in the generated code +- the tool is created to allow defining the lexer in high-level language + +> Debug the high-level language definition, not the generated code + +--- +## Writing a lexer by hand + +1. Start with the lexical grammar +2. Read input symbol by symbol, for each symbol follow rules that are still + possible +3. Continue reading until no more input is possible -> emit the last possible + token + +--- +## Writing a lexer by hand + +For our sample lexical grammar: + + while (c != '\0') { + if (isdigit(c)) { + emit_number(); + } + else if (c >= 'a' && c <= 'z') { + auto word = read_word(); + if (keyword(word)) { + emit_keyword(word); + } else { + emit_identifier(word); + } + } + else { error(); } + } + +--- +### Keyword vs identifier + +> The set of keywords is fixed and finite. + +- it is possible to create a perfect hash + - gperf is a tool for that +- use a good data-structure that will allow for very fast look-up + +--- +#### Demo for gperf + +https://github.com/SofiaCPP/IPL/tree/master/demo/gperf + +--- +# Note + +Some languages do not have/need grammar for compilation + +- assembler languages +- Languages based on reverse or prefix notation +- Forth + +--- +# Lexer in JSImpl + +`Lexer.cpp` +- by hand +- `std::unordered_map` to recognize keywords + + +--- +# Homework + +Create a xxx2html syntax highlighter for a language of your choice. + +--- +# ? + diff --git a/website/content/slides/03_parsing/_index.md b/website/content/slides/03_parsing/_index.md new file mode 100644 index 0000000..7fccdcc --- /dev/null +++ b/website/content/slides/03_parsing/_index.md @@ -0,0 +1,529 @@ +--- +title: "Parsing" +date: 2018-08-02T17:45:53+03:00 +draft: false +outputs: ["Reveal"] +--- + +# 3. Parsing + +--- +## Contents + +1. CFG and PEG +2. AST +3. Visitor pattern +4. Hand-crafted parsers + +--- +### Parser + +> Recognizes the rules of the language and builds the Abstract Syntax Tree +> (AST) of the program from the stream of tokens. + +--- +### Grammars + +The grammar of a languages defines the structure of correct sentences and how to +derive their meaning. + +--- +#### CFG + +Context Free Grammars are: + +1. formal grammars - they describe all the strings in a formal language +2. context free - there is only one non-terminal on left hand side of each rule + + <expr> ::= <expr> <op> <expr> | (<expr>) | <term> + <op> ::= + | - | * | / + <term> ::= [0-9]+ + +> Does this grammar allow for operator precedence? (No, more later) + +--- +##### Terminals and Non-terminals + +The grammar has two alphabets: + +1. Terminals - symbols in the strings of the language, only on right side of + rules +2. Non-terminals - stand on left side in each rule and can be used on the right + side + +--- +##### Terminals and Non-terminals + +In the expression grammar: + +- terminals - ( ) + - * / 0-9 +- non-terminals - expr, op, term + +--- +#### Backus-Naur Form - BNF + +Notation for describing context-free grammars. + + + <expr> ::= <expr> <op> <expr> | "(" <expr> ")" | <term> + <op> ::= "+" | "-" | "*" | "/" + <term> ::= <digit> | <digit><term> + <digit>::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" + +--- +#### Extended Backus-Naur Form - EBNF + +Extended BNF for more compact represenation of grammars. There are different +specifications for EBNF, but they have the same power, just different syntax. + +- https://www.w3.org/TR/REC-xml/#sec-notation + + + expr = expr , op , expr | "(" , expr , ")" | term + op = "+" | "-" | "*" | "/" + term = { digit } + digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" + + +--- +#### PEG + +Parser Expression Grammars are similar to CFG, but are more convenient for +parsing, since the choice operator is not ambiguous. + +- the choice operator is `/` (not `|`) and it is not commutative +- CFG allows selecting any matching variant and can have more than one parse + tree. + - parsing algorithms try to resolve this by extra rules +- PEG prioritizes the variants in the order that they are written. + + +--- +#### PEG + + <expr> ::= <sum> + <sum> ::= <prod> ([+-] <prod>)* + <prod> ::= <value> ([*/] <value>)* + <value> ::= [0-9]+ / '(' <expr> ')' + +- That is a CFG as well, so for some grammars there is no difference. +- Some languages can be expressed only with ambiguous grammars. + +--- +#### CFG vs PEG + +Where the `else` goes? + + <if> ::= if <expr> <stmnt> else <stmnt> + / if <expr> <stmnt> + + + if x0 if x1 s1 else s2 + + if x0 { if x1 s1 } else s2 // 1 + if x0 { if x1 s1 else s2 } // 2 + +- CFG - it is ambiguous +- PEG - 2 - because it is the first option + +--- +#### Program + + function answer() { + return 6*7; + } + +--- +###### Tokens + +- keyword: `function` +- identifier: `answer` +- symbol: `(` +- symbol: `)` +- symbol: `{` +- keyword: `return` +- number: 6 +- symbol: `*` +- number: 7 +- symbol: `;` +- symbol: `}` + +--- +## Abstract Syntax Tree (AST) + +- https://esprima.org/demo/parse.html?code=function%20answer()%20%7B%0A%20%20%20%20return%206%20*%207%3B%0A%7D +- https://astexplorer.net/ + +--- +### Concrete Syntax tree (CST) + +- aka Parse Tree +- aka Derivation Tree + +> The tree that starts from the grammar inital non-terminal and generates +> a string in the language. + +--- +### Abstract vs Concrete + +> AST differ from CST because superficial distinctions of form, unimportant for +> translation, do not appear in AST. + +--- + +We will be focusing solely on AST, since it is used for translation and it + easy to skip the CST and generate directly AST. + +--- +## Creating an AST + +- Most implementations use a common base class for each Node type and a derived + class for each specific node + + struct Node { + virtual ~Node() = 0; + }; + + typedef std::unique_ptr<Node> NodePtr; + +--- +### Node for a `for` cycle + + struct ForNode : Node { + virtual ~ForNode() override = default; + NodePtr m_Init; + NodePtr m_Condition; + NodePtr m_Increment; + NodePtr m_Body; + }; + +--- +### Using the AST + +- Compilers use the AST a lot to: + - remove syntactic sugar + - optmize + - generate IR or code +- It makes sense to be able to execute different code on the AST + +--- +#### How to work with the AST? + +- a `virtual` method for each operation? +- a recursive function (or a stack) with `switch` for each node type? + +> No, adding a new algorithm or a node will be difficult in both cases. + +--- +## Visitor pattern + +> Represent an operation to be performed on elements of an object structure. + +> Visitor lets you define a new operation without changing the classes of the +> elements on which it operates. + +--- +### Visitor in C++ + + struct NodeVisitor { + virtual ~NodeVisitor() = 0; + virtual Visit(IfNode& node) = 0; + virtual Visit(ForNode& node) = 0; + // etc + }; + +- There must be overloads for all the Node types. +- It is expected that the nodes change very rarely, while new visitors are + constantly added. + +--- +### Node + + struct NodeVisitor; + + struct Node { + virtual ~Node() = 0; + virtual void Visit(NodeVisitor& visitor) = 0; + }; + +--- +#### Node for a `for` cycle + + struct ForNode : Node { + virtual ~ForNode() override = default; + virtual void Visit(NodeVisitor& visitor) override { + visitor.Visit(*this); + } + + NodePtr m_Init; + NodePtr m_Condition; + NodePtr m_Increment; + NodePtr m_Body; + }; + +--- +## AST in JSImpl + +- Macro iterators +- Variadic Templates +- C++Future - metaclasses + +- [`Expression.h`](https://github.com/SofiaCPP/IPL/blob/master/JSImpl/src/Expression.h) +- [`Expression.cpp`](https://github.com/SofiaCPP/IPL/blob/master/JSImpl/src/Expression.cpp) +- [`ExpressionDefinitions.h`](https://github.com/SofiaCPP/IPL/blob/master/JSImpl/src/ExpressionDefinitions.h) + + +--- +### Visitor in JSImpl + +- [`ExpressionVisitor.h`](https://github.com/SofiaCPP/IPL/blob/master/JSImpl/src/ExpressionVisitor.h) + +--- +### Parsing algorithms + +- There a lot of algorithms for parsing grammars, with different time / memory + tradeoffs +- The algorithms can be: + - top-down or bottom-up + - left-most derivation or right-most derivation + +- Most of the algorithms require making the grammar follow a specific form and + then explain how to create a parser for the language. + +--- +### Parsing algorithms + +- Recursive descent parsing +- Operator-precedence parsing +- Pratt parsing - top-down operator-precedence parsing +- Packrat parsing +- [LL](https://en.wikipedia.org/wiki/LL_parser) +- [LR](https://en.wikipedia.org/wiki/LR_parser) +- [LALR](https://en.wikipedia.org/wiki/LALR_parser) + +These are the major grammar forms and parsing algorithms. While they are not +exactly the same in terms of algorithms and power. + +{{< note >}} + +- First three are easy to implement by hand, the second three are better + generated. +- Pratt parsing is a mix between recursive descent and operator-precedence. + +{{< /note >}} + +--- +## Hand-crafted parser + +Disclaimer: It is possible to write every parser manually, but we'll be +discussing: + +- top-down AKA recursive-descent parsers +- operator precedence parser + +When we get to generated parsers, will be discussing bottom-up parsers as well. + +--- +## Hand-crafted parser + +How to write a hand-crafted parser? + +1. Start with a grammar +2. For each *Non-terminal* *E* write a function that parses it and generates AST + for it. + +--- +### How to parse a *Non-terminal* + +for each rule that has *E* as a symbol on the left, make a case in the function +that parser the rule. + +- '|' is translated to `if` and `match(XXX)` or check whether a subexpression + has been parsed. +- `*` (repeats) are translated to `while (match(XXX))` +- *Non-terminals* are translated to calls to their functions +- *terminals* are translated to `require(XXX)` + +Where `XXX` is a token (aka *terminal*). + + +--- +### Math expression example + +--- +#### Grammar + + <expr> ::= <sum> + <sum> ::= <prod> ([+-] <prod>)* + <prod> ::= <value> ([*/] <value>)* + <value> ::= [0-9]+ / '(' <expr> ')' + +--- +##### Handling precedence + +- The higher the precedence -> the lower in the tree +- Lower precedence *non-terminals* generate higher ones + + <sum> ::= <prod> ([+-] <prod>)* + <prod> ::= <value> ([*/] <value>)* + +--- +##### Handling associativity + +- Left associative operators go deep (loop) on the left +- Right associative operators go deep (loop) on the right +- Or can be handled in the parser + + <sum> ::= <prod> [+-] <prod> | <sum> [+-] <prod> + +--- +#### Recursive descent + +--- +##### Expr + + // <expr> ::= <sum> + + AST parse_expr() { + return parse_sum(); + } + +--- +##### Sum + + // <sum> ::= <prod> ([+-] <prod>)* + + AST parse_sum() { + AST left = parse_prod(); + auto token = next_token(); + while (token == '+' || token == '-') { + AST right = parse_prod(); + left = make_op(token, left, right); + } + return left; + } + +--- +##### Prod + + // <prod> ::= <value> ([*/] <value>)* + + AST parse_prod() { + AST left = parse_value(); + auto token = next_token(); + while (token == '*' || token == '/') { + AST right = parse_value(); + left = make_op(token, left, right); + } + return left; + } + +--- +##### Value + + // <value> ::= [0-9]+ / '(' <expr> ')' + + AST parse_value() { + auto token = next_token(); + if (token == NUMBER) { + return make_number(token); + } + else if (token == '(') { + AST expr = parse_expr(); + require_token(')'); + return expr; + } + throw error; + } + +--- +#### Operator precedence + +[Shunting yard](https://en.wikipedia.org/wiki/Shunting-yard_algorithm) + +--- + int precedence(token) { + switch (token) { + case EOF: return 0; + case '(': return 2; + case ')': return 5; + case '+': + case '-': return 10; + case '*': + case '/': return 20; + } + } +--- + + AST parse_expr() { + stack<AST> output; + stack<Token> operators; + + do { + auto token = next_token(); + handle_token(token, output, operators); + } while (token != EOF); + + AST result = output.top(); + output.pop(); + assert(output.empty()); + return result; + } + +--- + + void handle_token(token, output, operators) { + if (token == NUMBER) { + output.push(make_number(token)); + } else { + handle_operator(token, output, operators); + } + } + +--- + + void handle_operator(token, output, operators) { + auto prec = precedence(token); + while (!operators.empty() && + (precedence(operators.top()) >= prec)) { + output_tree(operators.top()); + operators.pop(); + } + if (token == ')') { + assert(operators.top() == '('); + operators.pop(); + } else if (token != EOF) { // '(' or an operator + operators.push(token); + } + } + +--- + + void output_tree(Token operator, output) { + auto rhs = output.top(); + output.pop(); + auto lhs = output.top(); + output.pop(); + output.push(make_op(operator, lhs, rhs)); + } + +--- + +Most hand-written parsers use combination of recursive descent and operator +precendence for expression for better performance when parsing expressions. + +--- +# Homework + +Extend the xxx2html tool to: + +1. Produce pretty-printed html + - bonus: support line length limit +2. Produce html where functions have their background colored depending on + cyclomatic complexity ranging from light green to light read. +3. Produce html where control structures can be collapsed. + +Do only one of these. + +--- +# ? diff --git a/website/content/slides/04_parser_generators/_index.md b/website/content/slides/04_parser_generators/_index.md new file mode 100644 index 0000000..b1e4075 --- /dev/null +++ b/website/content/slides/04_parser_generators/_index.md @@ -0,0 +1,110 @@ +--- +title: "Parser Generators" +date: 2018-10-02T17:45:53+03:00 +draft: false +outputs: ["Reveal"] +--- + +# Parser Generators + +Contents: + +- LR Parsers +- Bison + +--- +# LR Parsers + +- L - the parsers reads the text only once, without backing up +- R - rightmost derivation +- bottom-up parser +- LR(1) - 1 - the number of look-ahead symbols necessary to parse the grammar + +--- +### Rightmost derivation + +- The tree created for an expression would replace the rightmost non-terminal at + each step + +--- +### Bottom-up + +The tree is constructed from the bottom - from the leaves to the root. + +--- +## Algorithm + +The parser: + +- keeps a stack of the parsed sub-trees so far +- runs in a loop over the input and on each iteration it does either +a *shift* or a *reduce* action. + + - shift - push the token on the stack + - reduce - pop N subtrees from the stack, make a new tree that has them as + children and push it to the stack + +--- +#### Ring any bells? + +--- +#### Ring any bells? + +Same as the shunting yard algorithm, but: +- without the operator precedence + - it replaced by the grammar structure +- There all the rules had just two children + +--- +### To shift or to reduce? + +- Depends on the grammar rules. +- The algorithm uses a Finite State Automaton (FSA) + +--- +### To shift or to reduce? + +The FSA has for each (state, next token) -> (action, next state) + +- action - whether to shift or reduce + +--- +# Bison + +- Bison generates LR(1) and GLR parsers + - GLR parsers can have arbitrary lookahead and be ambigous +- You don't always have to convert the grammar in an LR form + - operator precedence and assiociativity are handled for your + +--- +### Input + + %{ + /* verbatim copy */ + %} + + /* definitions */ + + %% + /* rules */ + %% + /* verbatim copy */ + +--- +### Parsing expressions + +https://github.com/SofiaCPP/IPL/blob/master/demo/bison/calc/parser.y + +--- +### Understanding the parser + +https://www.gnu.org/software/bison/manual/html_node/Debugging.html#Debugging + +--- +### + +[bison output for the expression grammar](parser) + +--- +# ? + diff --git a/website/content/slides/04_parser_generators/parser.html b/website/content/slides/04_parser_generators/parser.html new file mode 100644 index 0000000..724b703 --- /dev/null +++ b/website/content/slides/04_parser_generators/parser.html @@ -0,0 +1,334 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" xmlns:bison="http://www.gnu.org/software/bison/"> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> + <title>parser.y - GNU Bison XML Automaton Report</title> + <style type="text/css"> + body { + font-family: "Nimbus Sans L", Arial, sans-serif; + font-size: 9pt; + } + a:link { + color: #1f00ff; + text-decoration: none; + } + a:visited { + color: #1f00ff; + text-decoration: none; + } + a:hover { + color: red; + } + #menu a { + text-decoration: underline; + } + .i { + font-style: italic; + } + .pre { + font-family: monospace; + white-space: pre; + } + ol.decimal { + list-style-type: decimal; + } + ol.lower-alpha { + list-style-type: lower-alpha; + } + .point { + color: #cc0000; + } + #footer { + margin-top: 3.5em; + font-size: 7pt; + } + </style> + </head> + <body><h1>GNU Bison XML Automaton Report</h1><p> + input grammar: <span class="i">parser.y</span></p> + +<h3>Table of Contents</h3><ul id="menu"><li><a href="#reductions">Reductions</a><ul class="lower-alpha"><li><a href="#nonterminals_useless_in_grammar">Nonterminals useless in grammar</a></li><li><a href="#terminals_unused_in_grammar">Terminals unused in grammar</a></li><li><a href="#rules_useless_in_grammar">Rules useless in grammar</a></li></ul></li><li><a href="#conflicts">Conflicts</a></li><li><a href="#grammar">Grammar</a><ul class="lower-alpha"><li><a href="#grammar">Itemset</a></li><li><a href="#terminals">Terminal symbols</a></li><li><a href="#nonterminals">Nonterminal symbols</a></li></ul></li><li><a href="#automaton">Automaton</a></li></ul><h2><a name="reductions" id="reductions"></a> Reductions</h2><h3><a name="nonterminals_useless_in_grammar" id="nonterminals_useless_in_grammar"></a> Nonterminals useless in grammar</h3> + +<h3><a name="terminals_unused_in_grammar" id="terminals_unused_in_grammar"></a> Terminals unused in grammar</h3> + +<h3><a name="rules_useless_in_grammar" id="rules_useless_in_grammar"></a> Rules useless in grammar</h3> +<h2><a name="conflicts" id="conflicts"></a> Conflicts</h2> + +<h2><a name="grammar" id="grammar"></a> Grammar</h2> +<p class="pre"> +<a name="rule_0" id="rule_0"></a> 0 <span class="i">$accept</span> → <span class="i">input</span> <b>$end</b> + +<a name="rule_1" id="rule_1"></a> 1 <span class="i">input</span> → %empty +<a name="rule_2" id="rule_2"></a> 2 | <span class="i">expr</span> + +<a name="rule_3" id="rule_3"></a> 3 <span class="i">expr</span> → <b>NUMBER</b> +<a name="rule_4" id="rule_4"></a> 4 | <b>'('</b> <span class="i">expr</span> <b>')'</b> +<a name="rule_5" id="rule_5"></a> 5 | <span class="i">expr</span> <b>PLUS</b> <span class="i">expr</span> +<a name="rule_6" id="rule_6"></a> 6 | <span class="i">expr</span> <b>MINUS</b> <span class="i">expr</span> +<a name="rule_7" id="rule_7"></a> 7 | <span class="i">expr</span> <b>MULT</b> <span class="i">expr</span> +<a name="rule_8" id="rule_8"></a> 8 | <span class="i">expr</span> <b>DIV</b> <span class="i">expr</span> +</p> + +<h3><a name="terminals" id="terminals"></a> Terminals, with rules where they appear</h3> + +<p class="pre"><b>$end</b> (0) <a href="#rule_0">0</a> +<b>'('</b> (40) <a href="#rule_4">4</a> +<b>')'</b> (41) <a href="#rule_4">4</a> +<b>error</b> (256) +<b>NUMBER</b> (258) <a href="#rule_3">3</a> +<b>PLUS</b> (259) <a href="#rule_5">5</a> +<b>MINUS</b> (260) <a href="#rule_6">6</a> +<b>MULT</b> (261) <a href="#rule_7">7</a> +<b>DIV</b> (262) <a href="#rule_8">8</a> +</p> + +<h3><a name="nonterminals" id="nonterminals"></a> Nonterminals, with rules where they appear</h3> + +<p class="pre"><b>$accept</b> (10) + on left: <a href="#rule_0">0</a> +<b>input</b> (11) + on left: <a href="#rule_1">1</a> <a href="#rule_2">2</a> + on right: <a href="#rule_0">0</a> +<b>expr</b> (12) + on left: <a href="#rule_3">3</a> <a href="#rule_4">4</a> <a href="#rule_5">5</a> <a href="#rule_6">6</a> <a href="#rule_7">7</a> <a href="#rule_8">8</a> + on right: <a href="#rule_2">2</a> <a href="#rule_4">4</a> <a href="#rule_5">5</a> <a href="#rule_6">6</a> <a href="#rule_7">7</a> <a href="#rule_8">8</a> +</p><h2><a name="automaton" id="automaton"></a> Automaton</h2> + +<h3><a name="state_0" id="state_0"></a>state 0</h3> + +<p class="pre"> <a href="#rule_0"> 0</a> <span class="i">$accept</span> → <span class="point">.</span> <span class="i">input</span> <b>$end</b> + <a href="#rule_1"> 1</a> <span class="i">input</span> → <span class="point">.</span> %empty [$end] + <a href="#rule_2"> 2</a> | <span class="point">.</span> <span class="i">expr</span> + <a href="#rule_3"> 3</a> <span class="i">expr</span> → <span class="point">.</span> <b>NUMBER</b> + <a href="#rule_4"> 4</a> | <span class="point">.</span> <b>'('</b> <span class="i">expr</span> <b>')'</b> + <a href="#rule_5"> 5</a> | <span class="point">.</span> <span class="i">expr</span> <b>PLUS</b> <span class="i">expr</span> + <a href="#rule_6"> 6</a> | <span class="point">.</span> <span class="i">expr</span> <b>MINUS</b> <span class="i">expr</span> + <a href="#rule_7"> 7</a> | <span class="point">.</span> <span class="i">expr</span> <b>MULT</b> <span class="i">expr</span> + <a href="#rule_8"> 8</a> | <span class="point">.</span> <span class="i">expr</span> <b>DIV</b> <span class="i">expr</span> + + NUMBER <a href="#state_1">shift, and go to state 1</a> + '(' <a href="#state_2">shift, and go to state 2</a> + + $default <a href="#rule_1">reduce using rule 1</a> (input) + + input <a href="#state_3">go to state 3</a> + expr <a href="#state_4">go to state 4</a> +</p> + +<h3><a name="state_1" id="state_1"></a>state 1</h3> + +<p class="pre"> <a href="#rule_3"> 3</a> <span class="i">expr</span> → <b>NUMBER</b> <span class="point">.</span> + + $default <a href="#rule_3">reduce using rule 3</a> (expr) +</p> + +<h3><a name="state_2" id="state_2"></a>state 2</h3> + +<p class="pre"> <a href="#rule_3"> 3</a> <span class="i">expr</span> → <span class="point">.</span> <b>NUMBER</b> + <a href="#rule_4"> 4</a> | <span class="point">.</span> <b>'('</b> <span class="i">expr</span> <b>')'</b> + <a href="#rule_4"> 4</a> | <b>'('</b> <span class="point">.</span> <span class="i">expr</span> <b>')'</b> + <a href="#rule_5"> 5</a> | <span class="point">.</span> <span class="i">expr</span> <b>PLUS</b> <span class="i">expr</span> + <a href="#rule_6"> 6</a> | <span class="point">.</span> <span class="i">expr</span> <b>MINUS</b> <span class="i">expr</span> + <a href="#rule_7"> 7</a> | <span class="point">.</span> <span class="i">expr</span> <b>MULT</b> <span class="i">expr</span> + <a href="#rule_8"> 8</a> | <span class="point">.</span> <span class="i">expr</span> <b>DIV</b> <span class="i">expr</span> + + NUMBER <a href="#state_1">shift, and go to state 1</a> + '(' <a href="#state_2">shift, and go to state 2</a> + + expr <a href="#state_5">go to state 5</a> +</p> + +<h3><a name="state_3" id="state_3"></a>state 3</h3> + +<p class="pre"> <a href="#rule_0"> 0</a> <span class="i">$accept</span> → <span class="i">input</span> <span class="point">.</span> <b>$end</b> + + $end <a href="#state_6">shift, and go to state 6</a> +</p> + +<h3><a name="state_4" id="state_4"></a>state 4</h3> + +<p class="pre"> <a href="#rule_2"> 2</a> <span class="i">input</span> → <span class="i">expr</span> <span class="point">.</span> [$end] + <a href="#rule_5"> 5</a> <span class="i">expr</span> → <span class="i">expr</span> <span class="point">.</span> <b>PLUS</b> <span class="i">expr</span> + <a href="#rule_6"> 6</a> | <span class="i">expr</span> <span class="point">.</span> <b>MINUS</b> <span class="i">expr</span> + <a href="#rule_7"> 7</a> | <span class="i">expr</span> <span class="point">.</span> <b>MULT</b> <span class="i">expr</span> + <a href="#rule_8"> 8</a> | <span class="i">expr</span> <span class="point">.</span> <b>DIV</b> <span class="i">expr</span> + + PLUS <a href="#state_7">shift, and go to state 7</a> + MINUS <a href="#state_8">shift, and go to state 8</a> + MULT <a href="#state_9">shift, and go to state 9</a> + DIV <a href="#state_10">shift, and go to state 10</a> + + $default <a href="#rule_2">reduce using rule 2</a> (input) +</p> + +<h3><a name="state_5" id="state_5"></a>state 5</h3> + +<p class="pre"> <a href="#rule_4"> 4</a> <span class="i">expr</span> → <b>'('</b> <span class="i">expr</span> <span class="point">.</span> <b>')'</b> + <a href="#rule_5"> 5</a> | <span class="i">expr</span> <span class="point">.</span> <b>PLUS</b> <span class="i">expr</span> + <a href="#rule_6"> 6</a> | <span class="i">expr</span> <span class="point">.</span> <b>MINUS</b> <span class="i">expr</span> + <a href="#rule_7"> 7</a> | <span class="i">expr</span> <span class="point">.</span> <b>MULT</b> <span class="i">expr</span> + <a href="#rule_8"> 8</a> | <span class="i">expr</span> <span class="point">.</span> <b>DIV</b> <span class="i">expr</span> + + PLUS <a href="#state_7">shift, and go to state 7</a> + MINUS <a href="#state_8">shift, and go to state 8</a> + MULT <a href="#state_9">shift, and go to state 9</a> + DIV <a href="#state_10">shift, and go to state 10</a> + ')' <a href="#state_11">shift, and go to state 11</a> +</p> + +<h3><a name="state_6" id="state_6"></a>state 6</h3> + +<p class="pre"> <a href="#rule_0"> 0</a> <span class="i">$accept</span> → <span class="i">input</span> <b>$end</b> <span class="point">.</span> + + $default accept +</p> + +<h3><a name="state_7" id="state_7"></a>state 7</h3> + +<p class="pre"> <a href="#rule_3"> 3</a> <span class="i">expr</span> → <span class="point">.</span> <b>NUMBER</b> + <a href="#rule_4"> 4</a> | <span class="point">.</span> <b>'('</b> <span class="i">expr</span> <b>')'</b> + <a href="#rule_5"> 5</a> | <span class="point">.</span> <span class="i">expr</span> <b>PLUS</b> <span class="i">expr</span> + <a href="#rule_5"> 5</a> | <span class="i">expr</span> <b>PLUS</b> <span class="point">.</span> <span class="i">expr</span> + <a href="#rule_6"> 6</a> | <span class="point">.</span> <span class="i">expr</span> <b>MINUS</b> <span class="i">expr</span> + <a href="#rule_7"> 7</a> | <span class="point">.</span> <span class="i">expr</span> <b>MULT</b> <span class="i">expr</span> + <a href="#rule_8"> 8</a> | <span class="point">.</span> <span class="i">expr</span> <b>DIV</b> <span class="i">expr</span> + + NUMBER <a href="#state_1">shift, and go to state 1</a> + '(' <a href="#state_2">shift, and go to state 2</a> + + expr <a href="#state_12">go to state 12</a> +</p> + +<h3><a name="state_8" id="state_8"></a>state 8</h3> + +<p class="pre"> <a href="#rule_3"> 3</a> <span class="i">expr</span> → <span class="point">.</span> <b>NUMBER</b> + <a href="#rule_4"> 4</a> | <span class="point">.</span> <b>'('</b> <span class="i">expr</span> <b>')'</b> + <a href="#rule_5"> 5</a> | <span class="point">.</span> <span class="i">expr</span> <b>PLUS</b> <span class="i">expr</span> + <a href="#rule_6"> 6</a> | <span class="point">.</span> <span class="i">expr</span> <b>MINUS</b> <span class="i">expr</span> + <a href="#rule_6"> 6</a> | <span class="i">expr</span> <b>MINUS</b> <span class="point">.</span> <span class="i">expr</span> + <a href="#rule_7"> 7</a> | <span class="point">.</span> <span class="i">expr</span> <b>MULT</b> <span class="i">expr</span> + <a href="#rule_8"> 8</a> | <span class="point">.</span> <span class="i">expr</span> <b>DIV</b> <span class="i">expr</span> + + NUMBER <a href="#state_1">shift, and go to state 1</a> + '(' <a href="#state_2">shift, and go to state 2</a> + + expr <a href="#state_13">go to state 13</a> +</p> + +<h3><a name="state_9" id="state_9"></a>state 9</h3> + +<p class="pre"> <a href="#rule_3"> 3</a> <span class="i">expr</span> → <span class="point">.</span> <b>NUMBER</b> + <a href="#rule_4"> 4</a> | <span class="point">.</span> <b>'('</b> <span class="i">expr</span> <b>')'</b> + <a href="#rule_5"> 5</a> | <span class="point">.</span> <span class="i">expr</span> <b>PLUS</b> <span class="i">expr</span> + <a href="#rule_6"> 6</a> | <span class="point">.</span> <span class="i">expr</span> <b>MINUS</b> <span class="i">expr</span> + <a href="#rule_7"> 7</a> | <span class="point">.</span> <span class="i">expr</span> <b>MULT</b> <span class="i">expr</span> + <a href="#rule_7"> 7</a> | <span class="i">expr</span> <b>MULT</b> <span class="point">.</span> <span class="i">expr</span> + <a href="#rule_8"> 8</a> | <span class="point">.</span> <span class="i">expr</span> <b>DIV</b> <span class="i">expr</span> + + NUMBER <a href="#state_1">shift, and go to state 1</a> + '(' <a href="#state_2">shift, and go to state 2</a> + + expr <a href="#state_14">go to state 14</a> +</p> + +<h3><a name="state_10" id="state_10"></a>state 10</h3> + +<p class="pre"> <a href="#rule_3"> 3</a> <span class="i">expr</span> → <span class="point">.</span> <b>NUMBER</b> + <a href="#rule_4"> 4</a> | <span class="point">.</span> <b>'('</b> <span class="i">expr</span> <b>')'</b> + <a href="#rule_5"> 5</a> | <span class="point">.</span> <span class="i">expr</span> <b>PLUS</b> <span class="i">expr</span> + <a href="#rule_6"> 6</a> | <span class="point">.</span> <span class="i">expr</span> <b>MINUS</b> <span class="i">expr</span> + <a href="#rule_7"> 7</a> | <span class="point">.</span> <span class="i">expr</span> <b>MULT</b> <span class="i">expr</span> + <a href="#rule_8"> 8</a> | <span class="point">.</span> <span class="i">expr</span> <b>DIV</b> <span class="i">expr</span> + <a href="#rule_8"> 8</a> | <span class="i">expr</span> <b>DIV</b> <span class="point">.</span> <span class="i">expr</span> + + NUMBER <a href="#state_1">shift, and go to state 1</a> + '(' <a href="#state_2">shift, and go to state 2</a> + + expr <a href="#state_15">go to state 15</a> +</p> + +<h3><a name="state_11" id="state_11"></a>state 11</h3> + +<p class="pre"> <a href="#rule_4"> 4</a> <span class="i">expr</span> → <b>'('</b> <span class="i">expr</span> <b>')'</b> <span class="point">.</span> + + $default <a href="#rule_4">reduce using rule 4</a> (expr) +</p> + +<h3><a name="state_12" id="state_12"></a>state 12</h3> + +<p class="pre"> <a href="#rule_5"> 5</a> <span class="i">expr</span> → <span class="i">expr</span> <span class="point">.</span> <b>PLUS</b> <span class="i">expr</span> + <a href="#rule_5"> 5</a> | <span class="i">expr</span> <b>PLUS</b> <span class="i">expr</span> <span class="point">.</span> [$end, PLUS, MINUS, ')'] + <a href="#rule_6"> 6</a> | <span class="i">expr</span> <span class="point">.</span> <b>MINUS</b> <span class="i">expr</span> + <a href="#rule_7"> 7</a> | <span class="i">expr</span> <span class="point">.</span> <b>MULT</b> <span class="i">expr</span> + <a href="#rule_8"> 8</a> | <span class="i">expr</span> <span class="point">.</span> <b>DIV</b> <span class="i">expr</span> + + MULT <a href="#state_9">shift, and go to state 9</a> + DIV <a href="#state_10">shift, and go to state 10</a> + + $default <a href="#rule_5">reduce using rule 5</a> (expr) + + Conflict between <a href="#rule_5">rule 5</a> and token PLUS resolved as reduce (%left PLUS). + Conflict between <a href="#rule_5">rule 5</a> and token MINUS resolved as reduce (%left MINUS). + Conflict between <a href="#rule_5">rule 5</a> and token MULT resolved as shift (PLUS < MULT). + Conflict between <a href="#rule_5">rule 5</a> and token DIV resolved as shift (PLUS < DIV). +</p> + +<h3><a name="state_13" id="state_13"></a>state 13</h3> + +<p class="pre"> <a href="#rule_5"> 5</a> <span class="i">expr</span> → <span class="i">expr</span> <span class="point">.</span> <b>PLUS</b> <span class="i">expr</span> + <a href="#rule_6"> 6</a> | <span class="i">expr</span> <span class="point">.</span> <b>MINUS</b> <span class="i">expr</span> + <a href="#rule_6"> 6</a> | <span class="i">expr</span> <b>MINUS</b> <span class="i">expr</span> <span class="point">.</span> [$end, PLUS, MINUS, ')'] + <a href="#rule_7"> 7</a> | <span class="i">expr</span> <span class="point">.</span> <b>MULT</b> <span class="i">expr</span> + <a href="#rule_8"> 8</a> | <span class="i">expr</span> <span class="point">.</span> <b>DIV</b> <span class="i">expr</span> + + MULT <a href="#state_9">shift, and go to state 9</a> + DIV <a href="#state_10">shift, and go to state 10</a> + + $default <a href="#rule_6">reduce using rule 6</a> (expr) + + Conflict between <a href="#rule_6">rule 6</a> and token PLUS resolved as reduce (%left PLUS). + Conflict between <a href="#rule_6">rule 6</a> and token MINUS resolved as reduce (%left MINUS). + Conflict between <a href="#rule_6">rule 6</a> and token MULT resolved as shift (MINUS < MULT). + Conflict between <a href="#rule_6">rule 6</a> and token DIV resolved as shift (MINUS < DIV). +</p> + +<h3><a name="state_14" id="state_14"></a>state 14</h3> + +<p class="pre"> <a href="#rule_5"> 5</a> <span class="i">expr</span> → <span class="i">expr</span> <span class="point">.</span> <b>PLUS</b> <span class="i">expr</span> + <a href="#rule_6"> 6</a> | <span class="i">expr</span> <span class="point">.</span> <b>MINUS</b> <span class="i">expr</span> + <a href="#rule_7"> 7</a> | <span class="i">expr</span> <span class="point">.</span> <b>MULT</b> <span class="i">expr</span> + <a href="#rule_7"> 7</a> | <span class="i">expr</span> <b>MULT</b> <span class="i">expr</span> <span class="point">.</span> [$end, PLUS, MINUS, MULT, DIV, ')'] + <a href="#rule_8"> 8</a> | <span class="i">expr</span> <span class="point">.</span> <b>DIV</b> <span class="i">expr</span> + + $default <a href="#rule_7">reduce using rule 7</a> (expr) + + Conflict between <a href="#rule_7">rule 7</a> and token PLUS resolved as reduce (PLUS < MULT). + Conflict between <a href="#rule_7">rule 7</a> and token MINUS resolved as reduce (MINUS < MULT). + Conflict between <a href="#rule_7">rule 7</a> and token MULT resolved as reduce (%left MULT). + Conflict between <a href="#rule_7">rule 7</a> and token DIV resolved as reduce (%left DIV). +</p> + +<h3><a name="state_15" id="state_15"></a>state 15</h3> + +<p class="pre"> <a href="#rule_5"> 5</a> <span class="i">expr</span> → <span class="i">expr</span> <span class="point">.</span> <b>PLUS</b> <span class="i">expr</span> + <a href="#rule_6"> 6</a> | <span class="i">expr</span> <span class="point">.</span> <b>MINUS</b> <span class="i">expr</span> + <a href="#rule_7"> 7</a> | <span class="i">expr</span> <span class="point">.</span> <b>MULT</b> <span class="i">expr</span> + <a href="#rule_8"> 8</a> | <span class="i">expr</span> <span class="point">.</span> <b>DIV</b> <span class="i">expr</span> + <a href="#rule_8"> 8</a> | <span class="i">expr</span> <b>DIV</b> <span class="i">expr</span> <span class="point">.</span> [$end, PLUS, MINUS, MULT, DIV, ')'] + + $default <a href="#rule_8">reduce using rule 8</a> (expr) + + Conflict between <a href="#rule_8">rule 8</a> and token PLUS resolved as reduce (PLUS < DIV). + Conflict between <a href="#rule_8">rule 8</a> and token MINUS resolved as reduce (MINUS < DIV). + Conflict between <a href="#rule_8">rule 8</a> and token MULT resolved as reduce (%left MULT). + Conflict between <a href="#rule_8">rule 8</a> and token DIV resolved as reduce (%left DIV). +</p> + +<div id="footer"><hr />This document was generated using + <a href="http://www.gnu.org/software/bison/" title="GNU Bison"> + GNU Bison 3.0.4</a> + XML Automaton Report.<br /> + Verbatim copying and distribution of this entire page is + permitted in any medium, provided this notice is preserved.</div></body> +</html> diff --git a/website/content/slides/05_vm_intro/_index.md b/website/content/slides/05_vm_intro/_index.md new file mode 100644 index 0000000..2879fa1 --- /dev/null +++ b/website/content/slides/05_vm_intro/_index.md @@ -0,0 +1,370 @@ +--- +title: "Introduction to Virtual Machines" +date: 2018-11-07T17:45:53+03:00 +draft: false +outputs: ["Reveal"] +--- + +# Virtual Machines - Wikipedia + +> In computing, a virtual machine (VM) is an emulation of a computer system. +> Virtual machines are based on computer architectures and provide functionality +> of a physical computer. + +--- +# Virtual Machines - Wikipedia + +- system virtual machines - provide substitute for a real machine +- process virtual machines - allow executing of computer programs in a platform + independent environment + +> We will be looking only at the second type of virtual machines and VM will +> mean that for us. + +--- +# Virtual Machines + +- Implement a computational model +- Just like real machines AKA computers +- run on top of the real machine +- you can have a hardware implementation of VM + +--- + +## Computational model + +- Regular Languages +- Context Free Languages +- *Everything that is computable* + +--- +## Computational model + +- Regular Expressions +- Pushdown automata +- Turing machines + +--- +### Turing machine + +- has infinite tape with cells +- each cells can hold one of finite number of values +- head that can read, write and move to the left and right +- finite set of states, one designated as starting state +- finite program that given (state, value) return the new (state, action, value) + +--- +### Turing machine operation + +1. starts with the initial state +2. Read the value at the head position +3. look up (state, value) in the table - if missing *HALT* +4. Set state to *new state*, write *new value* at the head position and move the + head left or right +5. Go to 2 + +--- +## From theory to practice + +- Infinite tapes are expensive +- Not great user experience to interact via checking the cells on the tape + +--- +Still computers and VMs are an implementations of Turing machines. + +The tape is not infinite :/ + +- less powerful +- we have to reuse the tape + +--- +### What is inside a machine + +1. Processor - implements the machine running algorithm + - reads, writes to the tape, moves the head and changes the current state +2. Memory - the tape, consists of cells of variable sizes filled with 0 and 1 + - almost always random accessible +3. Program - the state transition function/table + - resides in the memory - von Neumann architecture +4. Program Counter (PC) - the current state + +{{% note %}} + +All the fancy output like sound and graphics is writting at dedicated addresses +in memory. + +So to writting something on the screen, used to be write the bytes in +0xF000-0xFFFF and the hardware will just blit them on the screen. +Playing a sound - set some address to the frequency of the tone. + + +{{% /note %}} + +--- +#### How the machine works? + +1. Reads the instruction at PC +2. Decodes the instruction at PC +3. Modifies the memory according to the instruction +4. Moves PC to the next instruction +5. Go to 1 + +--- +### Instructions + +- CISC - Complex Instruction Set Computer + - one instruction can do a lot of operations +- RISC - Reduced Instruction Set Computer +- Register Memory - most operations can use both - registers and memory + addresses +- Register Register - most operations take place only between registers and + there are dedicated instructions that allow loading and storing data in memory + +--- +### Instructions + +- x86 - CISC, Register Memory + - the CPU actually runs microcode that is RISC ... +- ARM - RISC, Register Register + +--- +### Instructions + +- transfer data between registers and memory +- add, substract, multiply, divide values +- boolean operations on values +- change the PC +- call a subroutine + +--- +### Subroutines + +- not required by Turing machines +- but very useful, that are part of every machine + +- Stack for storing return addresses (at least) +- Stack Pointer (SP) + +--- +### "Real" vs Virtual Machine + +- the "real" machine is implemented in the hardware +- the operations of the machine are mapped 1:1 to the hardware actions +- these statements used to be true, not any more + +{{% note %}} +Out-of-order execution, branch prediction -> meltdown, spectre show that our +"machine" code runs on a virtual machine. +{{% /note %}} + +--- +## Virtual machines + +- Stack based +- Register based + +--- +### Stack based VM + +- all operations work with arguments on the stack + - operands are popped from the stack + - the result is pushed on the stack + +--- + + read // from input to top of stack + dup + loop: + push 1 + sub + dup + push 0 + jmpeq end + swap + dup -1 + add + swap + jmp loop + end: + pop + print // pop result and print + +--- + +- the instructions are smaller and the code is compact +- more code is required + +--- +### Register based VM + +- operations can work with registers + +--- + + read 0 + move 1, 0 + loop: + sub 0, 0, #1 + cmp 0, #0 + jmp end + add 1, 1, 0 + jmp loop + end: + print 1 + +--- + +- less code +- the instructions have arguments and can be larger + +--- + +#### Typing + +VMs can be statically or dynamically typed + +- certain registers / memory locations / instructios can work only on certain + argument types. + +--- +### From VM to a interpreter + +Implementing everything at the VM level would be too hard + +- interpreter = VM + runtime +- VM - control logic and computations +- runtime - language features and standard library + +--- +### Course future + +1. Implement a register based VM that works with numbers +2. Implement a runtime + 1. Strings + 2. Objects + 3. Arrays + 4. Functions + 5. Garbage Collector +3. Make JSImpl generate code for the VM + +--- +## Implementing a VM + +- register based +- still needs a stack for argument passing and keeping local variables + +--- +### Instruction set + +- choosing an instruction set is difficult + - performance + - speed + - energy consumption + - how easy it is to target that instruction set + +--- + +Fixed size instructions vs variable length instructions: + +- fixed size is easier to decode, but imposes restrictions and can be wasteful + +--- +### Instruction set + +We'll be doing varible length instructions + +> The instruction set is subject to change, so do not start the press (yet!). + +--- +### Instruction set + +Instructions will be between 1 and 25 bytes. + +- 6 bits for OpCode - we have up to 64 opcodes +- 2 bits - n - length of the arguments + - 2^n bytes per agrument + - up to 3 arguments per instruction + +--- +### Instruction set + +https://docs.google.com/spreadsheets/d/1Q90x60BF-7T0jqPngScsjlaGBXXHRx4tszwCTSRYUrA/edit?usp=sharing + +--- +### Calling convention + +1. push arguments on stack +2. call function +3. callee can access arguments from the stack with regiters + - 0 - count of arguments + - -1 - first argument + - -n - n-th argument +4. callee calls `ret reg`, which removes all locals and arguments and leaves + `reg` on top of the stack +5. caller pops the result from the stack + +--- +### How a program looks? + + function add_answer(x) { + return x + 42; + } + +--- + + func add + const 42 // goes to register 2 + add 2, -1, 2 + ret 2 + +--- +### Interpreter loop + +1. read the next instruction +2. decode the opcode and arguments + - move PC to the next instruction +3. execute the operation +4. go to 1 + +--- + + while (1) { + auto instruction = get_op(PC); + switch (instruction & 0x3F) { + case ADD: { + const auto size = (instruction >> 6); + const auto arg0 = get_arg(PC, size); + const auto arg1 = get_arg(PC, size); + const auto arg2 = get_arg(PC, size); + m_Stack[arg0] = m_Stack[arg1] + m_Stack[arg2]; + } + // ... + } + } + +--- + + int get_op(byte*& PC) { + return *(PC++); + } + size_t get_arg(byte*& PC, int size) { + switch (size) { + case 0: + return *(PC++); + case 1: + return *(((unsigned short*&)PC)++); + case 2: + return *(((unsigned int*&)PC)++); + case 3: + return *(((size_t*)PC&)++); + } + } + +--- +# Homework + +- implement a brainfuck interpreter +- implement a gcd in spasm + +--- +# ? diff --git a/website/content/slides/06_vm_values/_index.md b/website/content/slides/06_vm_values/_index.md new file mode 100644 index 0000000..23d3d91 --- /dev/null +++ b/website/content/slides/06_vm_values/_index.md @@ -0,0 +1,299 @@ +--- +title: "Values in the VM" +date: 2018-11-21T17:45:53+03:00 +draft: false +outputs: ["Reveal"] +--- + +# Values in the VM + +- Languages and VMs +- NanBoxing + +--- + +# Language Semantics and VM + +The VM implementation depends a lot on language semantics + +- typing - static or dynamic? +- number types - integers and floating point +- strings - immutability + +--- + +That is why it is almost every language has its own VM. + +--- + +# Values in the VM? + + function add(a, b) { + return a + b + } + + +--- + + add r1 a1 a2 + ret r1 + +--- + +- must work for numbers +- must work for strings +- must work for strings and numbers mixed +- can work for objects and arrays + - if the target language has semantics for that + +--- + +## How do we support that? + +C++ is statically type, the value in the registers can have a single C++ type + +--- + +## Axiom of CS + +> *Every* problem can be solved by adding another level of indirection. + +> ..., except too many indirections. + +--- + +### Polymorhism + +- C++ way for type erasure + +- Base class with virtual methods + +--- + + struct Value { + virtual ValuePtr Add(ValuePtr rhs) const = 0; + // ... + } + + struct NumberValue : Value { + double m_Number; + } + +--- + +#### Performance + +- `sizeof(NumberValue)` - 16 B - 100% overhead + - pointer + double +- cache miss on every access to the number +- virtual call for adding two numbers + +- It is so inefficient, that almost nobody does it this way + +--- +### What we can do? + +--- + + struct Value { + bool m_IsDouble; + union { + double as_Double; + void* as_Pointer; + } m_Value; + } + +--- + +- still 100% memory overhead because m_Value will be aligned to 8 bytes + - will not fit in a register + - more cache misses + +--- +### Doubles and IEEE + +A double has 64-bits, from least to most significant: + +1. 52 bits - mantissa + - a leading 1 bit set to 1 is assumed, so the precision is 53 bits +2. 11 bits - exponent - from 0 to 2047 +3. 1 bit - sign + +Value = Mantissa * 2 ^ (exponent - 1023) + +--- + +Not all possible values are actually valid numbers. + +- Infinity - exponent is 2047, mantissa - 0 + + +--- + + double r = sqrt(-1); + + NaN - Not a Number + +- sign bit is set +- exponent is all 1 (2047) +- most significant bit of the mantissa is 1 +- the rest 51 bits do not matter - it is always a NaN + - the CPU always sets them to 0 + + +--- +# The rest 51 bits do not matter + +- so we can (ab)use them to store our pointers! +- but one pointer is 64 bits? + +--- + +> For x86_64 / arm64 the addresses above 2^48 are reserved and can't be used +> from user applications + +--- + +- 48 bits for the pointer +- 3 bits for ... type + +--- +### Type + + enum ValueType { + Number = 0, + Null = 1, + Undefined = 2, + Boolean = 3, + String = 4, + Array = 5, + Object = 6, + Function= 7, + }; + +--- +#### Why Number is 0? + +- so that we treat regular NaNs as numbers. + +--- +#### NanBoxing + + +Need to split easily `double` to bits - use union to share the memory between a +`double` and structs with bitfields. + + union { + double as_double; + NanPointer as_pointer; + CheckType to_check; + + } m_value; + +--- + + struct NanPointer + { + // order from least to most significant bits + // bit field - has type size_t, but only 48 bits + size_t pointer:48; + size_t tag:3; // 0 for a real nan and non zero for out type + size_t nan:13; // must be all 1s to force a nan + }; + +--- + + // Used to check whether the value is a double or not + struct CheckType + { + size_t payload: 48; + size_t check:16; + }; + +--- + + bool is_double() const + { + // If any of the least significant bits is non-zero, + // then this is not a normal double or a NaN value + return m_value.to_check.check <= 0xFFF8; + } + + double get_double() const + { + assert(is_double()); + return m_value.as_double; + } + +--- + + int get_tag() { + assert(!is_double()); + return m_value.as_pointer.tag; + } + + void* get_pointer() const { + return (void*)(size_t) m_value.as_pointer.pointer; + } + +--- + +#? + +--- + +## Strings + +Strings in JavaScript are immutable, which means that changing one string +returns another. + + +--- + +#### String interning + +> A method of storing only one instance of any given string, which is immutable. + +This means that there is only one copy of `"answer"` inside the VM + +--- + +Comparing strings for equality becomes very fast. + +> Two strings are the same if and only if their pointers are the same. + +--- + + struct StringValue + { + std::string Value; + // extra data + // int RefCount; + // int GCFlags; + + } + +--- + class Spasm + { + typedef std::unordered_set<StringValue> StringTable; + + StringTable m_Strings; + }; + +--- + + Value Spasm::AllocateString(const char* s) { + auto current = m_Strings.find(s); + if (current != m_Strings.end()) + { + return Value(ValueType::String, &(*current)); + } + auto insert = m_Strings.insert(StringValue(s)); + return Value(ValueType::String, &(*insert.second)); + } + + +--- + +# ? diff --git a/website/content/slides/08_vm_objects/_index.md b/website/content/slides/08_vm_objects/_index.md new file mode 100644 index 0000000..44d43f8 --- /dev/null +++ b/website/content/slides/08_vm_objects/_index.md @@ -0,0 +1,231 @@ +--- +title: "Objects in the VM" +date: 2018-12-05T17:45:53+03:00 +draft: false +outputs: ["Reveal"] +--- +# Objects in the VM + +--- +## Contents + +1. JavaScript Language Features +2. Getting properties +3. Objects +4. Optimizations +4. Talking to the world + +--- +## JavaScript Language Features + +> We will be discussing only EcmaScript 3 inheritance. + +1. Prototype-based inheritance +2. Everything is an object + +--- +### Inheritance + +JavaScript is dynamically typed, so inheritance is about properties + + console.log(answer.value) + +--- +#### Property access + +When looking-up a property in a object: + +1. Look for the property in the object, if not found +2. Look for the property in the object's prototype, if not found +3. Look for the property in the object's prototype's prototype ... + +--- + + Value GetProperty(object, name) { + Value result = object.GetProps().GetProperty(name); + while (result == undefined && object.GetPrototype()) { + object = object.GetPrototype(); + result = object.GetProps().GetProperty(name); + } + return result; + } + +--- +### Properties + +We need to map from string to a value. + +--- + + struct Properties + { + typedef std::unordered_map<StringValue* name, Value> PropertyMap; + PropertyMap m_Props; + + Value GetProperty(StringValue* name) { + const auto i = m_Props.find(name); + return i != m_Props.end()? i->second : Value::kUndefined; + } + }; + +--- +### Settting a property? + +Set on the object directly + + void SetProperty(Object* object, StringValue* name, + Value value) + { + object->GetProps().Set(name, value); + } + +--- +### Prototypes + + struct Object { + Value GetProperty(StringValue* name); + Object* GetPrototype() { return m_Prototype; } + Properties& GetProps() { return m_OwnProps;} + + Object* m_Prototype; + Properties m_OwnProps; + }; + +--- +## Optimizations + +--- +### Inline Cache + +> Skip the name look up for a property at the place where the look is done + +--- + + var s = 0; + for (var i = 0; i < strings.length; ++i) { + s += strings[i].length; // << Here is the interesting part + } + +--- + + getprop $t, $strings, $i + getprop $r, $t, "length" // Goes in to the runtime and does the hash lookup + add $s, $s, $r + +--- + + getprop $t, $strings, $i + if (typeof $t == "string") { + $r = getfast($t, 0); // (size_t*)(*t+8); + } else { + getprop $r, $t, "length" + } + +--- + +[JSC impl](www.filpizlo.com/papers.html) + +--- +## Hidden structures + + +--- +## Implementation + +--- +## Enhancing `Value` + +- `toString` +- `getProperty` +- `setProperty` + +--- +### `toString` + + Value Value::toString(Spasm* vm) const + { + switch(get_type()) + { + case Number: + // ... + } + } + +--- +### `getProperty` + + Value Value::getProperty(Spasm* vm, Value key) const + { + switch(get_type()) + { + case Number: + // ... + } + } + +--- +### ? + +- lots of duplication +- lots of casting + +--- +### Visitor again + +--- + + template <typename V> + typename V::ResultType Visit(V& v) { + switch(get_type()) + { + case Number: return v.Visit(get_double()); + case Null: return v.VisitNull(); + case Undefined: return v.VisitUndefined(); + case String: return v.Visit(get_string()); + // ... + } + } + +--- +#### `toString` + +--- + + struct ToStringVisitor + { + typedef Value ResultType; + + Value Visit(double d) const; + Value VisitUndefined() const; + Value VisitNull() const; + Value Visit(const StringValue& value) const; + Value Visit(const ArrayValue& value) const; + Value Visit(const ObjectValue& value) const; + Value Visit(const FunctionValue& value) const; + }; + +--- +### Talking to the world + + + typedef Value (*Function)(Value thisObject, Value function, Value* args, + size_t count, Value* exception) + + typedef Value (*Getter)(Value thisObject, StringValue* name, + Value* exception); + + typedef void (*Setter)(Value thisObject, StringValue* name, Value value, + Value* exception); + +--- +### Property descriptors + +Special kind of object that has: + + struct PropertyDescriptor { + Getter m_Getter; + Setter m_Setter; + }; + +--- +# ? diff --git a/website/content/slides/10_vm_gc/_index.md b/website/content/slides/10_vm_gc/_index.md new file mode 100644 index 0000000..046467f --- /dev/null +++ b/website/content/slides/10_vm_gc/_index.md @@ -0,0 +1,228 @@ +--- +title: "Garbage collection in the VM" +date: 2018-12-05T17:45:53+03:00 +draft: false +outputs: ["Reveal"] +--- +# Garbage Collection in the VM + +--- +## Contents + +1. Allocation +2. Mark and sweep +3. Embedability +4. Incremental +5. Optimizations + +--- +## Theory reminders + +1. [Theory](https://www.slideshare.net/eelcovisser/garbage-collection-69688448) +0. [Barriers](https://www.cs.kent.ac.uk/pubs/2010/3011/content.pdf) +0. [Lua GC](http://www.inf.puc-rio.br/~roberto/talks/gc-lua.pdf) +0. [V8 GC](http://jayconrod.com/posts/55/a-tour-of-v8-garbage-collection) +0. [Generational GC](https://www.ps.uni-saarland.de/courses/gc-ws01/slides/generational_gc.pdf) +0. [Java Z GC](http://cr.openjdk.java.net/~pliden/slides/ZGC-FOSDEM-2018.pdf) +0. [LuaJIT GC](http://wiki.luajit.org/New-Garbage-Collector) + +--- +## Tri-colour marking + +In the core of concurrent and incremental garbage collectors + +- _white_ - not used, _dead_ object +- _black_ - used, _alive_ object, whose references have been marked +- _gray_ - used, _alive_ object, whose references have yet to be marked + +> references are the objects that are referenced by the current object + +--- +### Invariants + +- Weak: + + > All white objects pointed to by a black object are reachable from some grey + > object through a chain of white objects. + +- Strong: + + > There are no pointers from black objects to white objects. + +--- +### Escapes + +In the incremental or concurrent GC, while the marking phase is running, the +mutator can change the references of a black object and break the above +invariants. + +--- +### Barriers + +Barriers are code that gets executed by the mutator every time it mutates the +heap. They will enforce that the invariants are being kept. + +- read +- write + - deletion + +--- +#### Read Barrier + +Ensure the invariants by not allowing getting a _white_ object out of a _gray_ +one + + def read(object, field): + if is_grey(object): + shade(object) + return object[field] + +Not used, since _read_ operations are more than _write_ operations in a program +and having a slower _read_ is worse than having a slower _write_ + +--- +#### Write Barrier + +Ensure the invariants by not allowing to set a _white_ object as a reference +inside a _black_ object + + def write(object, field, value): + object[field] = value + if is_black(object): + shade(value) + + +--- +## Disclaimer + +> This is how GC can be implemented. Everything is subject to change. + +--- +## Allocation + +Having a custom allocator is a *must* have for most VM + +- decent performance +- optimizations + +--- +### Allocators and C++ + +[Allocators in +C++](https://sofiacpp.github.io/advanced-cpp/slides/17_allocators.html) + +--- +### Simplicity matters + +For simplicity, we are going to not use a special allocator. + +--- +## Mark and sweep + + +- mark reacheable objects starting from variables (roots) +- sweep + - unmarked objects are returned to the free heap + - marked objects are unmarked (for the next cycle) + +--- +### Mark + +- every object starts as dead +- reacheable objects are marked as alive + +--- +#### Reachable objects + + +--- +#### Roots + +- registers +- stack +- global object / environment + +Where are these stored? + +--- +#### Roots + +- The `data_stack` + - everything upto `m_SP` +- The global object + +--- +#### Marking + + void Spasm::Mark() { + for (auto cell = &data_stack[0]; cell != m_SP; ++cell) { + Mark(cell); // ? + } + Mark(m_Global); + } + +--- +#### Visit every object in the heap? + +- Visitor pattern again + +--- + + struct MarkVisitor + { + typedef void ResultType; + + void Visit(double d) const {} + void VisitUndefined() const {} + void VisitNull() const {} + void Visit(StringValue& value) const; + void Visit(ArrayValue& value) const; + void Visit(ObjectValue& value) const; + void Visit(FunctionValue& value) const; + }; + +--- + + void Visit(StringValue& value) const { + if (Dead(value)) { + SetAlive(value); + } + } + +--- + + void Visit(ArrayValue& value) const { + if (Dead(value)) { + SetAlive(value); + for (auto i = 0u; i < value.length(); ++i) { + value.item(i).Visit(*this); + } + } + } + +--- + + void Visit(ObjectValue& value) const { + if (Dead(value)) { + SetAlive(value); + for (auto* p : value.m_Properties) { + p->first.Visit(*this); + p->second.Visit(*this); + } + value.m_Prototype->Visit(*this); + } + } + +--- +#### State + +Where to store whether an object is *dead* or *alive* + +- `bool` per object, string, array, function +- `bitmap` that holds one bit for a range of objects +- `bit` per pointer + + + +--- +# ? diff --git a/website/content/slides/11_jit/_index.md b/website/content/slides/11_jit/_index.md new file mode 100644 index 0000000..18070e1 --- /dev/null +++ b/website/content/slides/11_jit/_index.md @@ -0,0 +1,352 @@ +--- +title: "Just-in-time compilation" +date: 2020-12-05T17:45:53+03:00 +draft: false +outputs: ["Reveal"] +--- + +# Just-In-Time compilation + +--- +## Why + +- Interpreters are slow +- Flexibility +- Optimization + +--- +### Interpreters + +Adding two numbers in an interpreter requires: + +1. loading the instruction +2. decoding the intstruction +3. dispatching the opcode +4. doing the addition +5. storing the result + +All is actually 2 instructions on a x86_64 CPU + + ; rax = rbx + rcx + mov rax, rbx + add rax, rcx + +--- +### Flexibility + +- generate native code only for functions that will affect performance +- generate for the actual target CPU, instead of distributting prebuilt binaries + +--- +### Optimization + +- All function arguments can be treated as contants + - constant propagation everywhere +- unroll loops +- remove branches +- remove runtime dispatches (virtual methods) +- remove property lookups + +--- +## What we need + +- Executable memory +- Generate code +- Execute code + +--- +### Executable memory + +- Why +- Security concerns + +--- +### Create executable memory Linux + + virtualCodeAddress = mmap( + NULL, + codeBytes, + PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_ANONYMOUS | MAP_PRIVATE, + 0, + 0); + +--- +### Create executable memory Windows + + auto const buffer = VirtualAlloc(nullptr, page_size, MEM_COMMIT, PAGE_READWRITE); + VirtualProtect(buffer, code.size(), PAGE_EXECUTE_READ, &dummy); + +--- +### Create executable memory other platforms + +- Consoles +- Mobile +- Pic + +--- +### How to create and execute code + + typedef unsigned (*asmFunc)(void); + + unsigned char * memory = (unsigned char *) (virtualCodeAddress); + // mov %rdi, %rax + memory[i++] = 0x48; // REX.W prefix + memory[i++] = 0x8b; // MOV opcode, register/register + memory[i++] = 0xc7; // MOD/RM byte for %rdi -> %rax + // ret + memory[i++] = 0xc3; // RET opcode + ((asmFunc) (virtualCodeAddress))(); + +--- +### Generate code + +- Code generation takes time. +- The more optimized code, the more time it takes + +--- +#### JIT tiers + +Most VMs have tiers that allow to trade off between latency and throughput. + +- _latency_ - how soon the VM starts executing your code +- _thoughput_ - how fast the VM executes your code + +--- +#### JIT tiers + +VMs have more than two tiers, but they are levels between the two extremes + +- baseline + - no optimizations + - can handle everypossible type + - profiling code to detect what needs to optimization and how to optimize it +- optimized + - highly specialized for certain types and parameters + - fallbacks when it can't handle the provided types or parameters + +--- +#### Template JIT + +Every opcode can be translated to machine code snippet, possibly with changeable +registers for inputs and outputs. + +- can work on the AST level as well, no explicit need for bytecode + +--- +#### Template JIT + +The program can be translated to machine code by concatenating all the snippets +for the opcodes, possibly with other snippets that make sure that input and +output registers are matching. + +--- +#### Full scale compiler + +- SSA +- Constant propagation +- Register allocation +- Compiler optimizations + - branch elimination + - loop unrolling + - inlining + - vectorization + - de-virtualization + - ... + +--- +#### Template JIT + + function add_answer(x) { + return x + 42; + } + +--- +##### Spasm + + func add_answer + const 1, 42 + add 2, -1, 1 + ret 2 + +--- +##### x86_64 + + add_answer(int): + push rbp # save the current call frame + mov rbp, rsp # create a new call frame + mov dword ptr [rbp - 4], edi # spill first argument to stack + mov eax, dword ptr [rbp - 4] + add eax, 42 + pop rbp # clean up our frame + ret + + +--- +##### JIT + + ASM prolog() { + return ASM(["push rbp", "mov rbp, rsp"]); + } + + ASM add(Reg a0, Reg a1, Reg a2) { + return ASM(["mov a0, a1", "add a0, a2"]).set(a0, a1, a2); + } + +--- +##### Optimized + + add_answer(int): + lea eax, [rdi + 42] + ret + +--- +##### Floating point + + .LCPI0_0: + .long 0x42280000 + add_answer(float): + push rbp + mov rbp, rsp + movaps xmm1, xmm0 + movss xmm0, dword ptr [rip + .LCPI0_0] # xmm0 = mem[0],zero,zero,zero + movss dword ptr [rbp - 4], xmm1 + addss xmm0, dword ptr [rbp - 4] + pop rbp + ret + +--- +### Calling convention + +- Standard + - allows easier calling into functions compiled in the runtime or existing + libraries +- Custom + - allows easier mapping into the language and VM implementation + +--- +### FFI + +Foreign Function Interface + +FFI allows calls from the VM to functions in existing libraries, written in +other languages, most importantly C and OS functions. + +--- +#### To x86_64 and back + +Translate Spasm calling convention to x86_64 and back + +> For simplicity, lets assume that spasm works with integer numbers instead of +> floating point. + + +--- +#### X86_64 calling convention + +- depends on OS - MS Windows is different from the rest +- System V AMD64 APIB + - Pass first six integer arguments into `RDI`, `RSI`, `RDX`, `RCX`, `R8`, + `R9` + - Result into `RAX` + +--- +##### Prolog + +- push all arguments passed through registers onto the stack +- push the number of arguments on to the stack +- set `RDX` to point to the top of the stack + +--- +##### Operation + +- Push new registers onto the stack as they are created +- Make all the opcode JIT code work with `RCX`, `R8` and `R9` + +- Translate Spasm negative registers to positive offsets from `RDX` + - make sure to skip `rbp`, `r15` stored on the stack +- Translate Spasm positive registeers to negative offsets from `RDX` + +> The native stack grows towards lower addresses! + +--- +##### Operaton + +For each opcode +1. Move its operands from stack to `RCX`, `R8`, `R9` +2. Insert the machine code for the opcode +3. Move the result from `RCX` to the spasm register on the stack + +--- +##### Epilog + +- move from spasm result register to `rax` +- restore the stack frame +- `ret` + +--- +##### ? + +How to handle vararg functions? + +--- + +--- +##### Spasm + + func add_answer + const 1, 42 + add 2, -1, 1 + ret 2 + +--- +#### JIT - Prolog + + push rbp # save the current call frame + mov rbp, rsp # create a new call frame + push r15 + mov r15, rsp # keep the stack pointer (or do lots of pop in the end) + push r9 + push r8 + push rcx + push rdx + push rsi + push rdi + push 1 + mov rdi, rsp + +--- +##### JIT - Body + + mov [rdi - 8], 42 # 8 -> sizeof(vm_value) # const 1, 42 + + mov r8, [rdi + 8] # load operands + mov r9, [rdi - 8] + + mov rcx, r8 # add + add rcx, r9 + + mov [rdi + 16], rcx # store result + +--- +##### JIT - Epilog + + mov eax, [rdi + 16] + mov rsp, r15 + pop r15 + pop rbp + ret + + +--- +#### Code generators + +- [LLVM](https://llvm.org/docs/ORCv2.html) +- [PeachPy](https://pypi.org/project/PeachPy/) +- [DynASM](https://corsix.github.io/dynasm-doc/index.html) +- [GNU lightning](https://www.gnu.org/software/lightning/) + - [docs](https://www.gnu.org/software/lightning/manual/lightning.html) +- [LibJIT](https://www.gnu.org/software/libjit/) + +--- +# ? diff --git a/website/content/slides/template/_index.md b/website/content/slides/template/_index.md new file mode 100644 index 0000000..46f559f --- /dev/null +++ b/website/content/slides/template/_index.md @@ -0,0 +1,27 @@ +--- +title: "Intro Slides" +date: 2018-08-02T17:45:53+03:00 +draft: false +outputs: ["Reveal"] +--- + +# Test Hugo reveal tests + +- Title +- Bullet + +--- + +# Extra slide + +FMI course stuff. + +--- + + void f(int x) { + if (x) { + } + } + +--- + |
