开发者

An error of parser

I am writing a compiler in Ocaml. I want to realize something like that:

program test;
var
   a,b : boolean;
   n : integer;
name
   ([2,3], [4,5]) : boolean;
   ([7,8], [9,10]), ([12,13], [14,15]) : integer;  
begin
   ...
end.

Actually, each of my programs contains a 2-dimensional array. ([2,3], [4,5]) : b开发者_StackOverflow中文版oolean declares that all the elements in [2,3]x[4,5] is boolean.

My question is about how to let the parser read well the declaration of names, Here are my sib_parser.mly and sib_syntax.ml. They compile well, but when I test the binary with the program, it throws an error of parser. Could anyone help? Thank you very much!


You need to factorize your code a bit; the rules you show are not only ugly as hell to read, they have a lot of redundancy in them. For example, the two rules are basically the same, except for the latter terminal; you could easily have factorized that part out by a specific rule:

type_name:
| INTEGER { St_int }
| BOOLEAN { St_bool }

To answer your question, parameters in parametrized rules applications cannot be a sequence of terminal (what should the whole thing return ?), but only one "actual" which is either a terminal, a non-terminal, or the application of a parametrized rule. This forces you to break your grammar into separate productions, which is good.

%inline couple(open_sep,X,close_sep):
| open_sep x1 = X COMMA x2 = X close_sep { (x1, x2) }

rectangle:
| rect = couple(LPAREN, couple(LBRACKET, INT, RBRACKET), RPAREN) { rect }

type_name:
| INTEGER { St_int }
| BOOLEAN { St_bool }

binding_names:
| ids_names = separated_nonempty_list (COMMA, rectangle) COLON ty = type_name
    { [] (* put what you want here *) }

In this case, rectangle returns an (int * int) * (int * int).

PS: if you encounter a similar error again, do not hesitate to read the menhir documentation (PDF).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜