SlideShare a Scribd company logo
1 of 20
Monadic parser combinators
in C#
Speaker: Alexey Golub @Tyrrrz
Speaker: Alexey Golub @Tyrrrz
name: Alexey Golub
primary_occupation: Open Source Developer
pays_the_bills:
position: Senior Software Developer
company: Svitla Systems
tech_stack:
- C#
- .NET Core
- Azure/AWS
links:
- https://github.com/tyrrrz
- https://twitter.com/tyrrrz
- https://tyrrrz.me
Agenda
• What is a parser and what does it do?
• Formal theory of language and grammar
• Structural representation of context-free grammars
• Different ways to build a parser
• The concept of “parser combinators”
• Live-coding session (writing a JSON parser)
Speaker: Alexey Golub @Tyrrrz
What is a parser?
Speaker: Alexey Golub @Tyrrrz
“123 456,93”
What we see:
123 456,93
numeric literals
thousands separator
decimal separator
numeric literal
What we understand:
What computer sees:
byte[10] { 49, 50, 51, 32, 52, 53,
54, 44, 57, 51 }
What we want computer to understand:
new SyntacticComponents[] {
new NumericLiteral(123),
new ThousandsSeparator(),
new NumericLiteral(456),
new DecimalSeparator(),
new NumericLiteral(93)
}
What does a parser do?
Speaker: Alexey Golub @Tyrrrz
Input
“<foo><bar/></foo>”
“<foo></bar>”
“hello world”
Parser
grammar + context
Rejected invalid input
Unexpected token “</bar>” expected “</foo>”
Unexpected token “hello world”
Domain objects
new XElement(“foo”) {
new XElement(“bar”)
}
What are parsers used for?
• Data deserialization (JSON, XML, YAML)
• Static code analysis (ReSharper, TSLint)
• Syntax highlighting (VS Code, Highlight.js)
• Compilers, transpilers, interpreters (Roslyn, Markdig, Babel, SQL)
• Template engines (Razor, Liquid, Scriban)
• Natural language processing (Spellchecking, Translation)
Speaker: Alexey Golub @Tyrrrz
Formal language theory
Speaker: Alexey Golub @Tyrrrz
Language
Alphabet
set of allowed
characters
Words
set of valid
combinations
of characters
or other words
Grammar
set of rules
that define
how words are
generated
Formal grammar
Regular grammar
A → a, where A is non-terminal and a is
terminal
A → aB, where A and B are non-terminals
and a is terminal
Context-free grammar
A → ⍺, where A is non-terminal and ⍺ is a
string of terminals and/or non-terminals
Speaker: Alexey Golub @Tyrrrz
Rule of thumb
Contains recursive
grammar
Context-free
Regular
Speaker: Alexey Golub @Tyrrrz
Syntax trees
• Context-free languages are structurally represented using syntax trees
• Syntax trees are used to make sense of the input text
Root
Terminal
node
Non-terminal
node
Terminal
node
Terminal
node
Speaker: Alexey Golub @Tyrrrz
Example AST produced by C-like code
while (a != 0)
{
if (a > b)
{
a = a - b;
}
else
{
b = b - a;
}
}
return a;
Speaker: Alexey Golub @Tyrrrz
Loop/stack-based manual parsers
• Loop through all characters in the input
• Maintain context on a stack
Pros:
• Performance
• Fine-tuning
• Debugging
Cons:
• Hard to write/read/maintain
• Code is not expressive
Speaker: Alexey Golub @Tyrrrz
Parser generators
• Define grammar in a specialized language
• Generate consuming code in one of the supported languages
Pros:
• Expressive
• Language-agnostic
Cons:
• Overhead of an extra language
• Can’t leverage the power of C# to write grammar
Speaker: Alexey Golub @Tyrrrz
Parser combinators
• Define grammar using higher-order functions
• Build complex parsers by combining simpler ones
Pros:
• Expressive
• Easy to write/read/maintain
• Everything is in C#
Cons:
• Performance
• Debugging
Speaker: Alexey Golub @Tyrrrz
Parsers vs combinators
Parser<T>:
(success, result, length) = f(input, offset=0)
Examples: Char('a'), String("foo"), Digit
Combinator<T>:
Parser<T> = f(parser1, parser2)
Examples: Or(p1, p2), Many(p), DelimitedBy(p1, p2)
Speaker: Alexey Golub @Tyrrrz
Parser combinators illustrated
Input: 10 + 5
Parser:
Number:
AtLeastOne(Digit)
THEN
Sign:
Many(WhiteSpace)
Or(‘+’, ‘-’, ‘*’, ‘/’)
Many(WhiteSpace)
THEN
Number:
AtLeastOne(Digit)
Speaker: Alexey Golub @Tyrrrz
-> “10”
-> ‘1’, ‘0’
-> “ + “
-> “ “
-> ‘+’
-> “ “
-> “5”
-> ‘5’
Number (5)Number (10)
PlusOperator
Live-coding time
Let’s develop a basic JSON parser using Sprache in C#
Speaker: Alexey Golub @Tyrrrz
Links
• JSON parser from earlier – https://github.com/Tyrrrz/DotNetFest2019
• Sprache – https://github.com/sprache/Sprache
• Parsing in C# by Federico Tomassetti –
https://tomassetti.me/parsing-in-csharp
• Formal grammar on Wikipedia –
https://en.wikipedia.org/wiki/Formal_grammar
Other .NET parser-combinator libraries:
Superpower (C#), Pidgin (C#), FParsec (F#)
Speaker: Alexey Golub @Tyrrrz
Thank you!
Speaker: Alexey Golub @Tyrrrz

More Related Content

What's hot

Exploring C# DSLs: LINQ, Fluent Interfaces and Expression Trees
Exploring C# DSLs: LINQ, Fluent Interfaces and Expression TreesExploring C# DSLs: LINQ, Fluent Interfaces and Expression Trees
Exploring C# DSLs: LINQ, Fluent Interfaces and Expression Treesrasmuskl
 
Road to Dynamic LINQ Part 1
Road to Dynamic LINQ Part 1Road to Dynamic LINQ Part 1
Road to Dynamic LINQ Part 1Axilis
 
Road to Dynamic LINQ - Part 2
 Road to Dynamic LINQ - Part 2 Road to Dynamic LINQ - Part 2
Road to Dynamic LINQ - Part 2Axilis
 
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)Binary Studio
 
The Spoofax Language Workbench (SPLASH 2010)
The Spoofax Language Workbench (SPLASH 2010)The Spoofax Language Workbench (SPLASH 2010)
The Spoofax Language Workbench (SPLASH 2010)lennartkats
 
An Introduction to ANTLR
An Introduction to ANTLRAn Introduction to ANTLR
An Introduction to ANTLRMorteza Zakeri
 
Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)lennartkats
 
PDQ Programming Languages plus an overview of Alice - Frank Ducrest
PDQ Programming Languages plus an overview of Alice - Frank DucrestPDQ Programming Languages plus an overview of Alice - Frank Ducrest
PDQ Programming Languages plus an overview of Alice - Frank DucrestMatthew Turland
 
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Skills Matter
 
How does intellisense work?
How does intellisense work?How does intellisense work?
How does intellisense work?Adam Friedman
 
Automation testing using Ruby with Cucumber in Docker
Automation testing using Ruby with Cucumber in DockerAutomation testing using Ruby with Cucumber in Docker
Automation testing using Ruby with Cucumber in DockerViacheslav Horbovskykh
 
JOSA TechTalks - Compilers, Transpilers, and Why You Should Care
JOSA TechTalks - Compilers, Transpilers, and Why You Should CareJOSA TechTalks - Compilers, Transpilers, and Why You Should Care
JOSA TechTalks - Compilers, Transpilers, and Why You Should CareJordan Open Source Association
 
Raspberry using Python Session 1
Raspberry using Python Session 1Raspberry using Python Session 1
Raspberry using Python Session 1Mohamed Abd Ela'al
 
Metaprogramming by brandon
Metaprogramming by brandonMetaprogramming by brandon
Metaprogramming by brandonMaslowB
 
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NETNETFest
 

What's hot (20)

Exploring C# DSLs: LINQ, Fluent Interfaces and Expression Trees
Exploring C# DSLs: LINQ, Fluent Interfaces and Expression TreesExploring C# DSLs: LINQ, Fluent Interfaces and Expression Trees
Exploring C# DSLs: LINQ, Fluent Interfaces and Expression Trees
 
Road to Dynamic LINQ Part 1
Road to Dynamic LINQ Part 1Road to Dynamic LINQ Part 1
Road to Dynamic LINQ Part 1
 
Future of Xtext
Future of XtextFuture of Xtext
Future of Xtext
 
Road to Dynamic LINQ - Part 2
 Road to Dynamic LINQ - Part 2 Road to Dynamic LINQ - Part 2
Road to Dynamic LINQ - Part 2
 
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)
 
The Spoofax Language Workbench (SPLASH 2010)
The Spoofax Language Workbench (SPLASH 2010)The Spoofax Language Workbench (SPLASH 2010)
The Spoofax Language Workbench (SPLASH 2010)
 
An Introduction to ANTLR
An Introduction to ANTLRAn Introduction to ANTLR
An Introduction to ANTLR
 
Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)Using Aspects for Language Portability (SCAM 2010)
Using Aspects for Language Portability (SCAM 2010)
 
PDQ Programming Languages plus an overview of Alice - Frank Ducrest
PDQ Programming Languages plus an overview of Alice - Frank DucrestPDQ Programming Languages plus an overview of Alice - Frank Ducrest
PDQ Programming Languages plus an overview of Alice - Frank Ducrest
 
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
 
How does intellisense work?
How does intellisense work?How does intellisense work?
How does intellisense work?
 
Automation testing using Ruby with Cucumber in Docker
Automation testing using Ruby with Cucumber in DockerAutomation testing using Ruby with Cucumber in Docker
Automation testing using Ruby with Cucumber in Docker
 
Haskell a simple intro
Haskell a simple introHaskell a simple intro
Haskell a simple intro
 
JOSA TechTalks - Compilers, Transpilers, and Why You Should Care
JOSA TechTalks - Compilers, Transpilers, and Why You Should CareJOSA TechTalks - Compilers, Transpilers, and Why You Should Care
JOSA TechTalks - Compilers, Transpilers, and Why You Should Care
 
05 functional programming
05 functional programming05 functional programming
05 functional programming
 
Raspberry using Python Session 1
Raspberry using Python Session 1Raspberry using Python Session 1
Raspberry using Python Session 1
 
Metaprogramming by brandon
Metaprogramming by brandonMetaprogramming by brandon
Metaprogramming by brandon
 
Swift vs. Language X
Swift vs. Language XSwift vs. Language X
Swift vs. Language X
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET
 

Similar to .NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой способ написания парсеров для сложных языков)

Programming Languages #devcon2013
Programming Languages #devcon2013Programming Languages #devcon2013
Programming Languages #devcon2013Iván Montes
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideNascenia IT
 
Compiler Design Basics
Compiler Design BasicsCompiler Design Basics
Compiler Design BasicsAkhil Kaushik
 
X-CS-8.0 Programming in C Language 2022-2023.pdf
X-CS-8.0 Programming in C Language 2022-2023.pdfX-CS-8.0 Programming in C Language 2022-2023.pdf
X-CS-8.0 Programming in C Language 2022-2023.pdfAlefya1
 
Open Source Swift Under the Hood
Open Source Swift Under the HoodOpen Source Swift Under the Hood
Open Source Swift Under the HoodC4Media
 
Compiler Design Basics
Compiler Design BasicsCompiler Design Basics
Compiler Design BasicsAkhil Kaushik
 
Elasticsearch Basics
Elasticsearch BasicsElasticsearch Basics
Elasticsearch BasicsShifa Khan
 
C-and-Cpp-Brochure-English. .
C-and-Cpp-Brochure-English.               .C-and-Cpp-Brochure-English.               .
C-and-Cpp-Brochure-English. .spotguys705
 
An introduction to go programming language
An introduction to go programming languageAn introduction to go programming language
An introduction to go programming languageTechnology Parser
 
EMPEX LA 2018 - Inclusion Starts with Docs
EMPEX LA 2018 - Inclusion Starts with DocsEMPEX LA 2018 - Inclusion Starts with Docs
EMPEX LA 2018 - Inclusion Starts with DocsPete Gamache
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler ConstructionAhmed Raza
 
Embedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterEmbedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterHossam Hassan
 
Code as Data workshop: Using source{d} Engine to extract insights from git re...
Code as Data workshop: Using source{d} Engine to extract insights from git re...Code as Data workshop: Using source{d} Engine to extract insights from git re...
Code as Data workshop: Using source{d} Engine to extract insights from git re...source{d}
 

Similar to .NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой способ написания парсеров для сложных языков) (20)

Programming Languages #devcon2013
Programming Languages #devcon2013Programming Languages #devcon2013
Programming Languages #devcon2013
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation Guide
 
Compiler Design Basics
Compiler Design BasicsCompiler Design Basics
Compiler Design Basics
 
X-CS-8.0 Programming in C Language 2022-2023.pdf
X-CS-8.0 Programming in C Language 2022-2023.pdfX-CS-8.0 Programming in C Language 2022-2023.pdf
X-CS-8.0 Programming in C Language 2022-2023.pdf
 
Open Source Swift Under the Hood
Open Source Swift Under the HoodOpen Source Swift Under the Hood
Open Source Swift Under the Hood
 
Compiler Design Basics
Compiler Design BasicsCompiler Design Basics
Compiler Design Basics
 
Elasticsearch Basics
Elasticsearch BasicsElasticsearch Basics
Elasticsearch Basics
 
1 cc
1 cc1 cc
1 cc
 
C-and-Cpp-Brochure-English. .
C-and-Cpp-Brochure-English.               .C-and-Cpp-Brochure-English.               .
C-and-Cpp-Brochure-English. .
 
An introduction to go programming language
An introduction to go programming languageAn introduction to go programming language
An introduction to go programming language
 
COMPILER DESIGN PPTS.pptx
COMPILER DESIGN PPTS.pptxCOMPILER DESIGN PPTS.pptx
COMPILER DESIGN PPTS.pptx
 
EMPEX LA 2018 - Inclusion Starts with Docs
EMPEX LA 2018 - Inclusion Starts with DocsEMPEX LA 2018 - Inclusion Starts with Docs
EMPEX LA 2018 - Inclusion Starts with Docs
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
 
Embedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterEmbedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals master
 
Unit1.ppt
Unit1.pptUnit1.ppt
Unit1.ppt
 
Code as Data workshop: Using source{d} Engine to extract insights from git re...
Code as Data workshop: Using source{d} Engine to extract insights from git re...Code as Data workshop: Using source{d} Engine to extract insights from git re...
Code as Data workshop: Using source{d} Engine to extract insights from git re...
 
Rustbridge
RustbridgeRustbridge
Rustbridge
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Introduction to .Net
Introduction to .NetIntroduction to .Net
Introduction to .Net
 
Compilers.pptx
Compilers.pptxCompilers.pptx
Compilers.pptx
 

More from NETFest

.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET
.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET
.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NETNETFest
 
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE...
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE....NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE...
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE...NETFest
 
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NETNETFest
 
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистовNETFest
 
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem...
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem....NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem...
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem...NETFest
 
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven DesignNETFest
 
.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at Wirex
.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at Wirex.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at Wirex
.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at WirexNETFest
 
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A....NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...NETFest
 
.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture
.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture
.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixtureNETFest
 
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
.NET Fest 2019. Анатолий Колесник. Love, Death & F# TestsNETFest
 
.NET Fest 2019. Roberto Freato. Azure App Service deep dive
.NET Fest 2019. Roberto Freato. Azure App Service deep dive.NET Fest 2019. Roberto Freato. Azure App Service deep dive
.NET Fest 2019. Roberto Freato. Azure App Service deep diveNETFest
 
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
.NET Fest 2019. Леонид Молотиевский. DotNet Core in productionNETFest
 
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com...
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com....NET Fest 2019. Александр Демчук. How to measure relationships within the Com...
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com...NETFest
 
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real....NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...NETFest
 
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystemNETFest
 
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ....NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...NETFest
 
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali....NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...NETFest
 
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur....NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...NETFest
 
.NET Fest 2019. Eran Stiller. 6 Lessons I Learned on My Journey from Monolith...
.NET Fest 2019. Eran Stiller. 6 Lessons I Learned on My Journey from Monolith....NET Fest 2019. Eran Stiller. 6 Lessons I Learned on My Journey from Monolith...
.NET Fest 2019. Eran Stiller. 6 Lessons I Learned on My Journey from Monolith...NETFest
 
.NET Fest 2019. Kevin Dockx. Uncovering Swagger/OpenAPI
.NET Fest 2019. Kevin Dockx. Uncovering Swagger/OpenAPI.NET Fest 2019. Kevin Dockx. Uncovering Swagger/OpenAPI
.NET Fest 2019. Kevin Dockx. Uncovering Swagger/OpenAPINETFest
 

More from NETFest (20)

.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET
.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET
.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET
 
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE...
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE....NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE...
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE...
 
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET
 
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов
 
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem...
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem....NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem...
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem...
 
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
 
.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at Wirex
.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at Wirex.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at Wirex
.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at Wirex
 
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A....NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
 
.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture
.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture
.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture
 
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
 
.NET Fest 2019. Roberto Freato. Azure App Service deep dive
.NET Fest 2019. Roberto Freato. Azure App Service deep dive.NET Fest 2019. Roberto Freato. Azure App Service deep dive
.NET Fest 2019. Roberto Freato. Azure App Service deep dive
 
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
 
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com...
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com....NET Fest 2019. Александр Демчук. How to measure relationships within the Com...
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com...
 
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real....NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...
 
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem
 
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ....NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...
 
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali....NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...
 
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur....NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...
 
.NET Fest 2019. Eran Stiller. 6 Lessons I Learned on My Journey from Monolith...
.NET Fest 2019. Eran Stiller. 6 Lessons I Learned on My Journey from Monolith....NET Fest 2019. Eran Stiller. 6 Lessons I Learned on My Journey from Monolith...
.NET Fest 2019. Eran Stiller. 6 Lessons I Learned on My Journey from Monolith...
 
.NET Fest 2019. Kevin Dockx. Uncovering Swagger/OpenAPI
.NET Fest 2019. Kevin Dockx. Uncovering Swagger/OpenAPI.NET Fest 2019. Kevin Dockx. Uncovering Swagger/OpenAPI
.NET Fest 2019. Kevin Dockx. Uncovering Swagger/OpenAPI
 

Recently uploaded

HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 

Recently uploaded (20)

HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой способ написания парсеров для сложных языков)

  • 1. Monadic parser combinators in C# Speaker: Alexey Golub @Tyrrrz
  • 2. Speaker: Alexey Golub @Tyrrrz name: Alexey Golub primary_occupation: Open Source Developer pays_the_bills: position: Senior Software Developer company: Svitla Systems tech_stack: - C# - .NET Core - Azure/AWS links: - https://github.com/tyrrrz - https://twitter.com/tyrrrz - https://tyrrrz.me
  • 3. Agenda • What is a parser and what does it do? • Formal theory of language and grammar • Structural representation of context-free grammars • Different ways to build a parser • The concept of “parser combinators” • Live-coding session (writing a JSON parser) Speaker: Alexey Golub @Tyrrrz
  • 4. What is a parser? Speaker: Alexey Golub @Tyrrrz “123 456,93” What we see: 123 456,93 numeric literals thousands separator decimal separator numeric literal What we understand: What computer sees: byte[10] { 49, 50, 51, 32, 52, 53, 54, 44, 57, 51 } What we want computer to understand: new SyntacticComponents[] { new NumericLiteral(123), new ThousandsSeparator(), new NumericLiteral(456), new DecimalSeparator(), new NumericLiteral(93) }
  • 5. What does a parser do? Speaker: Alexey Golub @Tyrrrz Input “<foo><bar/></foo>” “<foo></bar>” “hello world” Parser grammar + context Rejected invalid input Unexpected token “</bar>” expected “</foo>” Unexpected token “hello world” Domain objects new XElement(“foo”) { new XElement(“bar”) }
  • 6. What are parsers used for? • Data deserialization (JSON, XML, YAML) • Static code analysis (ReSharper, TSLint) • Syntax highlighting (VS Code, Highlight.js) • Compilers, transpilers, interpreters (Roslyn, Markdig, Babel, SQL) • Template engines (Razor, Liquid, Scriban) • Natural language processing (Spellchecking, Translation) Speaker: Alexey Golub @Tyrrrz
  • 7. Formal language theory Speaker: Alexey Golub @Tyrrrz Language Alphabet set of allowed characters Words set of valid combinations of characters or other words Grammar set of rules that define how words are generated
  • 8. Formal grammar Regular grammar A → a, where A is non-terminal and a is terminal A → aB, where A and B are non-terminals and a is terminal Context-free grammar A → ⍺, where A is non-terminal and ⍺ is a string of terminals and/or non-terminals Speaker: Alexey Golub @Tyrrrz
  • 9.
  • 10. Rule of thumb Contains recursive grammar Context-free Regular Speaker: Alexey Golub @Tyrrrz
  • 11. Syntax trees • Context-free languages are structurally represented using syntax trees • Syntax trees are used to make sense of the input text Root Terminal node Non-terminal node Terminal node Terminal node Speaker: Alexey Golub @Tyrrrz
  • 12. Example AST produced by C-like code while (a != 0) { if (a > b) { a = a - b; } else { b = b - a; } } return a; Speaker: Alexey Golub @Tyrrrz
  • 13. Loop/stack-based manual parsers • Loop through all characters in the input • Maintain context on a stack Pros: • Performance • Fine-tuning • Debugging Cons: • Hard to write/read/maintain • Code is not expressive Speaker: Alexey Golub @Tyrrrz
  • 14. Parser generators • Define grammar in a specialized language • Generate consuming code in one of the supported languages Pros: • Expressive • Language-agnostic Cons: • Overhead of an extra language • Can’t leverage the power of C# to write grammar Speaker: Alexey Golub @Tyrrrz
  • 15. Parser combinators • Define grammar using higher-order functions • Build complex parsers by combining simpler ones Pros: • Expressive • Easy to write/read/maintain • Everything is in C# Cons: • Performance • Debugging Speaker: Alexey Golub @Tyrrrz
  • 16. Parsers vs combinators Parser<T>: (success, result, length) = f(input, offset=0) Examples: Char('a'), String("foo"), Digit Combinator<T>: Parser<T> = f(parser1, parser2) Examples: Or(p1, p2), Many(p), DelimitedBy(p1, p2) Speaker: Alexey Golub @Tyrrrz
  • 17. Parser combinators illustrated Input: 10 + 5 Parser: Number: AtLeastOne(Digit) THEN Sign: Many(WhiteSpace) Or(‘+’, ‘-’, ‘*’, ‘/’) Many(WhiteSpace) THEN Number: AtLeastOne(Digit) Speaker: Alexey Golub @Tyrrrz -> “10” -> ‘1’, ‘0’ -> “ + “ -> “ “ -> ‘+’ -> “ “ -> “5” -> ‘5’ Number (5)Number (10) PlusOperator
  • 18. Live-coding time Let’s develop a basic JSON parser using Sprache in C# Speaker: Alexey Golub @Tyrrrz
  • 19. Links • JSON parser from earlier – https://github.com/Tyrrrz/DotNetFest2019 • Sprache – https://github.com/sprache/Sprache • Parsing in C# by Federico Tomassetti – https://tomassetti.me/parsing-in-csharp • Formal grammar on Wikipedia – https://en.wikipedia.org/wiki/Formal_grammar Other .NET parser-combinator libraries: Superpower (C#), Pidgin (C#), FParsec (F#) Speaker: Alexey Golub @Tyrrrz
  • 20. Thank you! Speaker: Alexey Golub @Tyrrrz