问题描述:

I am writing a compiler of mini-pascal in Ocaml. I would like my compiler to accept the following code for instance:

program test;

var

a,b : boolean;

n : integer;

begin

...

end.

I have difficulties in dealing with the declaration of variables (the part following var). At the moment, the type of variables is defined like this in sib_syntax.ml:

type s_var =

{ s_var_name: string;

s_var_type: s_type; }

Here is sib_parser.mly. My question is, where and how I could tell the compiler to build globals, the declaration of variables, which is actually a list of s_var. I guess I need to refine the part of menhir in the end of sib_parser.mly(terminated_bindings, binding, separated_nonempty_list, etc.), but I do not know how...

Could anyone help? Thank you very much!

网友答案:

From the looks of it, in your binding rules, you have access to ids which is a list of variable names, so you could write, for instance:

binding:
  | ids = separated_nonempty_list(COMMA, IDENT) COLON INTEGER
      { List.map (fun id -> { s_var_name = id ; s_var_type = St_int}) ids }
  | ids = separated_nonempty_list(COMMA, IDENT) COLON BOOLEAN
      { List.map (fun id -> { s_var_name = id ; s_var_type = St_bool}) ids }

This would make the binding rule return a s_var list.

相关阅读:
Top