Writing an interpreter in OCaml [closed]

隐身守侯 提交于 2019-12-10 20:22:03

问题


I'm following a course in my University that ask me to write an interpreter in OCaml of a language starting from its operational semantics. Unfortunately, they didn't give us much resources from which we can learn about it, except from the lesson's slides. Can someone suggest me some book or some website where I can find something about it (or similar) ? Thanks.


回答1:


May be you should try Types and Programming Languages by B. Pierce which is probably a good reference on the topic (especially if your input language is functional).

If you want to go deeper into semantics I would advice Formal Semantics of Programming Languages by G. Winskel. But it won't help you with implementation.

Finally, if at one point you need to compile your language instead of interpreting it you should have a look at Modern Compiler Implementation in ML by A. Appel.

But these books are probably overkills for what you want to do (your lectures notes should probably be enough).




回答2:


Once you have a suitable data type that represents the language, it's mostly a matter of translating the semantics, rule by rule, using pattern-matching.

For instance, given this trivial language that has integer literals, addition, and assignable variables:

type Expression = Literal of int | Variable of string | Addition of Expression * Expression;;
type Statement = Assignment of string * Expression | Sequence of Statement * Statement;;

and a Store for storing the values of variables:

type Store = <something>
lookup : Store -> string -> int
update : Store -> string -> int -> Store

we could define semantic functions like these (I'll skip the step of defining the semantics formally):

let semE store = function
   | Literal l -> l
   | Variable x -> lookup store x
   | Addition e1 e2 -> (semE e1 store) + (semE e2 store);;

let semS store = function
   | Assignment x e -> update store x (semE e store)
   | Sequence (s1, s2) -> let store' = semS store s1 
                          in semS store' s2;;

This is a complete interpreter for the language, but it doesn't have a parser for translating from the language's syntax to the representation above.

For instance,

semS (Sequence (Assignment "x" (Literal 3), 
                Assignment "x" (Addition (Variable "x") (Literal 1)))) 
      empty_store

which might be represented in the input language as x := 3; x := x + 1, should result in a Store where x has the value 4.




回答3:


I would suggest this MOOC (in english !) : ocamlmooc

Books (the ones I use... but there is many other) :
Developping applications with Ocaml
real world ocaml.

In the first book, have a look on Chapter 6, that should held you.



来源:https://stackoverflow.com/questions/34120459/writing-an-interpreter-in-ocaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!