frontend - Common way to store positions in a formatter -


i want write small editor specific language. in editor, able indent 1 or several lines (ie, adding white-spaces on left hand of each line); able format whole code (ie, alter white-spaces , newlines in appropriate locations).

given program, front-end ocamllex , ocamlyacc build abstract syntax tree (ast). know common ways store positions of elements in ast.

one way guess append (start) position each element of ast. example, if type of expression defined follow:

type expression =   ...   | e_int of int   | e_function_ees of function.t * (expression list) 

it become:

type expression =   ...   | e_int of position * int   | e_function_ees of position * function.t * (expression list) 

then, if know length of each element, can infer position of in editor. common way so? don't find nice...

you don't have repeat position each pattern. write 1 in end:

type expression =    ...   | e_int of int   | e_function_ees of function.t * (expression list)   | e_loc of position * expression 

as result, existing functions on expression, add case e_loc, , not need touch existing cases.

to construct e_loc automatically while parsing, add in .mly example:

loc(expression): | t = expression { e_loc (($startpos, $endpos), t) }  (* immediate construction: *) expression: | int { e_loc (($startpos, $endpos), e_int $1) }  (* or delay construction: *) expression: | e0 = loc(expression) plus e1 = loc(expression) { e_function_ees (function.plus, [e0; e1]) } 

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

python 3.x - PyQt5 - Signal : pyqtSignal no method connect -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)