Representation of optional syntax and repetition with OcamlYacc / FsYacc

I am trying to create some skills in lexing / parsing grammar. I look back at the simple parser that I wrote for SQL, and I'm not quite happy with that - there seemed to be an easier way to write the parser.

SQL worked because it has a lot of extra tokens and repetitions. For example:

SELECT *
FROM t1
INNER JOIN t2
INNER JOIN t3
WHERE t1.ID = t2.ID and t1.ID = t3.ID

It is equivalent to:

SELECT *
FROM t1
INNER JOIN t2 ON t1.ID = t2.ID
INNER JOIN t3 on t1.ID = t3.ID

Offers ONand WHEREare optional and may occur more than once. I processed them in my parser as follows:

%{
open AST
%}

// ...    
%token <string> ID   
%token AND OR COMMA
%token EQ LT LE GT GE
%token JOIN INNER LEFT RIGHT ON
// ...

%%

op: EQ { Eq } | LT { Lt } | LE { Le } | GT { Gt } | GE { Ge }

// WHERE clause is optional    
whereClause:
    |                       { None }
    | WHERE whereList       { Some($2) }        

whereList:
    | ID op ID                    { Cond($1, $2, $3) }
    | ID op ID AND whereList      { And(Cond($1, $2, $3), $5) }
    | ID op ID OR whereList       { Or(Cond($1, $2, $3), $5) }


// Join clause is optional    
joinList:
    |                       { [] }
    | joinClause            { [$1] }
    | joinClause joinList   { $1 :: $2 }

joinClause:
    | INNER JOIN ID joinOnClause    { $3, Inner, $4 }
    | LEFT JOIN ID joinOnClause     { $3, Left, $4 }
    | RIGHT JOIN ID joinOnClause    { $3, Right, $4 }

// "On" clause is optional    
joinOnClause:
    |                       { None }
    | ON whereList          { Some($2) }

// ...
%%

, , . , , , .

, , * +. whereClause joinList :

whereClause:
    |                       { None }
//    $1    $2, I envision $2 being return as an (ID * op * ID * cond) list
    | WHERE [ ID op ID { (AND | OR) }]+
        { Some([for name1, op, name2, _ in $1 -> name1, op, name2]) }

joinClause:
    |                       { None }

//    $1, returned as (joinType
//                       * JOIN
//                       * ID
//                       * ((ID * op * ID) list) option) list
    | [ (INNER | LEFT | RIGHT) JOIN ID [ON whereClause] ]*
        { let joinType, _, table, onClause = $1;
          Some(table, joinType, onClause) }

, much , . , Ocaml F #, - .

OcamlYacc FsYacc?

+3
2

, - , . :

(INNER | RIGHT | LEFT ) 

inner_right_left

, .

. , camlp4, , . , , .

EDIT:

, camlp4 Camlp4 tutorial . , , , . , ocaml, , . .

+3

Menhir , , , . :

option(X): x=X { Some x} 
         | { None }

, ""? " ()", " +" "_list ()".

. ocamlbuild ocamlyacc. !

, SQL :)

+3

Source: https://habr.com/ru/post/1702995/


All Articles