On this page:
parser

2 LALR(1) Parsers🔗ℹ

 (require parser-tools/yacc) package: parser-tools-lib

syntax

(parser clause ...)

 
clause = 
(grammar (non-terminal-id
          ((grammar-id ...) maybe-prec expr)
          ...)
         ...)
  | (tokens group-id ...)
  | (start non-terminal-id ...)
  | (end token-id ...)
  | (error expr)
  | (precs (assoc token-id ...) ...)
  | (src-pos)
  | (suppress)
  | (expected-SR-conflicts num)
  | (expected-RR-conflicts num)
  | (debug filename)
  | (yacc-output filename)
     
maybe-prec = 
  | (prec token-id)
     
assoc = left
  | right
  | nonassoc
Creates a parser. The clauses may be in any order, as long as there are no duplicates and all non-OPTIONAL declarations are present:

The result of a parser expression with one start non-terminal is a function, parse, that takes one argument. This argument must be a zero argument function, gen, that produces successive tokens of the input each time it is called. If desired, the gen may return symbols instead of tokens, and the parser will treat symbols as tokens of the corresponding name (with #f as a value, so it is usual to return symbols only in the case of empty tokens). The parse function returns the value associated with the parse tree by the semantic actions. If the parser encounters an error, after invoking the supplied error function, it will try to use error productions to continue parsing. If it cannot, it raises exn:fail:read.

If multiple non-terminals are provided in start, the parser expression produces a list of parsing functions, one for each non-terminal in the same order. Each parsing function is like the result of a parser expression with only one start non-terminal.

Each time the Racket code for a parser is compiled (e.g. when a ".rkt" file containing a parser form is loaded), the parser generator is run. To avoid this overhead place the parser into a module and compile the module to a ".zo" bytecode file.

Examples:
; Use the lexer and tokens from Tokens
; and the sample input from Creating a Lexer
> (define the-parser
    (parser
      [start expr]
      [end EOF]
      [error void]
      [tokens basic-tokens punct-tokens]
      [grammar
       [expr [(LPAREN exprs RPAREN) $2]
             [(NUM) $1]
             [(ID) $1]]
       [exprs [() '()]
              [(expr exprs) (cons $1 $2)]]]))
> (define p (open-input-string sample-input))
> (the-parser (λ () (the-lexer/tokens p)))

'(lambda (a) (add_number a 42))