6.1. top level parser

Start felix section to tut/tutorial/tut-5.01-0.flx[1 /1 ]
     1: #line 5428 "./lpsrc/flx_tutorial.pak"
     2: //Check parser generator
     3: #import <flx.flxh>
     4: 
     5: // a type for tokens
     6: union token_t =
     7:   | TOK_EOF
     8:   | TOK_PLUS
     9:   | TOK_INT of int
    10: ;
    11: 
    12: // a token stream generator
    13: gen get_token (s:string) ():token_t = {
    14:   var i: int; forall i in 0 upto (len s) - 1 do
    15:     yield
    16:       match s.[i to i+1] with
    17:       | "+" => TOK_PLUS
    18:       | "1" => TOK_INT 1
    19:       | "2" => TOK_INT 2
    20:       | "3" => TOK_INT 3
    21:       endmatch
    22:     ;
    23:   done;
    24:   return TOK_EOF;
    25: }
    26: 
    27: // a type for expression terms
    28: union expr_t =
    29:   | Integr of int
    30: ;
    31: 
    32: // a grammar for expressions
    33: nonterm eexpr : expr_t =
    34: | xx:eexpr TOK_PLUS y:TOK_INT =>
    35:   match xx with
    36:   | Integr ?i => Integr (i+y)
    37:   endmatch
    38: 
    39: | y:TOK_INT => Integr y
    40: ;
    41: 
    42: // the input string
    43: data := "1+2+3";
    44: 
    45: // a parser for our example
    46: var z : 1 + int =
    47:   parse get_token data with
    48:   | e: eexpr => match e with | Integr ?i => i endmatch
    49:   endmatch
    50: ;
    51: 
    52: // print the result
    53: match z with
    54: | case 0 => { print "Error"; }
    55: | case 1 (?i) => { print i; }
    56: endmatch;
    57: endl;
End felix section to tut/tutorial/tut-5.01-0.flx[1]
Start data section to tut/tutorial/tut-5.01-0.expect[1 /1 ]
     1: 6
End data section to tut/tutorial/tut-5.01-0.expect[1]