SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
Building parsers in
JavaScript
Kenneth Geisshirt
kneth
kgeisshirt
Agenda
● What is parsing?
● Fractions
● Nearley
● Example: Fraction calculator
Rajiv Patel, https://tinyurl.com/yx6rmcdt
What is parsing?
You know the problem
● What is syntax?
● How is the syntax defined?
● How do you check if input
matches syntax?
● How can you use the syntax
in your applications?
https://xkcd.com/859/
Grammar
● The syntax is defined by a grammar
● Lexical analysis breaks down input into
tokens or terminals
○ Keywords, literals, identifiers, operators
● A set of rules connecting non-terminals to
tokens
● One non-terminal is the start symbol
● Parsers are software which use a grammar
to verify input
keyword
identifier
Body: statements
Example
● S → AA
● A → 𝞪
● A → 𝞫
Matches 𝞪𝞪, 𝞪𝞫, 𝞫𝞪, and 𝞫𝞫
function add2(n) {
let r = n + 2;
return r;
}
Ken Whytock, https://tinyurl.com/s9s3eee
literal
Parser generators
● Many well-documented algorithms exist
○ Hot research topics in 1960s and 1970s
● It’s not a trivial task to write a parser
● Parser generators can speed up development
process
○ Yacc (C) - 1975!!
○ ANTLR (mostly Java) - 1989
○ Nearley (JavaScript) - 2014
Erica Zabowski, https://tinyurl.com/uqbaldv
Fractions
Quick recap
● A fraction is a rational number
○ Numerator and denominator, both natural numbers
○ Broken latin (fractus, broken)
● Fractions are rational numbers
Bill Ward, https://tinyurl.com/r3dtp2b
Arithmetic
Greatest Common Divisor
● Original algorithm by Euclid (c. 300 BC)
● Often used to reduce or simplify a fraction
● https://en.wikipedia.org/wiki/Greatest_common_divisor
Nearley
Earley Parsers in JavaScript
● Nearley implements Earley’s parser algorithm
○ Left-recursive (LR) grammars
○ Deterministic parser
○ Worst-case performance O(n3
) but O(n) for well-behaving grammars
○ https://en.wikipedia.org/wiki/Earley_parser
● Can generate JavaScript, CoffeeScript, and TypeScript
○ Can run in browsers, node.js and probably React Native
● Inclusion of predefined grammars
○ Numbers, white spaces, strings
● Lexer is also included
○ Define tokens using double-quotes
● Rules can have (semantic) actions
○ Plain JavaScript functions
How to use
● Easy installation: npm install nearley --save-dev
● Generate a parser: npx nearleyc -o parser.js parser.ne
○ Add to scripts in package.json
● The .ne files contains rules, terminals, non-terminals, and actions
expr -> "(" _ sum _ ")" {% function (d) { return d[2]; }
%}
| value {% function (d) { return d[0]; }
%}
Non-terminal Terminal Whitespace Action The return value
from the sum rule
Additional tools
Supported by many editors
● VS Code, Atom, Emacs, Vim, Sublime
Railroad diagrams
Example:
Fraction
calculator
kalculator
● Simple Fraction class
○ Basic arithmetic and simplification
● Parser
○ Actions to perform calculation
● Little driver to read input and call parser
The grammar (no actions)
main → sum
expr → ( sum )
| value
product → product * expr
| product / expr
| value
sum → sum + expr
| sum - expr
| product
value → fraction
| int
fraction → int / int
Start symbol: main
Tokens: (, ), +, -, *, /
Positive integer: int
Important take-aways
● Recursive rules
● Operator precedence
Source code:
parser.ne
Source code: kalc.js
Resources
Links
● My example: https://github.com/kneth/kalculator
● Nearley: https://nearley.js.org/
● Earley parsers explained: http://loup-vaillant.fr/tutorials/earley-parsing/
● An Efficient Context-Free Parsing Algorithm. Jay Earley’s Ph.D. thesis from
1968.
http://reports-archive.adm.cs.cmu.edu/anon/anon/usr/ftp/scan/CMU-CS-68-earl
ey.pdf
Building parsers
for JavaScript is
easy - and fun
Ron Mader, https://tinyurl.com/sg5pdwn

Contenu connexe

Tendances

Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Ovidiu Farauanu
 
Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11Åsa Pehrsson
 
Introduction to Object Oriented Javascript
Introduction to Object Oriented JavascriptIntroduction to Object Oriented Javascript
Introduction to Object Oriented Javascriptnodeninjas
 
Grant Rogerson SDEC2015
Grant Rogerson SDEC2015Grant Rogerson SDEC2015
Grant Rogerson SDEC2015Grant Rogerson
 
Smalltalk, the dynamic language
Smalltalk, the dynamic languageSmalltalk, the dynamic language
Smalltalk, the dynamic languagemohamedsamyali
 
A Shallow Survey of Alternative Languages on the JVM
A Shallow Survey of Alternative Languages on the JVMA Shallow Survey of Alternative Languages on the JVM
A Shallow Survey of Alternative Languages on the JVMCharles Anderson
 
Lambda expression par Christophe Huntzinger
Lambda expression par Christophe HuntzingerLambda expression par Christophe Huntzinger
Lambda expression par Christophe HuntzingerMik_Arber
 
Introduction to Smalltalk
Introduction to SmalltalkIntroduction to Smalltalk
Introduction to Smalltalkkim.mens
 
Php Inspections (EA Extended): if-conditions optimization
Php Inspections (EA Extended): if-conditions optimizationPhp Inspections (EA Extended): if-conditions optimization
Php Inspections (EA Extended): if-conditions optimizationVladimir Reznichenko
 
A hierarchical neural autoencoder for paragraphs and documents
A hierarchical neural autoencoder for paragraphs and documentsA hierarchical neural autoencoder for paragraphs and documents
A hierarchical neural autoencoder for paragraphs and documentsHayahide Yamagishi
 
Groovy / comparison with java
Groovy / comparison with javaGroovy / comparison with java
Groovy / comparison with javaLiviu Tudor
 
Kotlin functional programming basic@Kotlin TW study group
Kotlin  functional programming basic@Kotlin TW study groupKotlin  functional programming basic@Kotlin TW study group
Kotlin functional programming basic@Kotlin TW study groupJulian Yu-Lang Chu
 
How to check valid email? Find using regex(p?)
How to check valid email? Find using regex(p?)How to check valid email? Find using regex(p?)
How to check valid email? Find using regex(p?)Visuality
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17Daniel Eriksson
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016maiktoepfer
 

Tendances (20)

Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
 
Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11
 
Introduction to Object Oriented Javascript
Introduction to Object Oriented JavascriptIntroduction to Object Oriented Javascript
Introduction to Object Oriented Javascript
 
Grant Rogerson SDEC2015
Grant Rogerson SDEC2015Grant Rogerson SDEC2015
Grant Rogerson SDEC2015
 
Smalltalk, the dynamic language
Smalltalk, the dynamic languageSmalltalk, the dynamic language
Smalltalk, the dynamic language
 
JavaScript Data Types
JavaScript Data TypesJavaScript Data Types
JavaScript Data Types
 
A Shallow Survey of Alternative Languages on the JVM
A Shallow Survey of Alternative Languages on the JVMA Shallow Survey of Alternative Languages on the JVM
A Shallow Survey of Alternative Languages on the JVM
 
Lambda expression par Christophe Huntzinger
Lambda expression par Christophe HuntzingerLambda expression par Christophe Huntzinger
Lambda expression par Christophe Huntzinger
 
Introduction to Smalltalk
Introduction to SmalltalkIntroduction to Smalltalk
Introduction to Smalltalk
 
Php Inspections (EA Extended): if-conditions optimization
Php Inspections (EA Extended): if-conditions optimizationPhp Inspections (EA Extended): if-conditions optimization
Php Inspections (EA Extended): if-conditions optimization
 
A hierarchical neural autoencoder for paragraphs and documents
A hierarchical neural autoencoder for paragraphs and documentsA hierarchical neural autoencoder for paragraphs and documents
A hierarchical neural autoencoder for paragraphs and documents
 
Lambdas HOL
Lambdas HOLLambdas HOL
Lambdas HOL
 
Groovy / comparison with java
Groovy / comparison with javaGroovy / comparison with java
Groovy / comparison with java
 
Kotlin functional programming basic@Kotlin TW study group
Kotlin  functional programming basic@Kotlin TW study groupKotlin  functional programming basic@Kotlin TW study group
Kotlin functional programming basic@Kotlin TW study group
 
Learn JavaScript From Scratch
Learn JavaScript From ScratchLearn JavaScript From Scratch
Learn JavaScript From Scratch
 
How to check valid email? Find using regex(p?)
How to check valid email? Find using regex(p?)How to check valid email? Find using regex(p?)
How to check valid email? Find using regex(p?)
 
JavaScript Bootcamp
JavaScript BootcampJavaScript Bootcamp
JavaScript Bootcamp
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 

Similaire à Building parsers in JavaScript

Lint, coverage, doc, autocompletion, transpilation, minification... powered b...
Lint, coverage, doc, autocompletion, transpilation, minification... powered b...Lint, coverage, doc, autocompletion, transpilation, minification... powered b...
Lint, coverage, doc, autocompletion, transpilation, minification... powered b...Alexandre Morgaut
 
Sharable of qualities of clean code
Sharable of qualities of clean codeSharable of qualities of clean code
Sharable of qualities of clean codeEman Mohamed
 
Custom Pregel Algorithms in ArangoDB
Custom Pregel Algorithms in ArangoDBCustom Pregel Algorithms in ArangoDB
Custom Pregel Algorithms in ArangoDBArangoDB Database
 
Anatomy of spark catalyst
Anatomy of spark catalystAnatomy of spark catalyst
Anatomy of spark catalystdatamantra
 
Design and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageDesign and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageAsankhaya Sharma
 
HelsinkiJS - Clojurescript for Javascript Developers
HelsinkiJS - Clojurescript for Javascript DevelopersHelsinkiJS - Clojurescript for Javascript Developers
HelsinkiJS - Clojurescript for Javascript DevelopersJuho Teperi
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScriptJorg Janke
 
C# as a System Language
C# as a System LanguageC# as a System Language
C# as a System LanguageScyllaDB
 
Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)Kai Chan
 
Dart the better Javascript 2015
Dart the better Javascript 2015Dart the better Javascript 2015
Dart the better Javascript 2015Jorg Janke
 

Similaire à Building parsers in JavaScript (20)

04-JS.pptx
04-JS.pptx04-JS.pptx
04-JS.pptx
 
04-JS.pptx
04-JS.pptx04-JS.pptx
04-JS.pptx
 
04-JS.pptx
04-JS.pptx04-JS.pptx
04-JS.pptx
 
Lint, coverage, doc, autocompletion, transpilation, minification... powered b...
Lint, coverage, doc, autocompletion, transpilation, minification... powered b...Lint, coverage, doc, autocompletion, transpilation, minification... powered b...
Lint, coverage, doc, autocompletion, transpilation, minification... powered b...
 
Sharable of qualities of clean code
Sharable of qualities of clean codeSharable of qualities of clean code
Sharable of qualities of clean code
 
Extending Node.js using C++
Extending Node.js using C++Extending Node.js using C++
Extending Node.js using C++
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Custom Pregel Algorithms in ArangoDB
Custom Pregel Algorithms in ArangoDBCustom Pregel Algorithms in ArangoDB
Custom Pregel Algorithms in ArangoDB
 
Anatomy of spark catalyst
Anatomy of spark catalystAnatomy of spark catalyst
Anatomy of spark catalyst
 
Design and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageDesign and Implementation of the Security Graph Language
Design and Implementation of the Security Graph Language
 
ActiveDoc
ActiveDocActiveDoc
ActiveDoc
 
HelsinkiJS - Clojurescript for Javascript Developers
HelsinkiJS - Clojurescript for Javascript DevelopersHelsinkiJS - Clojurescript for Javascript Developers
HelsinkiJS - Clojurescript for Javascript Developers
 
Go_ Get iT! .pdf
Go_ Get iT! .pdfGo_ Get iT! .pdf
Go_ Get iT! .pdf
 
Python for web security - beginner
Python for web security - beginnerPython for web security - beginner
Python for web security - beginner
 
ANTLR4 in depth
ANTLR4 in depthANTLR4 in depth
ANTLR4 in depth
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScript
 
C# as a System Language
C# as a System LanguageC# as a System Language
C# as a System Language
 
Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)
 
Dart the better Javascript 2015
Dart the better Javascript 2015Dart the better Javascript 2015
Dart the better Javascript 2015
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
 

Plus de Kenneth Geisshirt

Building mobile apps with Realm for React Native
Building mobile apps with Realm for React NativeBuilding mobile apps with Realm for React Native
Building mobile apps with Realm for React NativeKenneth Geisshirt
 
Tales from the dark side: developing SDKs at scale
Tales from the dark side: developing SDKs at scaleTales from the dark side: developing SDKs at scale
Tales from the dark side: developing SDKs at scaleKenneth Geisshirt
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboyKenneth Geisshirt
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeKenneth Geisshirt
 
Is the database a solved problem?
Is the database a solved problem?Is the database a solved problem?
Is the database a solved problem?Kenneth Geisshirt
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboyKenneth Geisshirt
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Kenneth Geisshirt
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboyKenneth Geisshirt
 
Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012Kenneth Geisshirt
 
Hadoop - the data scientist's toolbox
Hadoop - the data scientist's toolboxHadoop - the data scientist's toolbox
Hadoop - the data scientist's toolboxKenneth Geisshirt
 
JavaScript/Emacs integration
JavaScript/Emacs integrationJavaScript/Emacs integration
JavaScript/Emacs integrationKenneth Geisshirt
 
Introduction to JavaScript for Modern Software Development
Introduction to JavaScript for Modern Software DevelopmentIntroduction to JavaScript for Modern Software Development
Introduction to JavaScript for Modern Software DevelopmentKenneth Geisshirt
 

Plus de Kenneth Geisshirt (18)

Open Source in Real Life
Open Source in Real LifeOpen Source in Real Life
Open Source in Real Life
 
Building mobile apps with Realm for React Native
Building mobile apps with Realm for React NativeBuilding mobile apps with Realm for React Native
Building mobile apps with Realm for React Native
 
micro:bit and JavaScript
micro:bit and JavaScriptmicro:bit and JavaScript
micro:bit and JavaScript
 
Tales from the dark side: developing SDKs at scale
Tales from the dark side: developing SDKs at scaleTales from the dark side: developing SDKs at scale
Tales from the dark side: developing SDKs at scale
 
Android things
Android thingsAndroid things
Android things
 
Node.js extensions in C++
Node.js extensions in C++Node.js extensions in C++
Node.js extensions in C++
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native code
 
Is the database a solved problem?
Is the database a solved problem?Is the database a solved problem?
Is the database a solved problem?
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++
 
Sociale netværk
Sociale netværkSociale netværk
Sociale netværk
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012
 
Hadoop - the data scientist's toolbox
Hadoop - the data scientist's toolboxHadoop - the data scientist's toolbox
Hadoop - the data scientist's toolbox
 
JavaScript/Emacs integration
JavaScript/Emacs integrationJavaScript/Emacs integration
JavaScript/Emacs integration
 
Introduction to JavaScript for Modern Software Development
Introduction to JavaScript for Modern Software DevelopmentIntroduction to JavaScript for Modern Software Development
Introduction to JavaScript for Modern Software Development
 
Kendthed og vigtighed
Kendthed og vigtighedKendthed og vigtighed
Kendthed og vigtighed
 

Dernier

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 

Dernier (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 

Building parsers in JavaScript

  • 1. Building parsers in JavaScript Kenneth Geisshirt kneth kgeisshirt
  • 2. Agenda ● What is parsing? ● Fractions ● Nearley ● Example: Fraction calculator Rajiv Patel, https://tinyurl.com/yx6rmcdt
  • 4. You know the problem ● What is syntax? ● How is the syntax defined? ● How do you check if input matches syntax? ● How can you use the syntax in your applications? https://xkcd.com/859/
  • 5. Grammar ● The syntax is defined by a grammar ● Lexical analysis breaks down input into tokens or terminals ○ Keywords, literals, identifiers, operators ● A set of rules connecting non-terminals to tokens ● One non-terminal is the start symbol ● Parsers are software which use a grammar to verify input keyword identifier Body: statements Example ● S → AA ● A → 𝞪 ● A → 𝞫 Matches 𝞪𝞪, 𝞪𝞫, 𝞫𝞪, and 𝞫𝞫 function add2(n) { let r = n + 2; return r; } Ken Whytock, https://tinyurl.com/s9s3eee literal
  • 6. Parser generators ● Many well-documented algorithms exist ○ Hot research topics in 1960s and 1970s ● It’s not a trivial task to write a parser ● Parser generators can speed up development process ○ Yacc (C) - 1975!! ○ ANTLR (mostly Java) - 1989 ○ Nearley (JavaScript) - 2014 Erica Zabowski, https://tinyurl.com/uqbaldv
  • 8. Quick recap ● A fraction is a rational number ○ Numerator and denominator, both natural numbers ○ Broken latin (fractus, broken) ● Fractions are rational numbers Bill Ward, https://tinyurl.com/r3dtp2b
  • 9. Arithmetic Greatest Common Divisor ● Original algorithm by Euclid (c. 300 BC) ● Often used to reduce or simplify a fraction ● https://en.wikipedia.org/wiki/Greatest_common_divisor
  • 11. Earley Parsers in JavaScript ● Nearley implements Earley’s parser algorithm ○ Left-recursive (LR) grammars ○ Deterministic parser ○ Worst-case performance O(n3 ) but O(n) for well-behaving grammars ○ https://en.wikipedia.org/wiki/Earley_parser ● Can generate JavaScript, CoffeeScript, and TypeScript ○ Can run in browsers, node.js and probably React Native ● Inclusion of predefined grammars ○ Numbers, white spaces, strings ● Lexer is also included ○ Define tokens using double-quotes ● Rules can have (semantic) actions ○ Plain JavaScript functions
  • 12. How to use ● Easy installation: npm install nearley --save-dev ● Generate a parser: npx nearleyc -o parser.js parser.ne ○ Add to scripts in package.json ● The .ne files contains rules, terminals, non-terminals, and actions expr -> "(" _ sum _ ")" {% function (d) { return d[2]; } %} | value {% function (d) { return d[0]; } %} Non-terminal Terminal Whitespace Action The return value from the sum rule
  • 13. Additional tools Supported by many editors ● VS Code, Atom, Emacs, Vim, Sublime Railroad diagrams
  • 15. kalculator ● Simple Fraction class ○ Basic arithmetic and simplification ● Parser ○ Actions to perform calculation ● Little driver to read input and call parser
  • 16. The grammar (no actions) main → sum expr → ( sum ) | value product → product * expr | product / expr | value sum → sum + expr | sum - expr | product value → fraction | int fraction → int / int Start symbol: main Tokens: (, ), +, -, *, / Positive integer: int Important take-aways ● Recursive rules ● Operator precedence
  • 20. Links ● My example: https://github.com/kneth/kalculator ● Nearley: https://nearley.js.org/ ● Earley parsers explained: http://loup-vaillant.fr/tutorials/earley-parsing/ ● An Efficient Context-Free Parsing Algorithm. Jay Earley’s Ph.D. thesis from 1968. http://reports-archive.adm.cs.cmu.edu/anon/anon/usr/ftp/scan/CMU-CS-68-earl ey.pdf
  • 21. Building parsers for JavaScript is easy - and fun