SlideShare a Scribd company logo
1 of 41
Download to read offline
Mastering Grammars
          with




      Lukas Renggli
http://dsal.cl/~jfabry/pp/
Agenda


1. PetitParser in a Nutshell
2. Combinatorial Parsing
3. Complex Grammars
4. Advanced Use
in a Nutshell
ID	
  ::=	
  letter	
  {	
  letter	
  |	
  digit	
  }	
  ;




              a..z                 a..z
                                  0..9
ID	
  ::=	
  letter	
  {	
  letter	
  |	
  digit	
  }	
  ;


                    sequence

             letter           many

                              choice

                         letter      digit
id	
  :=	
  #letter	
  asParser	
  ,	
  
(#letter	
  asParser	
  /	
  #digit	
  asParser)	
  star


                    sequence

               letter        many

                            choice

                         letter   digit
id	
  parse:	
  'yeah'.
	
   "	
  -­‐-­‐>	
  #($y	
  #($e	
  $a	
  $h))	
  "

id	
  parse:	
  'f12'.
	
   "	
  -­‐-­‐>	
  #($f	
  #($1	
  $2))	
  "

id	
  parse:	
  '123'.
	
   "	
  -­‐-­‐>	
  letter	
  expected	
  at	
  0	
  "
Example 1

‣ Test the identifier parser
‣ Inspect the parser object
‣ Create and test an integer parser
Combinatorial Parsing
Parser Terminals
     $a	
  asParser
                  letter ‘a’

     'abc'	
  asParser
               string ‘abc’

These factory methods are defined in
 PPPredicateObjectParser	
  class

     #any	
  asParser	                any character

     #digit	
  asParser	              the digits 0..9

     #letter	
  asParser	             the letters a..z and A..Z



     nil	
  asParser	                 the empty parser
Parser Operators
p1	
  ,	
  p2	
             sequence

p1	
  /	
  p2	
             ordered choice



p	
  star	
                 zero-or-more (0..*)

p	
  plus	
                 one-or-more (1..*)

p	
  optional	
             zero-or-one (0..1)


                             see the operations
p1	
  separatedBy:	
  p2
                           protocols in PPParser
p1	
  delimitedBy:	
  p2     for more operators
Parser Predicates


p	
  and	
             conjunction

                      (non-consuming look-ahead)

p	
  not	
             negation

                      (non-consuming look-ahead)


p	
  end	
             end of input
Parser Actions


     p	
  ==>	
  [	
  :arg	
  |	
  	
  	
  ]	   transformation	
  



     p	
  flatten	
                             create string

     p	
  token	
                               create token

     p	
  trim	                                 trim whitespaces

see the operations-mapping
   protocol in PPParser
      for more actions
term	
  	
  	
  	
  	
  ::=	
  prod	
  "+"	
  term	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  |	
  prod	
  ;

prod	
  	
  	
  	
  	
  ::=	
  prim	
  "*"	
  prod
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  |	
  prim	
  ;

prim	
  	
  	
  	
  	
  ::=	
  "("	
  term	
  ")"
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  |	
  number	
  ;

number	
  	
  	
  ::=	
  "0"	
  ..	
  "9"	
  ;
number	
  :=	
  	
  #digit	
  asParser	
  plus	
  flatten	
  trim
	
   ==>	
  [	
  :string	
  |	
  string	
  asNumber	
  ].

term	
  :=	
  PPUnresolvedParser	
  new.
prod	
  :=	
  PPUnresolvedParser	
  new.
prim	
  :=	
  PPUnresolvedParser	
  new.
	
  
term	
  def:	
  (prod	
  ,	
  $+	
  asParser	
  trim	
  ,	
  term	
  
	
   ==>	
  [	
  :nodes	
  |	
  nodes	
  first	
  +	
  nodes	
  last	
  ])
	
  	
  	
  /	
  prod.
prod	
  def:	
  (prim	
  ,	
  $*	
  asParser	
  trim	
  ,	
  prod
	
   ==>	
  [	
  :nodes	
  |	
  nodes	
  first	
  *	
  nodes	
  last	
  ])
	
  	
  	
  /	
  prim.
prim	
  def:	
  ($(	
  asParser	
  trim	
  ,	
  term	
  ,	
  $)	
  asParser	
  trim
	
   ==>	
  [	
  :nodes	
  |	
  nodes	
  second	
  ])
	
  	
  	
  /	
  number.

start	
  :=	
  term	
  end.
start	
  parse:	
  '1	
  +	
  2	
  *	
  3'.	
  	
  	
  
                                                    	
  
	
   "	
  -­‐-­‐>	
  7	
  "

start	
  parse:	
  '(1	
  +	
  2)	
  *	
  3'.	
  
                                              	
  
	
   "	
  -­‐-­‐>	
  9	
  "
Example 2

‣ Add support for negative numbers
‣ Add support for floating point numbers
‣ Add support for subtraction & division
Complex Grammars
PetitParser Scripts
to
qu ick
  wr ite


PetitParser Scripts
    embe
         d in
    Smal      to
         ltalk
to
    qu ick        d iffic
                        ult
      wr ite      to reu
                         se

   PetitParser Scripts
         embe           messy
 hard         d in
                   to if large
         Smal
to tes t      ltalk
PPCompositeParser
start
PPCompositeParser
start



 ExpressionGrammar
start
term
prod
...
One Method per Production

    PPCompositeParser
  start



   ExpressionGrammar
   start   start
   term    	
  	
  	
  ^	
  term	
  end
   prod
   ...
One Instance Variable per Production

        PPCompositeParser
       start



        ExpressionGrammar
       start
               term
       term
               	
  	
  	
  ^	
  (prod	
  ,	
  $+	
  asParser	
  t
       prod
               	
  	
  	
  	
  /	
  prod
       ...
Refer to Productions by Inst-Var Reference

           PPCompositeParser
          start



           ExpressionGrammar
          start
          term
                  prod
          prod
                  	
  	
  	
  ^	
  (prim	
  ,	
  $*	
  asParser	
  t
          ...
                  	
  	
  	
  	
  /	
  prim
res t
                            is
 PPCompositeParser   mag
                           ic
start



 ExpressionGrammar
start
term
prod
...
ExpressionGrammar
start
term
prod
...



ExpressionEvaluator
term
prod
number
...
Example 3

‣ Implement an expression grammar
‣ Implement an expression evaluator
‣ Implement an expression pretty printer
Advanced Use
does not just
work on Strings
Matching

p	
  matches:	
  'abc'.


p	
  matchesIn:	
  'abc'.	
  
p	
  matchesIn:	
  'abc'	
  do:	
  [	
  :each	
  |	
  	
  	
  ].


p	
  matchingRangesIn:	
  'abc'.
p	
  matchingRangesIn:	
  'abc'	
  do:	
  [	
  :interval	
  |	
  	
  	
  ].	
  
World ➔ Tools ➔
  PetitParser     GUI   PPBrowser	
  open
Reflection


p	
  allParser.
p	
  allParserDo:	
  [	
  :each	
  |	
  	
  	
  ].


p	
  firstSet.	
  
p	
  followSet.
p	
  cycleSet.
Transformations



p	
  replace:	
  p1	
  with:	
  p2.
p	
  transform:	
  [	
  :parser	
  |	
  	
  	
  ].


    Like #collect: on Collection, but
   transforms the whole grammar graph.
Pattern Searching

                       A placeholder
                     matching any parser

found	
  :=	
  PPSearcher	
  new
	
   matches:	
  PPPattern	
  any	
  star	
  plus	
  
	
   do:	
  [	
  :parser	
  :answer	
  |	
  parser	
  ];
	
   execute:	
  p	
  initialAnswer:	
  nil


            Grammar to
            be searched
Pattern Rewriting
Same pattern used in
 search and replace.

 pattern	
  :=	
  PPPattern	
  any.
 rewritten	
  :=	
  PPRewriter	
  new
 	
   replace:	
  pattern	
  star	
  plus
 	
   with:	
  pattern	
  star;
 	
   execute:	
  p


            Grammar to
            be rewritten
Grammar Optimization




        fast	
  :=	
  slow	
  optimize



   Many behavior preserving
  rewrite rules applied for you.
3000000




            2000000
chars/sec




            1000000




                  0
                      LALR      PetitParser       Hand-Written


                       Old VM            Cog VM
www.lukas-renggli.ch

More Related Content

What's hot

UNIX - Class5 - Advance Shell Scripting-P2
UNIX - Class5 - Advance Shell Scripting-P2UNIX - Class5 - Advance Shell Scripting-P2
UNIX - Class5 - Advance Shell Scripting-P2Nihar Ranjan Paital
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Samuel Fortier-Galarneau
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in PythonBen James
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functionsmussawir20
 
Write Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 HoursWrite Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 HoursPhillip Trelford
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageGiuseppe Arici
 
Hacking Parse.y with ujihisa
Hacking Parse.y with ujihisaHacking Parse.y with ujihisa
Hacking Parse.y with ujihisaujihisa
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014Phillip Trelford
 
CGI With Object Oriented Perl
CGI With Object Oriented PerlCGI With Object Oriented Perl
CGI With Object Oriented PerlBunty Ray
 
Python decorators
Python decoratorsPython decorators
Python decoratorsAlex Su
 
Learning sed and awk
Learning sed and awkLearning sed and awk
Learning sed and awkYogesh Sawant
 

What's hot (20)

UNIX - Class5 - Advance Shell Scripting-P2
UNIX - Class5 - Advance Shell Scripting-P2UNIX - Class5 - Advance Shell Scripting-P2
UNIX - Class5 - Advance Shell Scripting-P2
 
Subroutines
SubroutinesSubroutines
Subroutines
 
Awk programming
Awk programming Awk programming
Awk programming
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
 
Awk essentials
Awk essentialsAwk essentials
Awk essentials
 
Write Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 HoursWrite Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 Hours
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
Cleancode
CleancodeCleancode
Cleancode
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Hacking Parse.y with ujihisa
Hacking Parse.y with ujihisaHacking Parse.y with ujihisa
Hacking Parse.y with ujihisa
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
 
CGI With Object Oriented Perl
CGI With Object Oriented PerlCGI With Object Oriented Perl
CGI With Object Oriented Perl
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Learning sed and awk
Learning sed and awkLearning sed and awk
Learning sed and awk
 
Maintainable go
Maintainable goMaintainable go
Maintainable go
 
Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
 

Viewers also liked

Magritte - A Meta-Driven Approach to Empower Developers and End Users
Magritte - A Meta-Driven Approach to Empower Developers and End UsersMagritte - A Meta-Driven Approach to Empower Developers and End Users
Magritte - A Meta-Driven Approach to Empower Developers and End UsersLukas Renggli
 
Seaside — Agile Software Development
Seaside — Agile Software DevelopmentSeaside — Agile Software Development
Seaside — Agile Software DevelopmentLukas Renggli
 
Natural Language Checking with Program Checking Tools
Natural Language Checking with Program Checking ToolsNatural Language Checking with Program Checking Tools
Natural Language Checking with Program Checking ToolsLukas Renggli
 
The Dynamic Language is not Enough
The Dynamic Language is not EnoughThe Dynamic Language is not Enough
The Dynamic Language is not EnoughLukas Renggli
 
Dynamic Language Embedding With Homogeneous Tool Support
Dynamic Language Embedding With Homogeneous Tool SupportDynamic Language Embedding With Homogeneous Tool Support
Dynamic Language Embedding With Homogeneous Tool SupportLukas Renggli
 
The Great State of Design with CSS Grid Layout and Friends
The Great State of Design with CSS Grid Layout and FriendsThe Great State of Design with CSS Grid Layout and Friends
The Great State of Design with CSS Grid Layout and FriendsStacy Kvernmo
 

Viewers also liked (8)

Magritte - A Meta-Driven Approach to Empower Developers and End Users
Magritte - A Meta-Driven Approach to Empower Developers and End UsersMagritte - A Meta-Driven Approach to Empower Developers and End Users
Magritte - A Meta-Driven Approach to Empower Developers and End Users
 
Seaside — Agile Software Development
Seaside — Agile Software DevelopmentSeaside — Agile Software Development
Seaside — Agile Software Development
 
Natural Language Checking with Program Checking Tools
Natural Language Checking with Program Checking ToolsNatural Language Checking with Program Checking Tools
Natural Language Checking with Program Checking Tools
 
The Dynamic Language is not Enough
The Dynamic Language is not EnoughThe Dynamic Language is not Enough
The Dynamic Language is not Enough
 
Magritte
MagritteMagritte
Magritte
 
Dynamic Language Embedding With Homogeneous Tool Support
Dynamic Language Embedding With Homogeneous Tool SupportDynamic Language Embedding With Homogeneous Tool Support
Dynamic Language Embedding With Homogeneous Tool Support
 
Magritte Blitz
Magritte BlitzMagritte Blitz
Magritte Blitz
 
The Great State of Design with CSS Grid Layout and Friends
The Great State of Design with CSS Grid Layout and FriendsThe Great State of Design with CSS Grid Layout and Friends
The Great State of Design with CSS Grid Layout and Friends
 

Similar to Mastering Grammars with PetitParser

Parsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix KliuchnikovParsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix KliuchnikovVasil Remeniuk
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserYodalee
 
An introduction to Raku
An introduction to RakuAn introduction to Raku
An introduction to RakuSimon Proctor
 
Perl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one linersPerl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one linersKirk Kimmel
 
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...Adam Mukharil Bachtiar
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1Dave Cross
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n2
name name2 n2name name2 n2
name name2 n2callroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.pptcallroom
 

Similar to Mastering Grammars with PetitParser (20)

Parsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix KliuchnikovParsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language Parser
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
Ch2
Ch2Ch2
Ch2
 
An introduction to Raku
An introduction to RakuAn introduction to Raku
An introduction to Raku
 
Perl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one linersPerl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one liners
 
Ch2 (1).ppt
Ch2 (1).pptCh2 (1).ppt
Ch2 (1).ppt
 
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
test ppt
test ppttest ppt
test ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt21
ppt21ppt21
ppt21
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt17
ppt17ppt17
ppt17
 
ppt30
ppt30ppt30
ppt30
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.ppt
 

More from Lukas Renggli

Domain-Specific Program Checking
Domain-Specific Program CheckingDomain-Specific Program Checking
Domain-Specific Program CheckingLukas Renggli
 
Embedding Languages Without Breaking Tools
Embedding Languages Without Breaking ToolsEmbedding Languages Without Breaking Tools
Embedding Languages Without Breaking ToolsLukas Renggli
 
Language Boxes — Bending the Host Language with Modular Language Changes
Language Boxes — Bending the Host Language with Modular Language ChangesLanguage Boxes — Bending the Host Language with Modular Language Changes
Language Boxes — Bending the Host Language with Modular Language ChangesLukas Renggli
 
Seaside Status Message
Seaside Status MessageSeaside Status Message
Seaside Status MessageLukas Renggli
 
Seaside - The Revenge of Smalltalk
Seaside - The Revenge of SmalltalkSeaside - The Revenge of Smalltalk
Seaside - The Revenge of SmalltalkLukas Renggli
 
Seaside - On not getting bogged down
Seaside - On not getting bogged downSeaside - On not getting bogged down
Seaside - On not getting bogged downLukas Renggli
 
Seaside - Past, Present and Future
Seaside - Past, Present and FutureSeaside - Past, Present and Future
Seaside - Past, Present and FutureLukas Renggli
 
Transactional Memory for Smalltalk
Transactional Memory for SmalltalkTransactional Memory for Smalltalk
Transactional Memory for SmalltalkLukas Renggli
 
Seaside - Web Development As You Like It
Seaside - Web Development As You Like ItSeaside - Web Development As You Like It
Seaside - Web Development As You Like ItLukas Renggli
 
5 Steps to Mastering the Art of Seaside
5 Steps to Mastering the Art of Seaside5 Steps to Mastering the Art of Seaside
5 Steps to Mastering the Art of SeasideLukas Renggli
 

More from Lukas Renggli (12)

Dynamic grammars
Dynamic grammarsDynamic grammars
Dynamic grammars
 
Domain-Specific Program Checking
Domain-Specific Program CheckingDomain-Specific Program Checking
Domain-Specific Program Checking
 
Embedding Languages Without Breaking Tools
Embedding Languages Without Breaking ToolsEmbedding Languages Without Breaking Tools
Embedding Languages Without Breaking Tools
 
Language Boxes — Bending the Host Language with Modular Language Changes
Language Boxes — Bending the Host Language with Modular Language ChangesLanguage Boxes — Bending the Host Language with Modular Language Changes
Language Boxes — Bending the Host Language with Modular Language Changes
 
jQuery for Seaside
jQuery for SeasidejQuery for Seaside
jQuery for Seaside
 
Seaside Status Message
Seaside Status MessageSeaside Status Message
Seaside Status Message
 
Seaside - The Revenge of Smalltalk
Seaside - The Revenge of SmalltalkSeaside - The Revenge of Smalltalk
Seaside - The Revenge of Smalltalk
 
Seaside - On not getting bogged down
Seaside - On not getting bogged downSeaside - On not getting bogged down
Seaside - On not getting bogged down
 
Seaside - Past, Present and Future
Seaside - Past, Present and FutureSeaside - Past, Present and Future
Seaside - Past, Present and Future
 
Transactional Memory for Smalltalk
Transactional Memory for SmalltalkTransactional Memory for Smalltalk
Transactional Memory for Smalltalk
 
Seaside - Web Development As You Like It
Seaside - Web Development As You Like ItSeaside - Web Development As You Like It
Seaside - Web Development As You Like It
 
5 Steps to Mastering the Art of Seaside
5 Steps to Mastering the Art of Seaside5 Steps to Mastering the Art of Seaside
5 Steps to Mastering the Art of Seaside
 

Recently uploaded

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Recently uploaded (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Mastering Grammars with PetitParser

  • 1. Mastering Grammars with Lukas Renggli
  • 3. Agenda 1. PetitParser in a Nutshell 2. Combinatorial Parsing 3. Complex Grammars 4. Advanced Use
  • 5. ID  ::=  letter  {  letter  |  digit  }  ; a..z a..z 0..9
  • 6. ID  ::=  letter  {  letter  |  digit  }  ; sequence letter many choice letter digit
  • 7. id  :=  #letter  asParser  ,   (#letter  asParser  /  #digit  asParser)  star sequence letter many choice letter digit
  • 8. id  parse:  'yeah'.   "  -­‐-­‐>  #($y  #($e  $a  $h))  " id  parse:  'f12'.   "  -­‐-­‐>  #($f  #($1  $2))  " id  parse:  '123'.   "  -­‐-­‐>  letter  expected  at  0  "
  • 9. Example 1 ‣ Test the identifier parser ‣ Inspect the parser object ‣ Create and test an integer parser
  • 11. Parser Terminals $a  asParser letter ‘a’ 'abc'  asParser string ‘abc’ These factory methods are defined in PPPredicateObjectParser  class #any  asParser any character #digit  asParser the digits 0..9 #letter  asParser the letters a..z and A..Z nil  asParser the empty parser
  • 12. Parser Operators p1  ,  p2   sequence p1  /  p2   ordered choice p  star   zero-or-more (0..*) p  plus   one-or-more (1..*) p  optional   zero-or-one (0..1) see the operations p1  separatedBy:  p2 protocols in PPParser p1  delimitedBy:  p2 for more operators
  • 13. Parser Predicates p  and   conjunction (non-consuming look-ahead) p  not   negation (non-consuming look-ahead) p  end   end of input
  • 14. Parser Actions p  ==>  [  :arg  |      ] transformation   p  flatten   create string p  token   create token p  trim trim whitespaces see the operations-mapping protocol in PPParser for more actions
  • 15. term          ::=  prod  "+"  term                        |  prod  ; prod          ::=  prim  "*"  prod                      |  prim  ; prim          ::=  "("  term  ")"                      |  number  ; number      ::=  "0"  ..  "9"  ;
  • 16. number  :=    #digit  asParser  plus  flatten  trim   ==>  [  :string  |  string  asNumber  ]. term  :=  PPUnresolvedParser  new. prod  :=  PPUnresolvedParser  new. prim  :=  PPUnresolvedParser  new.   term  def:  (prod  ,  $+  asParser  trim  ,  term     ==>  [  :nodes  |  nodes  first  +  nodes  last  ])      /  prod. prod  def:  (prim  ,  $*  asParser  trim  ,  prod   ==>  [  :nodes  |  nodes  first  *  nodes  last  ])      /  prim. prim  def:  ($(  asParser  trim  ,  term  ,  $)  asParser  trim   ==>  [  :nodes  |  nodes  second  ])      /  number. start  :=  term  end.
  • 17. start  parse:  '1  +  2  *  3'.           "  -­‐-­‐>  7  " start  parse:  '(1  +  2)  *  3'.       "  -­‐-­‐>  9  "
  • 18. Example 2 ‣ Add support for negative numbers ‣ Add support for floating point numbers ‣ Add support for subtraction & division
  • 21. to qu ick wr ite PetitParser Scripts embe d in Smal to ltalk
  • 22. to qu ick d iffic ult wr ite to reu se PetitParser Scripts embe messy hard d in to if large Smal to tes t ltalk
  • 25. One Method per Production PPCompositeParser start ExpressionGrammar start start term      ^  term  end prod ...
  • 26. One Instance Variable per Production PPCompositeParser start ExpressionGrammar start term term      ^  (prod  ,  $+  asParser  t prod        /  prod ...
  • 27. Refer to Productions by Inst-Var Reference PPCompositeParser start ExpressionGrammar start term prod prod      ^  (prim  ,  $*  asParser  t ...        /  prim
  • 28. res t is PPCompositeParser mag ic start ExpressionGrammar start term prod ...
  • 30. Example 3 ‣ Implement an expression grammar ‣ Implement an expression evaluator ‣ Implement an expression pretty printer
  • 32. does not just work on Strings
  • 33. Matching p  matches:  'abc'. p  matchesIn:  'abc'.   p  matchesIn:  'abc'  do:  [  :each  |      ]. p  matchingRangesIn:  'abc'. p  matchingRangesIn:  'abc'  do:  [  :interval  |      ].  
  • 34. World ➔ Tools ➔ PetitParser GUI PPBrowser  open
  • 35. Reflection p  allParser. p  allParserDo:  [  :each  |      ]. p  firstSet.   p  followSet. p  cycleSet.
  • 36. Transformations p  replace:  p1  with:  p2. p  transform:  [  :parser  |      ]. Like #collect: on Collection, but transforms the whole grammar graph.
  • 37. Pattern Searching A placeholder matching any parser found  :=  PPSearcher  new   matches:  PPPattern  any  star  plus     do:  [  :parser  :answer  |  parser  ];   execute:  p  initialAnswer:  nil Grammar to be searched
  • 38. Pattern Rewriting Same pattern used in search and replace. pattern  :=  PPPattern  any. rewritten  :=  PPRewriter  new   replace:  pattern  star  plus   with:  pattern  star;   execute:  p Grammar to be rewritten
  • 39. Grammar Optimization fast  :=  slow  optimize Many behavior preserving rewrite rules applied for you.
  • 40. 3000000 2000000 chars/sec 1000000 0 LALR PetitParser Hand-Written Old VM Cog VM