PEG is a replacement to CFG. It is more powerful and can be more precise. In this slide I give a short introduction to PEG, the concept behind a programming language. Finally I write a parser for our programming language simple.
In this slide, I introduced how Gameboy works and how to build a Gameboy emulator using Rust programming language. Also, I introduce how to migrate the Rust emulator to Webassembly, so that we can run the emulator using browser.
Video of presentation of this slide:
https://www.youtube.com/watch?v=LqcEg3IVziQ
In this slide, I introduced how Gameboy works and how to build a Gameboy emulator using Rust programming language. Also, I introduce how to migrate the Rust emulator to Webassembly, so that we can run the emulator using browser.
Video of presentation of this slide:
https://www.youtube.com/watch?v=LqcEg3IVziQ
Teach your kids how to program with Python and the Raspberry PiJuan Gomez
RaspberryPis are the new frontier in enabling kids (and curious adults) to get access to an affordable and easy-to-program platform to build cool things. Over a million of these nifty little devices have been sold in less than a year and part of their popularity has been due to how easy it is to start programming on them.
In this session you'll learn how to get started with the Raspberry PI, initial set-up, configuration and some tips and tricks. Then we'll have a brief introduction to basic Python and we'll write a few simple programs that run on the RaspberryPI. The last section of the session will be dedicated to PyGame, we'll learn about surfaces, events, inputs, sprites, etc and demonstrate how to build very simple games that are as much fun for kids to write, than to play!
Python tutorial notes for all the beginners. It is covered with core topics in python with example programs. It is useful for all types of students (school, college (lower and higher level)) and also for teachers, lecturers, assistant professors, and professors.
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...Linaro
Compilers such as GCC may use undefined behaviour in language specifications to generate efficient code (especially newer recent versions). The rules for undefined behaviour can be subtle and programming mistakes can lead to correctness and/or security issues. This presentation will examine issues resulting from undefined behavior in applications. It will also discuss the position of the relevant language standards and address what compilers can do to exploit the standard in order to generate optimized code. We will also look at tools that can help us in detecting undefined behaviours so that these correctness issues can be prevented.
After a recap of implicits I introduce the type class mechanics in Scala. Then I have a look at ways for good non-intrusive type class design. The main focus of this presentation are type classes in Scala. In the last chapter I show the Haskell implementation of my example.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/28XnVtb.
Felix Klock describe the core concepts of the Rust language (ownership, borrowing, and lifetimes), as well as the tools beyond the compiler for open source software component distribution (cargo, crates.io). Filmed at qconlondon.com.
Felix Klock is a research engineer at Mozilla, where he works on the Rust compiler, runtime libraries, and language design. He previously worked on the ActionScript Virtual Machine for the Adobe Flash runtime. Klock is one of the developers of the Larceny Scheme language runtime.
With my simple implementation I wanted to demonstrate the basic ideas of th IO Monad.
My impl of the IO Monad is just a feasibility study, not production code!
When coding my impl of IO I was very much inspired by cats.effect.IO and monix.eval.Task which I studied at that time. Both are implementions of the IO Monad.
The API of my IO is very similar to the basics of Monix Task. This IO implementation also helped me to understand the IO Monad (of cats-effect) and Monix Task.
Interop with Future is also supported. You can convert IO to a Future. Vice versa you can convert a Future to an IO.
The development of my impl can be followed step by step in the code files in package iomonad.
Basics of Computer Coding: Understanding Coding LanguagesBrian Pichman
In this webinar, we will cover the different types of environments one may want to code for; whether that is apps, websites, programs that run on Windows, scripting, and more. Are you interested in learning code and considering if Java, PHP, CSS, Python or another language help bring a project to life? If you have a high-level approach to coding or are working on teaching patrons how to code or providing guidance to others, this will be a great resource to have.
We will learn about coding, types of code, and your " building-block" languages that eventually get you (or patrons) to the end goal of being a wizard coder. Resources for further education will be discussed in this webinar so you will have excellent next steps to continue your journey in a world of 1's and 0's.
Slides da disciplina de Análise de Algoritmos, ministrada pelo Prof. Marcelo H. Carvalho no curso de Pós-Graduação em Ciência da Computação, FACOM - UFMS.
Teach your kids how to program with Python and the Raspberry PiJuan Gomez
RaspberryPis are the new frontier in enabling kids (and curious adults) to get access to an affordable and easy-to-program platform to build cool things. Over a million of these nifty little devices have been sold in less than a year and part of their popularity has been due to how easy it is to start programming on them.
In this session you'll learn how to get started with the Raspberry PI, initial set-up, configuration and some tips and tricks. Then we'll have a brief introduction to basic Python and we'll write a few simple programs that run on the RaspberryPI. The last section of the session will be dedicated to PyGame, we'll learn about surfaces, events, inputs, sprites, etc and demonstrate how to build very simple games that are as much fun for kids to write, than to play!
Python tutorial notes for all the beginners. It is covered with core topics in python with example programs. It is useful for all types of students (school, college (lower and higher level)) and also for teachers, lecturers, assistant professors, and professors.
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...Linaro
Compilers such as GCC may use undefined behaviour in language specifications to generate efficient code (especially newer recent versions). The rules for undefined behaviour can be subtle and programming mistakes can lead to correctness and/or security issues. This presentation will examine issues resulting from undefined behavior in applications. It will also discuss the position of the relevant language standards and address what compilers can do to exploit the standard in order to generate optimized code. We will also look at tools that can help us in detecting undefined behaviours so that these correctness issues can be prevented.
After a recap of implicits I introduce the type class mechanics in Scala. Then I have a look at ways for good non-intrusive type class design. The main focus of this presentation are type classes in Scala. In the last chapter I show the Haskell implementation of my example.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/28XnVtb.
Felix Klock describe the core concepts of the Rust language (ownership, borrowing, and lifetimes), as well as the tools beyond the compiler for open source software component distribution (cargo, crates.io). Filmed at qconlondon.com.
Felix Klock is a research engineer at Mozilla, where he works on the Rust compiler, runtime libraries, and language design. He previously worked on the ActionScript Virtual Machine for the Adobe Flash runtime. Klock is one of the developers of the Larceny Scheme language runtime.
With my simple implementation I wanted to demonstrate the basic ideas of th IO Monad.
My impl of the IO Monad is just a feasibility study, not production code!
When coding my impl of IO I was very much inspired by cats.effect.IO and monix.eval.Task which I studied at that time. Both are implementions of the IO Monad.
The API of my IO is very similar to the basics of Monix Task. This IO implementation also helped me to understand the IO Monad (of cats-effect) and Monix Task.
Interop with Future is also supported. You can convert IO to a Future. Vice versa you can convert a Future to an IO.
The development of my impl can be followed step by step in the code files in package iomonad.
Basics of Computer Coding: Understanding Coding LanguagesBrian Pichman
In this webinar, we will cover the different types of environments one may want to code for; whether that is apps, websites, programs that run on Windows, scripting, and more. Are you interested in learning code and considering if Java, PHP, CSS, Python or another language help bring a project to life? If you have a high-level approach to coding or are working on teaching patrons how to code or providing guidance to others, this will be a great resource to have.
We will learn about coding, types of code, and your " building-block" languages that eventually get you (or patrons) to the end goal of being a wizard coder. Resources for further education will be discussed in this webinar so you will have excellent next steps to continue your journey in a world of 1's and 0's.
Slides da disciplina de Análise de Algoritmos, ministrada pelo Prof. Marcelo H. Carvalho no curso de Pós-Graduação em Ciência da Computação, FACOM - UFMS.
Golang basics for Java developers - Part 1Robert Stern
A short overview of Golang with Java comparison.
Part 1 of the series "Microservice development with Golang".
Contains hints and example links for potential Gophers
These are the slides for the seminar to have a basic overview on the GO Language, By Alessandro Sanino.
They were used on a Lesson in University of Turin (Computer Science Department) 11-06-2018
Conférence des Geeks Anonymes sur " le langage Go ", par Thomas Hayen le 23 septembre 2020.
Cette conférence est disponible en vidéo sur Youtube : https://youtu.be/AlGGneVGTJk
In this slide, I introduce how I implement RSA256 algorithm with verilog and verify with verilator.
The project use C++ to build the C-model and SystemC model.
To help build the model, we create a C++ class vint to simulate the behavior of Verilog. It supports normal Verilog operation with more strict rules.
The systemC model can be directly translated into Verilog, so the intention of Verilog design is quite clear and concise.
To simplify the simulation, we limit our module to be one input port and one output port. The port uses the valid/ready protocol to control the data flow, which can be modeled as sc_fifo in systemC.
With these abstraction, we can easily implement unit test for all of our modules, and make sure they act as what we want.
----
Please access the source code at:
https://github.com/yodalee/rsa256
The slide introduce some of the Rust concept that are necessary to write a kernel. Including wrapping an CSRs operation, locking mutable static variable, memory allocator, and pointer in Rust.
Please visit the project github to see the source code of the rrxv6 projects:
https://github.com/yodalee/rrxv6
Make A Shoot ‘Em Up Game with Amethyst FrameworkYodalee
A brief introduction to Rust, Amethyst game framework, and rust/WebAssembly. Focus on the ECS concept in amethyst framework and how to build a simple game by it.
You can build an old-fashioned Nixie tube clock by yourself. In this slide I introduce all the challenges and how I overcome them. I also publish all my design on website easyEDA and Github, you can use the design freely if you want to build your own one.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
AI Genie Review: World’s First Open AI WordPress Website CreatorGoogle
AI Genie Review: World’s First Open AI WordPress Website Creator
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-genie-review
AI Genie Review: Key Features
✅Creates Limitless Real-Time Unique Content, auto-publishing Posts, Pages & Images directly from Chat GPT & Open AI on WordPress in any Niche
✅First & Only Google Bard Approved Software That Publishes 100% Original, SEO Friendly Content using Open AI
✅Publish Automated Posts and Pages using AI Genie directly on Your website
✅50 DFY Websites Included Without Adding Any Images, Content Or Doing Anything Yourself
✅Integrated Chat GPT Bot gives Instant Answers on Your Website to Visitors
✅Just Enter the title, and your Content for Pages and Posts will be ready on your website
✅Automatically insert visually appealing images into posts based on keywords and titles.
✅Choose the temperature of the content and control its randomness.
✅Control the length of the content to be generated.
✅Never Worry About Paying Huge Money Monthly To Top Content Creation Platforms
✅100% Easy-to-Use, Newbie-Friendly Technology
✅30-Days Money-Back Guarantee
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIGenieApp #AIGenieBonus #AIGenieBonuses #AIGenieDemo #AIGenieDownload #AIGenieLegit #AIGenieLiveDemo #AIGenieOTO #AIGeniePreview #AIGenieReview #AIGenieReviewandBonus #AIGenieScamorLegit #AIGenieSoftware #AIGenieUpgrades #AIGenieUpsells #HowDoesAlGenie #HowtoBuyAIGenie #HowtoMakeMoneywithAIGenie #MakeMoneyOnline #MakeMoneywithAIGenie
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Understanding Nidhi Software Pricing: A Quick Guide 🌟
Choosing the right software is vital for Nidhi companies to streamline operations. Our latest presentation covers Nidhi software pricing, key factors, costs, and negotiation tips.
📊 What You’ll Learn:
Key factors influencing Nidhi software price
Understanding the true cost beyond the initial price
Tips for negotiating the best deal
Affordable and customizable pricing options with Vector Nidhi Software
🔗 Learn more at: www.vectornidhisoftware.com/software-for-nidhi-company/
#NidhiSoftwarePrice #NidhiSoftware #VectorNidhi
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Looking for a reliable mobile app development company in Noida? Look no further than Drona Infotech. We specialize in creating customized apps for your business needs.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
Do you want Software for your Business? Visit Deuglo
Deuglo has top Software Developers in India. They are experts in software development and help design and create custom Software solutions.
Deuglo follows seven steps methods for delivering their services to their customers. They called it the Software development life cycle process (SDLC).
Requirement — Collecting the Requirements is the first Phase in the SSLC process.
Feasibility Study — after completing the requirement process they move to the design phase.
Design — in this phase, they start designing the software.
Coding — when designing is completed, the developers start coding for the software.
Testing — in this phase when the coding of the software is done the testing team will start testing.
Installation — after completion of testing, the application opens to the live server and launches!
Maintenance — after completing the software development, customers start using the software.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Łukasz Chruściel
No one wants their application to drag like a car stuck in the slow lane! Yet it’s all too common to encounter bumpy, pothole-filled solutions that slow the speed of any application. Symfony apps are not an exception.
In this talk, I will take you for a spin around the performance racetrack. We’ll explore common pitfalls - those hidden potholes on your application that can cause unexpected slowdowns. Learn how to spot these performance bumps early, and more importantly, how to navigate around them to keep your application running at top speed.
We will focus in particular on tuning your engine at the application level, making the right adjustments to ensure that your system responds like a well-oiled, high-performance race car.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
2. Outline
Who am I? Why I did this?
Introduction to PEG
Introduction to programming language
Write a parser in PEG
No demo QQ
2
3. About Me
葉闆, Yodalee <lc85301@gmail.com>
Study EE in college, Microwave in graduate school,
now rookie engineer in Synopsys.
3
Github: yodalee Blogger: http://yodalee.blogspot.tw
4. Why Did I Do This
“Understanding Computation: From
Simple Machines to Impossible
Programs”
In the book, it implements a
programming language parser, regular
expression parser with Ruby Treetop,
which is a PEG parser.
I re-write all the code in Rust, so I did a
little research on PEG.
https://github.com/yodalee/computationbook
-rust
4
6. Parsing Expression Grammar, PEG
Bryan Ford, <Parsing Expression Grammars: A Recognition-
Based Syntactic Foundation>, 2004
A replacement to Chomsky language, by removing the
ambiguity in grammar.
The ambiguity is useful in modeling natural language, but not
in precise and unambiguous programming language.
6
Language <- Subject Verb Noun
Subject <- He | Lisa …
Verb <- is | has | sees…
Noun <- student | a toy …
7. PEG Basic Rule
PEG in definition are very similar to CFG, composed
of rules.
Rule will either:
Match success: consume input.
Match fail: not consume input.
As predicate: only return success or fail, not consume input.
7
8. PEG Basic Rule
Replace choice ‘|’ with
prioritized choice ‘/’.
Consider following:
CFG: A = “a” | “ab”
PEG: A = “a” / “ab”
PEG: A = a* a
8
Operator
“” String Literal
[] Character Set
. Any Character
(e1 e2 ..) Grouping
e? e+ e* Optional Repetition
&e And predicate
!e Not predicate
e1 e2 Sequence
e1 / e2 Prioritized Choice
9. Some Example
NUMBER <- [1-9] [0-9]*
COMMENT <- “//” (!”n” .)* n
EXPRESSION <- TERM ([+-] TERM)*
TERM <- FACTOR ([*/] FACTOR)*
STAT_IF <-
“if” COND “then” STATEMENT “else” STATEMENT /
“if” COND “then” STATEMENT
9
10. PEG is not CFG
PEG is equivalent to Top Down Programming Language
(TDPL)
Language anbncn is not context-free, however PEG can parse
it with And-predicate.
In CFG, A <- aAa | a match: odd number “a”
In PEG, A <- aAa / a match: 2n-1 “a”
It is an open problem that any CFG can be parsed by PEG
10
A <- aAb / ε
B <- bBc / ε
S <- &(A !b) a* B
11. Using PEG
There are many library that supports PEG:
Rust: rust-peg, pest, nom-peg …
C++: PEGTL, Boost …
Ruby: kpeg, raabro, Treetop …
Python: pyPEG, parsimonious …
Haskell: Peggy …
…
So why Rust?
11
13. Simple Language
3 types of statements: assign, if else, while.
Support integer arithmetic.
Support pair, list, function with one argument.
Simple, but actually we can do some complex things, like
recursion, map.
13
factorfun = function factor(x) {
if (x > 1) { x * factor ( x-1 ) } else { 1 }
}
result = factorfun(10); // 3628800
function last(l) {
if (isnothing(snd(l))) {
fst(l)
} else {
last(snd(l))
}
}
14. Abstract Syntax Tree
Use Rust enum to store a payload inside.
“Programming” like this:
14
pub enum Node {
Number(i64),
Boolean(bool),
Add(Box<Node>, Box<Node>),
Subtract(Box<Node>, Box<Node>),
LT(Box<Node>, Box<Node>)
…
}
let n = Node::add(Node::number(3), Node::number(4))
Add
3 4
LT
8
15. Abstract Syntax Tree
All the statement are Node:
15
pub enum Node {
Variable ( String ),
Assign ( String, Box<Node>),
If ( Box<Node>, Box<Node>, Box<Node> ),
While ( Box<Node>, Box<Node> ),
…
}
16. Pair, List and Nothing
Node::pair(Node::number(3), Node::number(4))
List [3,4,5] = pair(3, pair(4, pair(5, nothing)))
Nothing special
16
Pair
3 4
Pair
3 Pair
4 Pair
Nothing5
17. Environment and Machine
Environment stores a Hashmap<String, Box<Node>>, with
<add> and <get> interface.
A machine accepts an AST and an environment to evaluate
AST inside the machine.
17
pub struct Environment {
pub vars: HashMap<String, Box<Node>>
}
pub struct Machine {
pub environment: Environment,
expression: Box<Node>
}
18. Evaluate the AST
Add evaluate function to all AST node using trait.
The result will be a new Node.
18
fn evaluate(&self, env: &mut Environment) -> Box<Node>;
match *self {
Node::Add(ref l, ref r) => {
Node::number(l.evaluate(env).value() +
r.evaluate(env).value()) }
…
}
19. Evaluate the AST
How to evaluate While Node ( condition, body )?
Evaluate condition => evaluate body and self if true.
19
x = 3;
while (x < 9) { x = x * 2; }
Evaluate x = 3
Evaluate while (x < 9) x = x * 2
Evaluate x = x * 2
Evaluate while (x < 9) x = x * 2
Evaluate x = x * 2
Evaluate while (x < 9) x = x * 2
20. Function
Function is also a type of Node. Upon evaluation, function is
wrapped into Closure with environment at that time.
Call is evaluated the function with closure’s environment.
20
Node::Func(String, String, Box<Node>)
Node::Closure(Environment, Box<Node>)
fn evaluate(&self, env: &mut Environment) -> Box<Node> {
Node::Fun(ref name, ref arg, ref body) => {
Node::closure(env.clone(), Box::new(self.clone()))
}
}
21. Call a Function
fn evaluate(&self, env: &mut Environment) -> Box<Node> {
Node::Call(ref closure, ref arg) => {
match *closure {
Node::Closure(ref env, ref fun) => {
if let Node::Fun(funname, argname, body) = *fun.clone() {
let mut newenv = env.clone();
newenv.add(&funname, closure.evaluate(env));
newenv.add(&argname, arg.evaluate(env));
body.evaluate(&mut newenv);
} } } } }
21
22. Free Variable
Evaluate the free variables in a function to prevent copy whole
environment
Node::Variable
Node::Assign
Node::Function
22
function addx(x) { function addy(y) { x + y }}
-> no free variables
function addy(x) { x + y }
-> free variable y
23. Call a Function
if let Node::Fun(funname, argname, body) = *fun.clone() {
let mut newenv = new Environment {};
for var in free_vars(fun) {
newenv.add(var, env.get(var));
}
newenv.add(&funname, closure.evaluate(env));
newenv.add(&argname, arg.evaluate(env));
body.evaluate(&mut newenv);
}
23
24. What is a Language?
We make some concepts abstract, like a virtual machine.
Design a language is to design the abstraction.
Function “evaluate” implement the concept, of course we can
implement it as anything. Like return 42 on every evaluation.
24
Concept Simple, virtual
machine
Real Machine
Number 3 Node::number(3) 0b11 in memory
+ Node::add(l, r) add r1 r2
Choice Node::if branch command
25. What is a Language?
Abstraction will bring some precision issue, like floating point.
We have no way to express concept of <infinite>.
We can create a language on geometry as below, which
representation for line is best?
Consider every pros and cons the abstraction will bring.
25
Concept In Programming Language
Point (x: u32, y: u32)
Line
(Point, Point)
(Point, Slope)
(Point, Point, type{vertical, horizontal, angled})
Intersection Calculate intersection
27. The Pest Package
Rust Pest
https://github.com/pest-parser/pest
My simple language parser grammar at:
https://github.com/yodalee/simplelang
Parsing Flow
27
Grammar Parser
Source
Code
Pest Pair
Structure
Simple AST
28. The Pest Package
28
use pest::Parser;
#[derive(Parser)]
#[grammar = "simple.pest"]
struct SimpleParser;
let pairs = SimpleParser::parse(
Rule::simple, “<source code>")
A pair represents the parse result
from a rule.
Pair.as_rule() => the rule
Pair.as_span() => get match span
Pair.as_str() => matched text
Pair.into_inner()=> Sub-rules
30. Climb the Expression
Expression can be written as single Rule:
Expr = { Factor ~ (op_binary ~ Factor)* }
Pest provides a template, just defines:
Function build factor => create Factor Node
Function infix rules => create Operator Node
Operator precedence =>
vector of operator precedence and left/right association
30
31. Challenges
Error message with syntax error.
How to deal with optional? Like C for loop
A more systematic way to deal with large language, like C.
31
compound_statement <- block_list
block_list <- block_list block | ε
block <- declaration_list | statement_list
declaration_list <- declaration_list declaration | ε
statement_list <- statment_list statement | ε
// Wrong PEG
compound_statement <- block*
block <- declaration* ~ statement*
// Correct PEG
compound_statement <- block*
block <- (declaration | statement)+
33. Conclusion
PEG is a new, much powerful grammar than CFG. Fast and
convenient to create a small language parser.
The most important concept in programming language?
Abstraction
Is there best abstraction? NO. It is engineering.
33
34. Reference
<Parsing Expression Grammars: A Recognition-Based
Syntactic Foundation>, Bryan Ford
<Understanding Computation: From Simple Machines to
Impossible Programs>
<Programming Language Part B> on Coursera, University of
Washington
34