Typer
Threads by month
- ----- 2026 -----
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
March 2016
- 5 participants
- 19 discussions
Stefan pushed to branch master at Stefan / Typer
Commits:
6cd88359 by Stefan Monnier at 2016-03-20T22:12:22-04:00
Make the code compile
* src/eval.ml (_eval): Eval body with the extra vars bound from the
pattern match.
* src/main.ml (default_grammar, default_stt): Remove; use Grammar instead.
* tests/REPL.ml (ipexp_parse): Reduce duplication. Fix `nod' ref.
(ilexp_parse): Get it to type-check.
(ilexp_parse_all.loop, ieval_all.loop): Fix use of ::.
(ieval): Get it to type-check.
(repl.loop.print_e): Fix arg names.
- - - - -
4 changed files:
- src/eval.ml
- src/grammar.ml
- src/main.ml
- tests/REPL.ml
Changes:
=====================================
src/eval.ml
=====================================
--- a/src/eval.ml
+++ b/src/eval.ml
@@ -88,7 +88,8 @@ type runtime_env = (string option * lexp) myers
let make_runtime_ctx = nil;;
let add_rte_variable name x l = (cons (name, x) l);;
-let get_rte_variable (idx: int) (l: runtime_env): lexp =
+let get_rte_variable (idx: int) (l: runtime_env): lexp =
+ (* FIXME: Check that the variable's name is right! *)
let (_, x) = (nth idx l) in x
;;
@@ -151,7 +152,10 @@ let rec _eval lxp ctx i: (value_type) =
let n = List.length args in
match lname with
(* Hardcoded functions *)
-
+ (* FIXME: These should not be hardcoded here, but should be
+ * stuffed into the "initial environment", i.e. the value of
+ * `ctx` used at top-level. *)
+
(* + is read as a nested binary operator *)
| Var((_, name), _) when name = "_+_" ->
let nctx = build_arg_list args ctx i in
@@ -294,7 +298,7 @@ let rec _eval lxp ctx i: (value_type) =
ctx pat_args args in
(* eval body *)
- _eval exp ctx (i + 1) end
+ _eval exp nctx (i + 1) end
| _ -> Imm(String(dloc, "eval Not Implemented"))
=====================================
src/grammar.ml
=====================================
--- a/src/grammar.ml
+++ b/src/grammar.ml
@@ -48,6 +48,15 @@ let default_stt =
stt.(Char.code ')') <- true;
stt
+(* default_grammar is auto-generated from typer-smie-grammar via:
+
+ (dolist (x typer-smie-grammar)
+ (when (stringp (car x))
+ (insert "(\"" (car x) "\", "
+ (if (numberp (nth 1 x)) (format "Some %d" (nth 1 x)) "None") ", "
+ (if (numberp (nth 2 x)) (format "Some %d" (nth 2 x)) "None")
+ ");\n")))
+ *)
let default_grammar : grammar =
List.fold_left (fun g (n, ll, rl) -> SMap.add n (ll, rl) g)
SMap.empty
@@ -84,4 +93,4 @@ let default_grammar : grammar =
("let", None, Some 2);
("if", None, Some 1);
("(", None, Some 4);
- ]
\ No newline at end of file
+ ]
=====================================
src/main.ml
=====================================
--- a/src/main.ml
+++ b/src/main.ml
@@ -31,6 +31,7 @@ open Sexp
(* open Lexp *)
open Prelexer
open Pexp
+open Grammar
(* Overview.
*
@@ -80,62 +81,6 @@ open Pexp
(*************** The Top Level *********************)
-let default_stt =
- let stt = Array.make 256 false
- in stt.(Char.code ';') <- true;
- stt.(Char.code ',') <- true;
- stt.(Char.code '(') <- true;
- stt.(Char.code ')') <- true;
- stt
-
-(* default_grammar is auto-generated from typer-smie-grammar via:
-
- (dolist (x typer-smie-grammar)
- (when (stringp (car x))
- (insert "(\"" (car x) "\", "
- (if (numberp (nth 1 x)) (format "Some %d" (nth 1 x)) "None") ", "
- (if (numberp (nth 2 x)) (format "Some %d" (nth 2 x)) "None")
- ");\n")))
- *)
-let default_grammar : grammar
- = List.fold_left (fun g (n, ll, rl) -> SMap.add n (ll, rl) g)
- SMap.empty
- [("^", Some 171, Some 159);
- ("/", Some 148, Some 160);
- ("-", Some 92, Some 110);
- ("+", Some 93, Some 111);
- ("!=", Some 94, Some 75);
- (">=", Some 95, Some 76);
- ("<=", Some 96, Some 77);
- (">", Some 97, Some 78);
- ("<", Some 98, Some 79);
- ("&&", Some 64, Some 81);
- ("||", Some 39, Some 51);
- (",", Some 26, Some 26);
- ("then", Some 1, Some 0);
- ("=", Some 99, Some 80);
- ("type", None, Some 27);
- (";", Some 15, Some 15);
- ("*", Some 137, Some 137);
- (":", Some 173, Some 115);
- ("]", Some 3, None);
- ("->", Some 126, Some 114);
- ("=>", Some 126, Some 113);
- ("≡>", Some 126, Some 112);
- ("in", Some 2, Some 53);
- ("else", Some 0, Some 52);
- ("|", Some 40, Some 40);
- (")", Some 4, None);
- ("[", None, Some 3);
- ("case", None, Some 28);
- ("lambda", None, Some 126);
- ("letrec", None, Some 2);
- ("let", None, Some 2);
- ("if", None, Some 1);
- ("(", None, Some 4);
- ]
-
-
let process_typer_file sourcename choppable_suffix venv =
(* let targetbase = Filename.chop_suffix sourcename choppable_suffix in *)
let pretokens = prelex_file sourcename in
=====================================
tests/REPL.ml
=====================================
--- a/tests/REPL.ml
+++ b/tests/REPL.ml
@@ -54,14 +54,11 @@ type ptop =
let ipexp_parse p =
match p with
(* Declaration *)
- | Node (Symbol (_, "_=_"), [Symbol s; t]) ->
- let (a, b, c)::_ = pexp_p_decls nod in
- Pdecl(a, b, c)
- | Node (Symbol (_, "_:_"), [Symbol s; t]) ->
- let (a, b, c)::_ = pexp_p_decls nod in
+ | Node (Symbol (_, ("_=_" | "_:_")), [Symbol s; t]) ->
+ let (a, b, c)::_ = pexp_p_decls p in
Pdecl(a, b, c)
(* Expression *)
- | _ -> let a = pexp_parse nod in Pexpr(a)
+ | _ -> let a = pexp_parse p in Pexpr(a)
;;
let ipexp_parse_all ps = List.map ipexp_parse ps;;
@@ -72,10 +69,10 @@ type ltop =
let ilexp_parse l lctx =
match l with
- | Pdecl(_, _, _) -> let (a, b, c), d = lexp_decls [l] ctx in
+ | Pdecl(x, v, t) -> let [(a, b, c)], d = lexp_decls [(x, v, t)] lctx in
Ldecl(a, b, c), d
- | Pexpr(x) -> let v, c = lexp_parse x lctx in
- Lexpr(v), c
+ | Pexpr(x) -> let v = lexp_parse x lctx in
+ Lexpr(v), lctx
let ilexp_parse_all ls lctx =
let rec loop lst acc ctx =
@@ -83,8 +80,8 @@ let ilexp_parse_all ls lctx =
| [] -> List.rev acc, ctx
| hd::tl ->
let x, c = ilexp_parse hd ctx in
- let nacc = acc::x in
- loop tl nacc c in
+ let nacc = x::acc in
+ loop tl nacc c in
loop ls [] lctx
type ival =
@@ -93,9 +90,9 @@ type ival =
let ieval xpr rctx =
match xpr with
- | Ldecl(_, _, _) -> let r = eval_decls xpr rctx in
+ | Ldecl(x, v, t) -> let r = eval_decls [(x, v, t)] rctx in
Ivoid, rctx
- | Lexpr(x) -> let v, _ = eval x rctx in
+ | Lexpr(x) -> let v = eval x rctx in
Ival(v), rctx
let ieval_all xprs rctx =
@@ -104,7 +101,7 @@ let ieval_all xprs rctx =
| [] -> List.rev acc, ctx
| hd::tl ->
let x, c = ieval hd ctx in
- let nacc = acc::x in
+ let nacc = x::acc in
loop tl nacc c in
loop xprs [] rctx
@@ -125,7 +122,7 @@ let rec repl () =
let tenv = default_stt in
let grm = default_grammar in
let limit = (Some ";") in
- let eval_string str clxp rctx = eval_string str tenv grm limit clxp rctx in
+ (* let eval_string str clxp rctx = eval_string str tenv grm limit clxp rctx in *)
let lxp_ctx = make_lexp_context in
(* Those are hardcoded operation *)
let lxp_ctx = add_def "_+_" lxp_ctx in
@@ -147,7 +144,7 @@ let rec repl () =
else
let (ret, clxp, rctx) = (ieval_string ipt clxp rctx) in
- let print_e j v =
+ let print_e _ b =
match b with
| Ivoid -> ()
| Ival(x) -> print_eval_result i x in
@@ -173,4 +170,4 @@ let main () =
main ()
-;;
\ No newline at end of file
+;;
View it on GitLab: https://gitlab.com/monnier/typer/commit/6cd883591bc13c03681fd31b642bc04fa55…
1
0
[Git][monnier/typer][master] * src/lparse.ml (lexp_parse): Don't return a context
by Stefan 15 Mar '16
by Stefan 15 Mar '16
15 Mar '16
Stefan pushed to branch master at Stefan / Typer
Commits:
61f036c4 by Stefan Monnier at 2016-03-15T18:16:46-04:00
* src/lparse.ml (lexp_parse): Don't return a context
(lexp_parse_constructors, lexp_call): Same.
- - - - -
3 changed files:
- src/lexp.ml
- src/lparse.ml
- src/main.ml
Changes:
=====================================
src/lexp.ml
=====================================
--- a/src/lexp.ml
+++ b/src/lexp.ml
@@ -584,7 +584,6 @@ and lexp_unparse e : pexp =
(* (internal_error "Can't print a Susp") *)
let lexp_print e = sexp_print (pexp_unparse (lexp_unparse e))
-<<<<<<< HEAD
(* let rec lexp_type (env: (lexp option * lexp) VMap.t) e : lexp =
* let rec follow e =
=====================================
src/lparse.ml
=====================================
--- a/src/lparse.ml
+++ b/src/lparse.ml
@@ -20,11 +20,11 @@
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
- * You should have received a copy of the GNU General Public License along
- * with this program. If not, see <http://www.gnu.org/licenses/>.
+ * You should have received a copy of the GNU General Public License along
+ * with this program. If not, see <http://www.gnu.org/licenses/>.
*
* ---------------------------------------------------------------------------
- *
+ *
* Description:
* parse pexp expression into lexp
*
@@ -42,7 +42,7 @@ open Lexer
open Prelexer
(* Shortcut => Create a Var *)
-let make_var name index loc =
+let make_var name index loc =
Var(((loc, name), index))
;;
@@ -56,7 +56,7 @@ let dloc = dummy_location
let lexp_warning = msg_warning "LEXP"
let lexp_error = msg_error "LEXP"
-let lexp_fatal loc msg =
+let lexp_fatal loc msg =
msg_error "LEXP" loc msg;
raise (internal_error msg)
;;
@@ -72,12 +72,12 @@ let pvar_to_vdef p = p;;
(*
* The main job of lexp (currently) is to determine variable name (index)
- * and to regroup type specification with their variable
+ * and to regroup type specification with their variable
*
* lexp_context is composed of two environment: senv and env.
* the senv environment is used to find the correct debruijn index
* while the env environment is used to save variable information.
- * the env environment look a lot like the runtime environment that will be
+ * the env environment look a lot like the runtime environment that will be
* used in the eval section.
*
* While most of the time senv and env will be synchronised it is
@@ -88,131 +88,129 @@ let pvar_to_vdef p = p;;
* let a = 3; b = 5 in a + b;
*
*)
-
-let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
+
+let rec lexp_parse (p: pexp) (ctx: lexp_context): lexp =
(* So I don't have to extract it *)
let tloc = pexp_location p in
match p with
(* Block/String/Integer/Float *)
- | Pimm value -> Imm(value), ctx
-
+ | Pimm value -> Imm(value)
+
(* Symbol i.e identifier *)
- | Pvar (loc, name) -> begin
- try
+ | Pvar (loc, name) ->
+ (try
(* Send Variable loc *)
let idx = senv_lookup name ctx in
- (make_var name idx loc), ctx;
-
+ make_var name idx loc;
+
with Not_found ->
(lexp_error loc ("The Variable: " ^ name ^ " was not declared");
(* Error recovery. The -1 index will raise an error later on *)
- (make_var name (-1) loc), ctx) end
-
+ make_var name (-1) loc))
+
(* Let, Variable declaration + local scope *)
- | Plet(loc, decls, body) ->
+ | Plet(loc, decls, body) ->
let decl, nctx = lexp_decls decls ctx in
(* Body cannot modify context *)
- let bdy, _ = lexp_parse body nctx in
+ let bdy = lexp_parse body nctx in
(* Send back old context as we exit the inner scope *)
- Let(tloc, decl, bdy), ctx
-
+ Let(tloc, decl, bdy)
+
(* ->/=> *)
| Parrow (kind, Some var, tp, loc, expr) ->
let nvar = pvar_to_vdef var in (* /!\ HERE *)
- let ltyp, ctx = lexp_parse tp ctx in
- let lxp, ctx = lexp_parse expr ctx in
- Arrow(kind, Some nvar, ltyp, tloc, lxp), ctx
-
+ let ltyp = lexp_parse tp ctx in
+ let lxp = lexp_parse expr ctx in (* FIXME: add nvar to ctx! *)
+ Arrow(kind, Some nvar, ltyp, tloc, lxp)
+
| Parrow (kind, None, tp, loc, expr) ->
- let ltyp, ctx = lexp_parse tp ctx in
- let lxp, ctx = lexp_parse expr ctx in
- Arrow(kind, None, ltyp, tloc, lxp), ctx
-
+ let ltyp = lexp_parse tp ctx in
+ let lxp = lexp_parse expr ctx in
+ Arrow(kind, None, ltyp, tloc, lxp)
+
(* *)
| Plambda (kind, var, Some ptype, body) ->
(* Add argument to context *)
let (loc, vname) = var in
- let ltp, nctx = lexp_parse ptype ctx in (* Get Type *)
-
+ let ltp = lexp_parse ptype ctx in (* Get Type *)
+
let nctx = senv_add_var vname loc ctx in
let nctx = env_add_var_info (0, (loc, vname), dlxp, ltp) nctx in
- let lbody, _ = lexp_parse body nctx in
-
+ let lbody = lexp_parse body nctx in
+
(* Return old context as we exit lambda scope*)
- Lambda(kind, var, ltp, lbody), ctx
-
+ Lambda(kind, var, ltp, lbody)
+
| Plambda (kind, var, None, body) ->
let (loc, vname) = var in
-
+
let nctx = senv_add_var vname loc ctx in
let nctx = env_add_var_info (0, (loc, vname), dlxp, dltype) nctx in
-
- let lbody, _ = lexp_parse body nctx in
- Lambda(kind, var, UnknownType(tloc), lbody), ctx
-
- | Pcall (fname, _args) ->
- let r, c = lexp_call fname _args ctx in
- r, ctx
+
+ let lbody = lexp_parse body nctx in
+ Lambda(kind, var, UnknownType(tloc), lbody)
+
+ | Pcall (fname, args) -> lexp_call fname args ctx
(* Pinductive *)
| Pinductive (label, [], ctors) ->
- let map_ctor, nctx = lexp_parse_constructors ctors ctx in
- Inductive(tloc, label, [], map_ctor), nctx
-
+ let map_ctor = lexp_parse_constructors ctors ctx in
+ Inductive(tloc, label, [], map_ctor)
+
(* Pcons *)
| Pcons(vr, sym) -> (
let (loc, type_name) = vr in
let (_, ctor_name) = sym in
-
+
(* An inductive type named type_name must be in the environment *)
try let idx = senv_lookup type_name ctx in
(* Check if the constructor exists *)
(* TODO *)
- Cons((vr, idx), sym), ctx
+ Cons((vr, idx), sym)
with Not_found ->
- lexp_error loc
+ lexp_error loc
("The inductive type: " ^ type_name ^ " was not declared");
- Cons((vr, -1), sym), ctx)
-
+ Cons((vr, -1), sym))
+
(* Pcase *)
| Pcase (loc, target, patterns) ->
-
+
(* I need type info HERE *)
- let lxp, nctx = lexp_parse target ctx in
+ let lxp = lexp_parse target ctx in
let ltp = UnknownType(loc) in
(* Read patterns one by one *)
let rec loop ptrns merged dflt =
match ptrns with
| [] -> merged, dflt
- | hd::tl ->
+ | hd::tl ->
let (pat, exp) = hd in
(* Create pattern context *)
- let (name, iloc, arg), nctx2 =
- lexp_read_pattern pat exp lxp nctx in
+ let (name, iloc, arg), nctx2 =
+ lexp_read_pattern pat exp lxp ctx in
(* parse using pattern context *)
- let exp, _ = lexp_parse exp nctx2 in
-
+ let exp = lexp_parse exp nctx2 in
+
if name = "_" then
loop tl merged (Some exp)
else
let merged = SMap.add name (iloc, arg, exp) merged in
loop tl merged dflt in
-
+
let (lpattern, dflt) = loop patterns SMap.empty None in
(* Exit case, send back old context *)
- Case(loc, lxp, ltp, lpattern, dflt), ctx
-
- | _
- -> UnknownType(tloc), ctx
-
+ Case(loc, lxp, ltp, lpattern, dflt)
+
+ | _
+ -> UnknownType(tloc)
+
(* Identify Call Type and return processed call *)
and lexp_call (fname: pexp) (_args: sexp list) ctx =
(* Process Arguments *)
let pargs = List.map pexp_parse _args in
-
+
(* Call to named function which must have been defined earlier *
* i.e they must be in the context *)
begin try begin
@@ -221,52 +219,52 @@ and lexp_call (fname: pexp) (_args: sexp list) ctx =
| Pvar(loc, nm) -> nm, loc
| Pcons (_, (loc, nm)) -> nm, loc
| _ -> raise Not_found in
-
- let largs, fctx = lexp_parse_all pargs ctx in
+
+ let largs, fctx = lexp_parse_all pargs ctx in
let new_args = List.map (fun g -> (Aexplicit, g)) largs in
-
+
try
(* Check if the function was defined *)
let idx = senv_lookup name ctx in
let vf = (make_var name idx loc) in
-
- Call(vf, new_args), ctx
-
+
+ Call(vf, new_args)
+
with Not_found ->
(* Don't stop even if an error was found *)
- lexp_error loc ("The function \"" ^ name ^
+ lexp_error loc ("The function \"" ^ name ^
"\" was not defined");
let vf = (make_var name (-1) loc) in
- Call(vf, new_args), ctx end
-
+ Call(vf, new_args) end
+
(* Call to a nameless function *)
with Not_found ->
- let largs, fctx = lexp_parse_all pargs ctx in
+ let largs, fctx = lexp_parse_all pargs ctx in
let new_args = List.map (fun g -> (Aexplicit, g)) largs in
(* I think this should not modify context.
* if so, funny things might happen when evaluating *)
- let fname, ctx = lexp_parse fname ctx in
- Call(fname, new_args), ctx end
+ let fname = lexp_parse fname ctx in
+ Call(fname, new_args) end
-(* Read a pattern and create the equivalent representation *)
-and lexp_read_pattern pattern exp target ctx:
+(* Read a pattern and create the equivalent representation *)
+and lexp_read_pattern pattern exp target ctx:
((string * location * (arg_kind * vdef) option list) * lexp_context) =
-
+
match pattern with
| Ppatany (loc) -> (* Catch all expression nothing to do *)
- ("_", loc, []), ctx
-
+ ("_", loc, []), ctx
+
| Ppatvar (loc, name) ->(
(* FIXME better check *)
try
- let idx = senv_lookup name ctx in
+ let idx = senv_lookup name ctx in
(* constructor with no args *)
(name, loc, []), ctx
-
+
(* would it not make a default match too? *)
with Not_found ->
(* Create a variable containing target *)
- let nctx = senv_add_var name loc ctx in
+ let nctx = senv_add_var name loc ctx in
let nctx = env_add_var_info (0, (loc, name), target, dltype) nctx in
("_", loc, []), nctx)
@@ -276,7 +274,7 @@ and lexp_read_pattern pattern exp target ctx:
(* read pattern args *)
let args, nctx = lexp_read_pattern_args args ctx in
(name, loc, args), nctx
-
+
(* Read patterns inside a constructor *)
and lexp_read_pattern_args args ctx:
(((arg_kind * vdef) option list) * lexp_context)=
@@ -289,7 +287,7 @@ and lexp_read_pattern_args args ctx:
match pat with
(* Nothing to do *)
| Ppatany (loc) -> loop tl (None::acc) ctx
- | Ppatvar (loc, name) ->
+ | Ppatvar (loc, name) ->
(* Add var *)
let nctx = senv_add_var name loc ctx in
let nctx = env_add_var_info (0, (loc, name), dlxp, dltype) nctx in
@@ -299,12 +297,12 @@ and lexp_read_pattern_args args ctx:
loop tl (None::acc) ctx)
in loop args [] ctx
-
+
(* Parse inductive constructor *)
and lexp_parse_constructors ctors ctx =
-
+
let make_args (args:(arg_kind * pvar option * pexp) list):
- (arg_kind * ltype) list * lexp_context =
+ (arg_kind * ltype) list * lexp_context =
let rec loop args acc ctx =
match args with
| [] -> (List.rev acc), ctx
@@ -312,38 +310,38 @@ and lexp_parse_constructors ctors ctx =
match hd with
(* What does the optional Pvar do ?
that expression does not exist in LEXP*)
- | (kind, _, exp) ->
- let lxp, nctx = lexp_parse exp ctx in
- loop tl ((kind, lxp)::acc) nctx end in
+ | (kind, _, exp) ->
+ let lxp = lexp_parse exp ctx in
+ loop tl ((kind, lxp)::acc) ctx end in
loop args [] ctx in
-
+
let rec loop ctors merged ctx =
match ctors with
- | [] -> merged, ctx
- | hd::tl -> begin
- match hd with
+ | [] -> merged
+ | hd::tl -> begin
+ match hd with
| ((loc, name), args) ->
let largs, nctx = make_args args in
let nmerged = SMap.add name largs merged in
- (loop tl nmerged ctx)
- end in
-
+ loop tl nmerged ctx
+ end in
+
loop ctors SMap.empty ctx
-
+
(* Parse let declaration *)
and lexp_decls decls ctx: (((vdef * lexp * ltype) list) * lexp_context) =
(* Merge Type info and declaration together *)
(* We use a list because order matters and Maps reorder elements *)
- (*
+ (*
let rec is_equal target (p:(vdef * pexp option * pexp option)): bool =
let ((_, name), _, _) = p in
if name == target then true else false in *)
-
+
(* merge with a map to guarantee uniqueness. *)
- let rec merge_decls (decls: (pvar * pexp * bool) list) merged acc:
+ let rec merge_decls (decls: (pvar * pexp * bool) list) merged acc:
((location * pexp option * pexp option) SMap.t * string list) =
-
+
(* we cant evaluate here because variable are not in the environment *)
match decls with
| [] -> merged, (List.rev acc)
@@ -352,7 +350,7 @@ and lexp_decls decls ctx: (((vdef * lexp * ltype) list) * lexp_context) =
(* Type Info: Var:Type *)
| ((loc, name), type_info, true) -> begin
try
- (* If found its means the instruction was declared
+ (* If found its means the instruction was declared
* before the type info. Should we allow this? *)
let (l, inst, _) = SMap.find name merged in
let new_decl = (l, inst, Some type_info) in
@@ -362,7 +360,7 @@ and lexp_decls decls ctx: (((vdef * lexp * ltype) list) * lexp_context) =
let new_decl = (loc, None, Some type_info) in
let nmerged = SMap.add name new_decl merged in
(merge_decls tl nmerged (name::acc)) end
-
+
(* Instruction: Var = expr *)
| ((loc, name), inst, false) -> begin
try
@@ -370,29 +368,29 @@ and lexp_decls decls ctx: (((vdef * lexp * ltype) list) * lexp_context) =
let new_decl = (l, Some inst, tp) in
let nmerged = SMap.add name new_decl merged in
(merge_decls tl nmerged acc)
-
+
with Not_found ->
let new_decl = (loc, Some inst, None) in
let nmerged = SMap.add name new_decl merged in
(merge_decls tl nmerged (name::acc)) end in
-
+
let mdecls, ord = merge_decls decls SMap.empty [] in
-
+
(* cast map to list*)
let decls = List.map (fun name ->
let (l, inst, tp) = SMap.find name mdecls in
((l, name), inst, tp) ) ord
in
-
+
(* Add Each Variable to the environment *)
let nctx = List.fold_left (fun ctx hd ->
- match hd with
+ match hd with
| (_, None, _) -> ctx (* Unused variable: No Instruction *)
- | ((loc, name), _, _) -> senv_add_var name loc ctx)
+ | ((loc, name), _, _) -> senv_add_var name loc ctx)
ctx decls in
-
+
let n_decls = List.length decls in
-
+
(* Add Variable info *)
let rec process_var_info dcl_lst _ctx acc i =
match dcl_lst with
@@ -404,30 +402,30 @@ and lexp_decls decls ctx: (((vdef * lexp * ltype) list) * lexp_context) =
let nacc = ((loc, name), lxp, ltp)::acc in
let ctx2 = env_add_var_info (n_decls - i, (loc, name), lxp, ltp) _ctx in
process_var_info tl ctx2 nacc (i + 1))
-
+
| ((loc, name), Some pinst, Some ptype) ->(
- let linst, ctx1 = lexp_parse pinst _ctx in
- let ltyp, ctx2 = lexp_parse ptype ctx1 in
+ let linst = lexp_parse pinst _ctx in
+ let ltyp = lexp_parse ptype _ctx in
let nacc = ((loc, name), linst, ltyp)::acc in
- let ctx3 = env_add_var_info (n_decls - i, (loc, name), linst, ltyp) ctx2 in
+ let ctx3 = env_add_var_info (n_decls - i, (loc, name), linst, ltyp) _ctx in
process_var_info tl ctx3 nacc (i + 1))
(* Skip the variable *)
- | ((loc, name), None, _) -> (lexp_warning loc ("Unused Variable: " ^ name);
+ | ((loc, name), None, _) -> (lexp_warning loc ("Unused Variable: " ^ name);
process_var_info tl _ctx acc i) in
-
+
let acc, ctx = process_var_info decls nctx [] 0 in
acc, ctx
-and lexp_parse_all (p: pexp list) (ctx: lexp_context):
+and lexp_parse_all (p: pexp list) (ctx: lexp_context):
(lexp list * lexp_context) =
- let rec loop (plst: pexp list) ctx (acc: lexp list) =
+ let rec loop (plst: pexp list) ctx (acc: lexp list) =
match plst with
| [] -> ((List.rev acc), ctx)
- | _ -> let lxp, new_ctx = lexp_parse (List.hd plst) ctx in
- (loop (List.tl plst) new_ctx (lxp::acc)) in
+ | _ -> let lxp = lexp_parse (List.hd plst) ctx in
+ (loop (List.tl plst) ctx (lxp::acc)) in
(loop p ctx [])
-
+
(*
* Type Inference
* --------------------- *)
@@ -447,9 +445,9 @@ and lexp_parse_all (p: pexp list) (ctx: lexp_context):
* - use lexp_p_infer for destructors, and use lexp_p_check for constructors.
* - use lexp_p_check whenever you can.
*)
-
+
and lexp_p_infer (p : pexp) (env : lexp_context) : lexp * ltype =
- let lxp, nctx = lexp_parse p env in
+ let lxp = lexp_parse p env in
lxp, UnknownType(dummy_location)
and lexp_p_check (p : pexp) (t : ltype) (env : lexp_context): lexp =
@@ -461,7 +459,7 @@ and lexp_p_check (p : pexp) (t : ltype) (env : lexp_context): lexp =
(*
* Printing
* --------------------- *)
-
+
(* Print back in CET (Close Enough Typer) easier to read *)
(* So print can be called while parsing *)
and lexp_print_adv opt exp =
@@ -469,44 +467,44 @@ and lexp_print_adv opt exp =
let (pty, indent, prtp) = opt in
match exp with
| Imm(value) -> sexp_print value
- | Var ((loc, name), idx) ->
- print_string name;
+ | Var ((loc, name), idx) ->
+ print_string name;
print_string "["; print_int idx; print_string "]"
-
+
| Let (_, decls, body) ->
- print_string "let"; lexp_print_decls (pty, indent + 1, prtp) decls;
+ print_string "let"; lexp_print_decls (pty, indent + 1, prtp) decls;
if pty then print_string (make_line ' ' (indent * 4 + 4));
print_string " in "; lexp_print_adv (pty, indent + 2, prtp) body
-
+
| Arrow(kind, Some (_, name), tp, loc, expr) ->
slexp_print tp; print_string ": "; print_string name;
print_string " -> "; slexp_print expr;
-
+
| Arrow(kind, None, tp, loc, expr) ->
slexp_print tp; print_string " -> "; slexp_print expr;
-
+
| Lambda(kind, (loc, name), ltype, lbody) ->
- print_string "lambda ("; print_string (name ^ ": ");
+ print_string "lambda ("; print_string (name ^ ": ");
slexp_print ltype; print_string ") -> "; slexp_print lbody;
-
+
| Cons(vf, symbol) ->
let (loc, name) = symbol in
let ((loc, vname), idx) = vf in
print_string (name ^ "("); print_string vname;
print_string "["; print_int idx; print_string "])"
-
+
| Call(fname, args) -> begin (* /!\ Partial Print *)
(* get function name *)
let str, idx = match fname with
| Var((_, name), idx) -> name, idx
| _ -> "unkwn", -1 in
-
- let print_arg arg = match arg with | (kind, lxp) ->
+
+ let print_arg arg = match arg with | (kind, lxp) ->
lexp_print_adv (pty, 0, prtp) lxp in
-
- let print_binop op lhs rhs =
+
+ let print_binop op lhs rhs =
print_arg lhs; print_string op; print_arg rhs in
-
+
match (str, args) with
(* Special Operator *)
| ("_=_", [lhs; rhs]) -> print_binop " = " lhs rhs
@@ -515,7 +513,7 @@ and lexp_print_adv opt exp =
| ("_/_", [lhs; rhs]) -> print_binop " / " lhs rhs
| ("_*_", [lhs; rhs]) -> print_binop " * " lhs rhs
(* not an operator *)
- | _ ->
+ | _ ->
print_string ("(" ^ str ^ "["); print_int idx; print_string "]";
List.iter (fun arg -> print_string " "; print_arg arg) args;
print_string ")" end
@@ -523,43 +521,43 @@ and lexp_print_adv opt exp =
| Inductive (_, (_, name), _, ctors) ->
print_string ("inductive_ " ^ name ^ " ");
lexp_print_ctors opt ctors;
-
+
| Case (_, target, tpe, map, dflt) -> begin
print_string "case "; slexp_print target;
- print_string ": "; slexp_print tpe;
-
+ print_string ": "; slexp_print tpe;
+
if pty then print_string "\n";
-
+
let print_arg arg =
- List.iter (fun v ->
+ List.iter (fun v ->
match v with
| None -> print_string " _"
| Some (kind, (l, n)) -> print_string (" " ^ n)) arg in
-
+
SMap.iter (fun key (loc, arg, exp) ->
print_string (make_line ' ' (indent * 4));
- print_string ("| " ^ key); print_arg arg;
+ print_string ("| " ^ key); print_arg arg;
print_string " -> ";
slexp_print exp; print_string "; ";
if pty then print_string "\n";)
map;
-
+
match dflt with
| None -> ()
- | Some df ->
+ | Some df ->
print_string (make_line ' ' (indent * 4));
print_string "| _ -> "; slexp_print df;
print_string ";"; if pty then print_string "\n"; end
-
+
(* debug catch all *)
| UnknownType (loc) -> print_string "unkwn";
| _ -> print_string "Printint Not Implemented"
-
-
+
+
and lexp_print_ctors opt ctors =
SMap.iter (fun key value ->
print_string ("(" ^ key ^ ": ");
- List.iter (fun (kind, arg) ->
+ List.iter (fun (kind, arg) ->
lexp_print_adv opt arg; print_string " ") value;
print_string ")")
ctors
@@ -567,14 +565,14 @@ and lexp_print_ctors opt ctors =
and lexp_print_decls opt decls =
let (pty, indent, prtp) = opt in
let print_type nm tp =
- print_string (" " ^ nm ^ ": "); lexp_print_adv opt tp;
+ print_string (" " ^ nm ^ ": "); lexp_print_adv opt tp;
print_string ";"; in
List.iteri (fun idx g -> match g with
| ((loc, name), expr, ltyp) ->
if pty && idx > 0 then print_string (make_line ' ' (indent * 4));
if prtp then print_type name ltyp; print_string " ";
- print_string (name ^ " = ");
+ print_string (name ^ " = ");
lexp_print_adv opt expr; print_string ";";
if pty then print_string "\n")
decls
@@ -582,17 +580,17 @@ and lexp_print_decls opt decls =
(* Print context *)
and lexp_context_print ctx =
let ((n, map), env) = ctx in
-
+
print_string (make_title " LEXP CONTEXT ");
-
+
make_rheader [
(Some ('r', 10), "NAME");
(Some ('r', 7), "INDEX");
(Some ('r', 10), "NAME");
(Some ('r', 20), "VALUE:TYPE")];
-
+
print_string (make_sep '-');
-
+
StringMap.iter (fun key idx ->
(* Print senv info *)
print_string " | ";
@@ -600,9 +598,9 @@ and lexp_context_print ctx =
print_string " | ";
ralign_print_int (n - idx - 1) 7;
print_string " | ";
-
+
(* Print env Info *)
- try let (_, (_, name), exp, tp) = env_lookup_by_index (n - idx - 1) ctx in
+ try let (_, (_, name), exp, tp) = env_lookup_by_index (n - idx - 1) ctx in
ralign_print_string name 10; (* name must match *)
print_string " | ";
lexp_print_adv (false, 0, true) exp;
@@ -613,14 +611,14 @@ and lexp_context_print ctx =
Not_found -> print_string "Not_found \n")
map;
-
+
print_string (make_sep '=');
(* Only print var info *)
and lexp_print_var_info ctx =
let ((_, _), env) = ctx in
let n = Myers.length env in
-
+
for i = 0 to n - 1 do (
let (_, (_, name), exp, tp) = Myers.nth i env in
print_string name; (* name must match *)
@@ -632,11 +630,11 @@ and lexp_print_var_info ctx =
done;
;;
-let lexp_print e = lexp_print_adv (false, 0, true) e;;
-
+let lexp_print e = lexp_print_adv (false, 0, true) e;;
+
(* add dummy definition helper *)
-let add_def name ctx =
+let add_def name ctx =
let ctx = senv_add_var name dloc ctx in
env_add_var_info (0, (dloc, name), dlxp, dlxp) ctx
;;
@@ -646,7 +644,7 @@ let add_def name ctx =
* ------------------------ *)
(* Lexp helper *)
-let _lexp_expr_str (str: string) (tenv: bool array)
+let _lexp_expr_str (str: string) (tenv: bool array)
(grm: grammar) (limit: string option) (ctx: lexp_context) =
let pretoks = prelex_string str in
let toks = lex tenv pretoks in
@@ -656,7 +654,7 @@ let _lexp_expr_str (str: string) (tenv: bool array)
;;
(* specialized version *)
-let lexp_expr_str str lctx =
+let lexp_expr_str str lctx =
_lexp_expr_str str default_stt default_grammar (Some ";") lctx
;;
@@ -670,7 +668,6 @@ let _lexp_decl_str (str: string) tenv grm limit ctx =
;;
(* specialized version *)
-let lexp_decl_str str lctx =
+let lexp_decl_str str lctx =
_lexp_decl_str str default_stt default_grammar (Some ";") lctx
;;
-
=====================================
src/main.ml
=====================================
--- a/src/main.ml
+++ b/src/main.ml
@@ -88,16 +88,15 @@ let default_stt =
stt.(Char.code ')') <- true;
stt
-(*
+(* default_grammar is auto-generated from typer-smie-grammar via:
+
(dolist (x typer-smie-grammar)
(when (stringp (car x))
(insert "(\"" (car x) "\", "
(if (numberp (nth 1 x)) (format "Some %d" (nth 1 x)) "None") ", "
(if (numberp (nth 2 x)) (format "Some %d" (nth 2 x)) "None")
");\n")))
-
*)
-
let default_grammar : grammar
= List.fold_left (fun g (n, ll, rl) -> SMap.add n (ll, rl) g)
SMap.empty
View it on GitLab: https://gitlab.com/monnier/typer/commit/61f036c49dc0c1b31f1df56ae6a7de14ec8…
1
0
Setepenre pushed to branch master at Stefan / Typer
Commits:
2a292311 by Pierre Delaunay at 2016-03-11T10:17:24-05:00
declaration fix bis
- - - - -
e594f7fe by Pierre Delaunay at 2016-03-13T12:49:23-04:00
Basic utest lib
- - - - -
a37b8648 by Pierre Delaunay at 2016-03-13T14:31:28-04:00
tests
- - - - -
881f7888 by Pierre Delaunay at 2016-03-13T19:51:00-04:00
fix lexp_decl double decl
- - - - -
25 changed files:
- .gitignore
- GNUmakefile
- doc/Compiler Structure.md
- − samples/case.typer
- − samples/debug_test.typer
- − samples/functions.typer
- − samples/inductives.typer
- − samples/let.typer
- − samples/lexer_test.typer
- − samples/lexp_test.typer
- − samples/pretoken_test.typer
- src/debruijn.ml
- src/eval.ml
- src/fmt.ml
- src/lparse.ml
- src/pexp.ml
- tests/REPL.ml
- tests/debug.ml
- + tests/eval_test.ml
- tests/full_debug.ml
- − tests/let_test.ml
- + tests/lexp_test.ml
- + tests/pexp_test.ml
- + tests/utest_lib.ml
- tests/utest_main.ml
Changes:
=====================================
.gitignore
=====================================
--- a/.gitignore
+++ b/.gitignore
@@ -17,3 +17,4 @@ manual.??
#*#
test__.ml
_temp_hack
+test__.typer
=====================================
GNUmakefile
=====================================
--- a/GNUmakefile
+++ b/GNUmakefile
@@ -1,6 +1,9 @@
RM=rm -f
+SRC_FILES := $(wildcard ./src/*.ml)
+CPL_FILES := $(wildcard ./_build/src/*.cmo)
TEST_FILES := $(wildcard ./tests/*_test.ml)
+
# This is for windows: windows version is old
ifeq ($(OS),Windows_NT)
SHELL=C:/Windows/System32/cmd.exe
@@ -21,12 +24,17 @@ debug:
ityper:
ocamlbuild tests/REPL.native -I src -cflag -rectypes
mv _build/tests/REPL.native _build/ityper
-
-tests:
- # Build tests
+
+tests-build:
+# ============================
+# Build tests
+# ============================
$(foreach test, $(TEST_FILES), ocamlbuild $(subst ./,,$(subst .ml,.native,$(test))) -I src -cflag -rectypes;)
- # Run tests
+tests-run:
+# ============================
+# Run tests
+# ============================
ocamlbuild tests/utest_main.native
./_build/tests/utest_main.native
@@ -35,8 +43,8 @@ doc-tex:
texi2pdf ./doc/manual.texi --pdf --build=clean
# Make implementation doc
-#doc-ocaml:
-# ocamldoc
+doc-ocaml:
+ ocamldoc -html -d _build $(SRC_FILES)
.PHONY: ityper
.PHONY: typer
=====================================
doc/Compiler Structure.md
=====================================
--- a/doc/Compiler Structure.md
+++ b/doc/Compiler Structure.md
@@ -45,7 +45,7 @@ Functions:
sexp_parse sexp
node_parse_string str
-* Sexp -> Pexp: ~ Check grammar
+* Sexp -> Pexp: ~ Lexical Analysis
Identify nodes and transform them into language primitives
@@ -57,7 +57,7 @@ Functions:
pexp_p_decls % For top level declaration
pexp_p_toplevel % Parses using the appropriate parsing function
-* Pexp -> Lexp: ~ Check scopes/ declaration
+* Pexp -> Lexp: ~ Semantic Analysis
Replace variable name by their (reverse) index in the environment.
Lexps are very close to pexps
=====================================
samples/case.typer deleted
=====================================
--- a/samples/case.typer
+++ /dev/null
@@ -1,45 +0,0 @@
-% -------------------------------------------
-% Inductive type
-% -------------------------------------------
-
-
-%
-% Constructor with not args are not processed
-% correctly in case . I need type info to differentiate them
-% from variables
-%
-
-% definition
-inductive_ (dummy_Nat) (zero) (succ Nat);
-
-% declaration
-% Nat : Type; % This line is not parsed
-Nat = inductive_ (dummy_Nat) (zero) (succ Nat); % zero is not parsed
-
-% only inductive-cons is available
-inductive-cons Nat succ;
-
-% Usage
-zero = inductive-cons Nat zero; % those are aliases
-succ = inductive-cons Nat succ;
-
-one = (succ (zero));
-
-% Case test
-% x = (succ zero);
-x = (succ (succ zero));
-
-% Simple
-case x
- | succ y => y
- | _ => (2 + 4);
-
-% recursive
-tonum = lambda x -> case x
- | (succ y) => (1 + (tonum y))
- | _ => 0;
-
-(tonum x);
-
-
-
\ No newline at end of file
=====================================
samples/debug_test.typer deleted
=====================================
--- a/samples/debug_test.typer
+++ /dev/null
@@ -1,41 +0,0 @@
-%
-% Pexp Debugging: Everything must work
-% This is not meant to be correct Typer input
-%
-
-{a => "This is a block"}; % Pimm: Block
-"This is a String"; % Pimm: String
-12; % Pimm: Integer
-12.12; % Pimm: Float
-
-% Pvar
-ab;
-
-% let_in
-let a = b in
- c = b
-;
-
-% PCall
-(function arg1 arg2 arg3);
-
-% Parrow
-a -> 1;
-a => 2;
-a ≡> 1;
-
-% Lambda
-a = lambda (x, y) -> x + y;
-b = lambda (x, y) => x * y;
-c = lambda (x, y) ≡> x / y;
-
-% case
-case (a, b)
- | (1, 2) => 1
- | (_, _) => 3
-;
-
-% inductive
-% Nat : Type
-Type = inductive_ (Type_Label) (zero) (succ Type);
-inductive_ (Type_Label) (zero) (succ Type);
\ No newline at end of file
=====================================
samples/functions.typer deleted
=====================================
--- a/samples/functions.typer
+++ /dev/null
@@ -1,32 +0,0 @@
-% -------------------------------------------
-% Function Calls
-% -------------------------------------------
-
-% define sqrt
-sqr = lambda (x : Nat) -> x * x;
-
-(sqr 2);
-
-% define cube
-cube = lambda (x : Nat) -> x * (sqr x);
-
-(cube 3);
-
-% explicit
-mult = lambda (x : Nat) -> lambda (y : Nat) -> (y * x);
-
-(mult 2 3);
-
-% Not Working
-% ---------------------
-
-% implicit (Type annotation introduce a bug)
-% cube = lambda x y -> (x * y);
-
-
-% partial application
-partial_mul = (mult 2);
-
-(partial_mul 3);
-
-"FUNCTION END";
\ No newline at end of file
=====================================
samples/inductives.typer deleted
=====================================
--- a/samples/inductives.typer
+++ /dev/null
@@ -1,23 +0,0 @@
-% -------------------------------------------
-% Inductive type
-% -------------------------------------------
-
-% definition
-inductive_ (dummy_Nat) (zero) (succ Nat);
-
-
-% declaration
-% Nat : Type; % This line is not parsed
-Nat = inductive_ (dummy_Nat) (zero) (succ Nat); % zero is not parsed
-
-
-% only inductive-cons is available
-inductive-cons Nat succ;
-
-% Usage
-zero = inductive-cons Nat zero; % those are aliases
-succ = inductive-cons Nat succ;
-
-one = (succ (zero));
-one = (succ (zero));
-one = (succ (zero));
\ No newline at end of file
=====================================
samples/let.typer deleted
=====================================
--- a/samples/let.typer
+++ /dev/null
@@ -1,35 +0,0 @@
-% -------------------------------------------
-% Let
-% -------------------------------------------
-
-
-let c = 1; a = 5; b = 10; d = 3; in
- a + b;
-
-
-a = 1;
-b = 2;
-c = 3;
-d = 4;
-
-
-let a = 3; g = 1; e = 1; f = 3; in
- e + a + f + d;
-
-
-% Not Implemented
-% ----------------------
-
-
-% Type definition
-Nat = inductive_ (dummy_Nat) (zero) (succ Nat);
-
-zero = inductive-cons Nat zero;
-succ = inductive-cons Nat succ;
-
-v = (succ (succ zero));
-
-% Recursive Let
-let odd = lambda n -> case n | (zero) => false | (succ y) => (even y);
- even = lambda n -> case n | (zero) => true | (succ y) => (odd y); in
- (odd v)
\ No newline at end of file
=====================================
samples/lexer_test.typer deleted
=====================================
--- a/samples/lexer_test.typer
+++ /dev/null
@@ -1,33 +0,0 @@
-%% This file check if typer recognize correctly tokens
-
-%% builtin types
-%% ----------------
-
-%% String
-a => "The answer is 42";
-
-%% Integer
-b => 11;
-
-%% Float
-c => 3.14;
-
-%% Something
-C => 3.14.14;
-
-%% Case
-%% ----------------
-
-case (a,b)
- | (Foo, Foo) => 3.14
- | (Bar, Bar) => 3.15
-;
-
-
-%% Stuff
-%% ----------------
-
-%% Block
-{
- a => "This is a Block";
-}
\ No newline at end of file
=====================================
samples/lexp_test.typer deleted
=====================================
--- a/samples/lexp_test.typer
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
-% x : Nat;
-x = 4;
-
-x + x + x; % 12
-x * x * x; % 64
-
-sqr = lambda x -> x * x;
-% cube = lambda x -> x * x * x;
-
-(sqr x); % 16
-%(cube x);
-
-cube = lambda x -> x * (sqr x);
-(cube x); % 64
-
=====================================
samples/pretoken_test.typer deleted
=====================================
--- a/samples/pretoken_test.typer
+++ /dev/null
@@ -1,15 +0,0 @@
-%% This file check if typer recognize correctly pretokens
-
-%% Preblock
-%% --> hum, hum
-
-
-%% Prestring
-%% --> String variable
-b = "The answer is 42";
-
-
-%% Pretoken
-%% --> Everything else
-
-a = 3;
\ No newline at end of file
=====================================
src/debruijn.ml
=====================================
--- a/src/debruijn.ml
+++ b/src/debruijn.ml
@@ -90,7 +90,7 @@ let _add_var_env variable ctx =
let make_lexp_context = (_make_senv_type, _make_myers);;
(* return its current DeBruijn index *)
-let rec senv_lookup (name: string) (ctx: lexp_context) =
+let rec senv_lookup (name: string) (ctx: lexp_context): int =
let ((n, map), _) = ctx in
n - (StringMap.find name map) - 1
;;
=====================================
src/eval.ml
=====================================
--- a/src/eval.ml
+++ b/src/eval.ml
@@ -39,10 +39,6 @@ open Fmt
open Debruijn
open Grammar
-(* Value type *)
-type value_type =
- | Void
- | Val of lexp
let _eval_error loc msg =
msg_error "eval" loc msg;
@@ -84,7 +80,7 @@ let get_function_name fname =
let get_int lxp =
match lxp with
| Imm(Integer(_, l)) -> l
- | _ -> lexp_print (Ltexp(lxp)); -40
+ | _ -> lexp_print lxp; -40
;;
(* Runtime Environ *)
@@ -92,7 +88,11 @@ type runtime_env = (string option * lexp) myers
let make_runtime_ctx = nil;;
let add_rte_variable name x l = (cons (name, x) l);;
-let get_rte_variable idx l = let (_, x) = (nth (idx) l) in x;;
+let get_rte_variable (idx: int) (l: runtime_env): lexp =
+ let (_, x) = (nth idx l) in x
+;;
+
+let get_rte_size (l: runtime_env): int = length l;;
let print_rte_ctx l = print_myers_list l
(fun (n, g) ->
@@ -100,7 +100,7 @@ let print_rte_ctx l = print_myers_list l
match n with
| Some m -> lalign_print_string m 12; print_string " | "
| None -> print_string (make_line ' ' 12); print_string " | " in
- lexp_print (Ltexp(g)); print_string "\n")
+ lexp_print g; print_string "\n")
;;
@@ -113,29 +113,25 @@ let nfirst_rte_var n ctx =
loop 0 []
;;
-(* *)
-let rec eval_toplevel ltop ctx: (value_type * runtime_env) =
- global_trace := []; (* Clean up trace info *)
- (* I have to use a sexp because declaration are not "carried" *)
- match ltop with
- (* Eval expression and return results *)
- | Ltexp(x) ->
- let a, b = _eval x ctx 0 in
- Val(a), ctx
- (* Add declaration to environment. return void *)
- | Ltdecl(a, b, c) -> Void, (eval_decl (a, b, c) ctx)
+(* currently, we don't do much *)
+type value_type = lexp
+
+(* This is an internal definition
+ * 'i' is the recursion depth used to print the call trace *)
+let rec _eval lxp ctx i: (value_type) =
-(* _eval is an internal definition you should use eval or eval_toplevel *)
-and _eval lxp ctx i: (lexp * runtime_env) =
+ (if i > 255 then
+ raise (internal_error "Recursion Depth exceeded"));
+
add_call lxp i;
match lxp with
(* This is already a leaf *)
- | Imm(v) -> lxp, ctx
+ | Imm(v) -> lxp
(* Return a value stored in the environ *)
| Var((loc, name), idx) -> begin
try
- (get_rte_variable idx ctx), ctx
+ (get_rte_variable idx ctx)
with
Not_found ->
print_string ("Variable: " ^ name ^ " was not found | ");
@@ -144,13 +140,10 @@ and _eval lxp ctx i: (lexp * runtime_env) =
(* this works for non recursive let *)
| Let(_, decls, inst) -> begin
- (* First we _evaluate all declaration then we eval the instruction *)
-
+ (* First we _evaluate all declaration *)
let nctx = build_ctx decls ctx i in
-
- let value, nctx = _eval inst nctx (i + 1) in
- (* return old context as we exit let's scope*)
- value, ctx end
+ (* Then we eval the body *)
+ _eval inst nctx (i + 1) end
(* Function call *)
| Call (lname, args) -> (
@@ -165,7 +158,7 @@ and _eval lxp ctx i: (lexp * runtime_env) =
let l = get_int (get_rte_variable 0 nctx) in
let r = get_int (get_rte_variable 1 nctx) in
- Imm(Integer(dloc, l + r)), ctx
+ Imm(Integer(dloc, l + r))
(* _*_ is reas as a single function with x args *)
| Var((_, name), _) when name = "_*_" ->
@@ -175,31 +168,35 @@ and _eval lxp ctx i: (lexp * runtime_env) =
let varg = List.map (fun g -> get_int g) vint in
let v = List.fold_left (fun a g -> a * g) 1 varg in
- Imm(Integer(dloc, v)), ctx
+ Imm(Integer(dloc, v))
(* This is a named function call *)
- (* TODO: handle partial application *)
| Var((_, name), idx) ->
-
+ (* Check if the call is a constructor call *)
+
(* get function body *)
let body = get_rte_variable idx ctx in
+
(* Add args in the scope *)
let nctx = build_arg_list args ctx i in
- let e, nctx = (_eval body nctx (i + 1)) in
-
- (* we exit function and send back old ctx *)
- e, ctx
+ (* eval body *)
+ _eval body nctx (i + 1)
(* TODO Everything else *)
(* Which includes a call to a lambda *)
- | _ -> Imm(String(dloc, "Funct Not Implemented")), ctx)
+ | _ -> Imm(String(dloc, "Funct Not Implemented")))
+ (* Lambdas have one single mandatory argument *)
+ (* Nested lambda are collapsed then executed *)
+ (* I am thinking about building a 'get_free_variable' to be able to *)
+ (* handle partial application i.e build a new lambda if Partial App *)
| Lambda(_, vr, _, body) -> begin
let (loc, name) = vr in
(* Get first arg *)
let value = (get_rte_variable 0 ctx) in
let nctx = add_rte_variable (Some name) value ctx in
+ (* Collapse nested lambdas *)
let rec build_body bd idx nctx =
match bd with
| Lambda(_, vr, _, body) ->
@@ -212,45 +209,61 @@ and _eval lxp ctx i: (lexp * runtime_env) =
| _ -> bd, nctx in
let body, nctx = build_body body 1 nctx in
-
- let e, nctx = _eval body nctx (i + 1) in
- e, ctx end
+ (* eval lambda body *)
+ _eval body nctx (i + 1) end
(* Inductive is a type declaration. We have nothing to eval *)
- | Inductive (_, _, _, _) as e -> e, ctx
+ | Inductive (_, _, _, _) as e -> e
(* inductive-cons build a type too? *)
- | Cons (_, _) as e -> e, ctx
+ | Cons (_, _) as e -> e
(* Case *)
| Case (loc, target, _, pat, dflt) -> begin
(* Eval target *)
- let v, nctx = _eval target ctx (i + 1) in
+ let v = _eval target ctx (i + 1) in
+
+ let check_ctor ctor_name type_idx =
+ let info = get_rte_variable type_idx ctx in
+ match info with
+ | Inductive(_, _, _, ctor_def) -> SMap.find ctor_name ctor_def
+ | _ -> _eval_error loc "Target is not a Constructor" in
+
+ (* 'v' must be a constructor *)
+ let ctor_name, args, idx = match v with
- (* V must be a constructor Call *)
- let ctor_name, args = match v with
+ (* multi arg constructor are parsed as Call *)
| Call(lname, args) -> (match lname with
- | Var((_, ctor_name), _) -> ctor_name, args
- | _ -> _eval_error loc "Target is not a Constructor" )
- (*
- | Cons((_, idx), (_, cname)) -> begin
- (* retrieve type definition *)
- let info = get_rte_variable idx ctx in
- let Inductive(_, _, _, ctor_def) = info in
- try let args = SMap.find cname ctor_def in
- cname, args
- with
- Not_found ->
- _eval_error loc "Constructor does not exist" end *)
+ | Var((_, ctor_name), idx) ->
+ let offset = (get_rte_size ctx) - idx - 1 in
+ let tidx = idx + offset in
+ ctor_name, args, tidx
+
+ | _ -> _eval_error loc "Target is not a Constructor" )
+
+ | Cons((_, idx), (_, cname)) ->
+ let offset = (get_rte_size ctx) - idx - 1 in
+ let tidx = idx + offset in
+ cname, [], tidx
- | _ -> lexp_print (Ltexp(target));
+ | _ -> lexp_print v;
_eval_error loc "Can't match expression" in
+
+ (* Check if the constructor was defined *)
+ let targs = try check_ctor ctor_name idx
+ with Not_found -> _eval_error loc "Constructor does not exist" in
+ (* Check number of args *)
+ let n_targs = List.length targs in
+ let n_args = List.length args in
+ (if n_targs != n_args then
+ _eval_error loc "Wrong number of arguments");
+
(* Check if a default is present *)
let run_default df =
match df with
- | None -> Imm(String(loc, "Match Failure")), ctx
+ | None -> Imm(String(loc, "Match Failure"))
| Some lxp -> _eval lxp ctx (i + 1) in
let ctor_n = List.length args in
@@ -279,19 +292,16 @@ and _eval lxp ctx i: (lexp * runtime_env) =
| Some (_, (_, name)) -> let (_, xp) = cl in
add_rte_variable (Some name) xp nctx)
- nctx pat_args args in
-
- let r, nctx = _eval exp nctx (i + 1) in
- (* return old context as we exist the case *)
- r, ctx end
+ ctx pat_args args in
+ (* eval body *)
+ _eval exp ctx (i + 1) end
- | _ -> Imm(String(dloc, "eval Not Implemented")), ctx
+ | _ -> Imm(String(dloc, "eval Not Implemented"))
and build_arg_list args ctx i =
(* _eval every args *)
let arg_val = List.map (
- fun (k, e) ->
- let (v, c) = _eval e ctx (i + 1) in v)
+ fun (k, e) -> _eval e ctx (i + 1))
args in
(* Add args inside context *)
@@ -302,47 +312,35 @@ and build_ctx decls ctx i =
| [] -> ctx
| hd::tl ->
let (v, exp, tp) = hd in
- let (value, nctx) = _eval exp ctx (i + 1) in
- let nctx = add_rte_variable None value nctx in
- build_ctx tl nctx (i + 1)
+ let value = _eval exp ctx (i + 1) in
+ let nctx = add_rte_variable None value ctx in
+ build_ctx tl nctx i
and eval_decl ((l, n), lxp, ltp) ctx =
add_rte_variable (Some n) lxp ctx
+
+(* Eval a declaration if a main is found it is returned *)
+and eval_decls (decls: ((vdef * lexp * ltype) list))
+ (ctx: runtime_env): runtime_env =
+ let rec loop decls ctx =
+ match decls with
+ | [] -> ctx
+ | hd::tl ->
+ let ((_, n), lxp, ltp) = hd in
+ let nctx = add_rte_variable (Some n) lxp ctx in
+ loop tl nctx in
+
+ loop decls ctx
-and print_eval_result i tlxp =
- match tlxp with
- | Void -> ()
- | Val(lxp) ->
+and print_eval_result i lxp =
print_string " Out[";
ralign_print_int i 2;
print_string "] >> ";
match lxp with
| Imm(v) -> sexp_print v; print_string "\n"
- | e -> lexp_print (Ltexp(e)); print_string "\n"
-;;
-
-
-let print_first n l f =
- let rec loop i l =
- match l with
- | [] -> ()
- | hd::tl ->
- if i < n then ((f i hd); loop (i + 1) tl;)
- else () in
- loop 0 l
-;;
+ | e -> lexp_print e; print_string "\n"
-let _print_ct_tree i =
- print_string " ";
- let rec loop j =
- if j = i then () else
- match j with
- | _ when (j mod 2) = 0 -> print_char '|'; loop (j + 1)
- | _ -> print_char ':'; loop (j + 1) in
- loop 0
-;;
-
-let print_call_trace () =
+and print_call_trace () =
print_string (make_title " CALL TRACE ");
let n = List.length !global_trace in
@@ -350,63 +348,36 @@ let print_call_trace () =
print_string (make_sep '-');
let racc = List.rev !global_trace in
- print_first 20 racc (fun j (i, g) ->
+ print_first 50 racc (fun j (i, g) ->
_print_ct_tree i; print_string "+- ";
print_string (lexp_to_string g); print_string ": ";
- lexp_print (Ltexp(g)); print_string "\n");
+ lexp_print g; print_string "\n");
print_string (make_sep '=');
;;
+(* eval_expr *)
let eval lxp ctx =
try
- let r, c = eval_toplevel lxp ctx in
- (r, c)
+ (_eval lxp ctx 1)
with e -> (
print_rte_ctx ctx;
print_call_trace ();
raise e)
;;
-
-
-let evalprint lxp ctx =
- let v, ctx = (eval_toplevel lxp ctx) in
- print_eval_result 0 v;
- ctx
-;;
-
(* Eval a list of lexp *)
-let eval_all lxps rctx =
- let rec _eval_all lxps acc rctx =
- match lxps with
- | [] -> (List.rev acc), rctx
- | hd::tl ->
- let lxp, rctx = eval hd rctx in
- _eval_all tl (lxp::acc) rctx in
- (_eval_all lxps [] rctx)
-;;
+let eval_all lxps rctx = List.map (fun g -> eval g rctx) lxps;;
-(* Eval a string given a context *)
-let eval_string (str: string) tenv grm limit lxp_ctx rctx =
- let lxps, lxp_ctx = lexp_parse_string str tenv grm limit lxp_ctx in
- (eval_all lxps rctx), lxp_ctx
+(* Eval String
+ * ---------------------- *)
+let eval_expr_str str lctx rctx =
+ global_trace := [];
+ let lxps, lctx = lexp_expr_str str lctx in
+ (eval_all lxps rctx)
;;
-(* EVAL a string. Contexts are discarded *)
-let easy_eval_string str =
- let tenv = default_stt in
- let grm = default_grammar in
- let limit = (Some ";") in
- let eval_string str clxp rctx = eval_string str tenv grm limit clxp rctx in
- let clxp = make_lexp_context in
- (* Those are hardcoded operation *)
- let clxp = add_def "_+_" clxp in
- let clxp = add_def "_*_" clxp in
- let clxp = add_def "_=_" clxp in
-
- let rctx = make_runtime_ctx in
- let (ret, rctx), clxp = (eval_string str clxp rctx) in
- ret
+let eval_decl_str str lctx rctx =
+ let lxps, lctx = lexp_decl_str str lctx in
+ (eval_decls lxps rctx), lctx
;;
-
=====================================
src/fmt.ml
=====================================
--- a/src/fmt.ml
+++ b/src/fmt.ml
@@ -103,5 +103,27 @@ let make_rheader (head: (((char* int) option * string) list)) =
let make_sep c = " " ^ (make_line c 76) ^ "\n";;
+(* used to help visualize the call trace *)
+let _print_ct_tree i =
+ print_string " ";
+ let rec loop j =
+ if j = i then () else
+ match j with
+ | _ when (j mod 2) = 0 -> print_char '|'; loop (j + 1)
+ | _ -> print_char ':'; loop (j + 1) in
+ loop 0
+;;
+
+(* iterate of first n of a list l and apply f *)
+let print_first n l f =
+ let rec loop i l =
+ match l with
+ | [] -> ()
+ | hd::tl ->
+ if i < n then ((f i hd); loop (i + 1) tl;)
+ else () in
+ loop 0 l
+;;
+
=====================================
src/lparse.ml
=====================================
--- a/src/lparse.ml
+++ b/src/lparse.ml
@@ -68,18 +68,6 @@ type print_context = (bool * int * bool)
(* Vdef is exactly similar to Pvar but need to modify our ctx *)
let pvar_to_vdef p = p;;
-type ltop =
- | Ltexp of lexp
- | Ltdecl of vdef * lexp * ltype
-;;
-
-
-let lexp_location_toplevel ltp =
- match ltp with
- | Ltexp(x) -> lexp_location x
- | Ltdecl((l, _), _, _) -> l
-;;
-
(* PEXP is not giving SEXP types this is why types are always unknown *)
(*
@@ -101,22 +89,8 @@ let lexp_location_toplevel ltp =
*
*)
-(* Process a top-level expression *)
-let rec lexp_p_toplevel (p: ptop) (ctx: lexp_context) =
-
- (* Identify if the expression is a declaration *)
- match p with
- (* Declaration *)
- | Ptdecl (x, p) ->
- let (a, b, c), ctx = lexp_p_decls (x, p, None) ctx in
- Ltdecl(a, b, c), ctx
-
- (* Everything else*)
- | Ptexp (x) -> let x, ctx = lexp_parse x ctx in
- Ltexp(x), ctx
-
-(**)
-and lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
+
+let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
(* So I don't have to extract it *)
let tloc = pexp_location p in
match p with
@@ -137,7 +111,7 @@ and lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
(* Let, Variable declaration + local scope *)
| Plet(loc, decls, body) ->
- let decl, nctx = lexp_parse_let decls ctx in
+ let decl, nctx = lexp_decls decls ctx in
(* Body cannot modify context *)
let bdy, _ = lexp_parse body nctx in
(* Send back old context as we exit the inner scope *)
@@ -159,25 +133,28 @@ and lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
| Plambda (kind, var, Some ptype, body) ->
(* Add argument to context *)
let (loc, vname) = var in
+ let ltp, nctx = lexp_parse ptype ctx in (* Get Type *)
+
let nctx = senv_add_var vname loc ctx in
- let ltp, nctx = lexp_parse ptype nctx in (* Get Type *)
let nctx = env_add_var_info (0, (loc, vname), dlxp, ltp) nctx in
- let ltyp, nctx = lexp_parse ptype nctx in
- let lbody, nctx = lexp_parse body nctx in
+ let lbody, _ = lexp_parse body nctx in
(* Return old context as we exit lambda scope*)
- Lambda(kind, var, ltyp, lbody), ctx
+ Lambda(kind, var, ltp, lbody), ctx
| Plambda (kind, var, None, body) ->
let (loc, vname) = var in
+
let nctx = senv_add_var vname loc ctx in
let nctx = env_add_var_info (0, (loc, vname), dlxp, dltype) nctx in
- let lbody, ctx = lexp_parse body nctx in
+ let lbody, _ = lexp_parse body nctx in
Lambda(kind, var, UnknownType(tloc), lbody), ctx
- | Pcall (fname, _args) -> lexp_call fname _args ctx
+ | Pcall (fname, _args) ->
+ let r, c = lexp_call fname _args ctx in
+ r, ctx
(* Pinductive *)
| Pinductive (label, [], ctors) ->
@@ -201,6 +178,7 @@ and lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
(* Pcase *)
| Pcase (loc, target, patterns) ->
+
(* I need type info HERE *)
let lxp, nctx = lexp_parse target ctx in
let ltp = UnknownType(loc) in
@@ -212,9 +190,10 @@ and lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
| hd::tl ->
let (pat, exp) = hd in
(* Create pattern context *)
- let (name, iloc, arg), nctx = lexp_read_pattern pat exp lxp nctx in
+ let (name, iloc, arg), nctx2 =
+ lexp_read_pattern pat exp lxp nctx in
(* parse using pattern context *)
- let exp, nctx = lexp_parse exp nctx in
+ let exp, _ = lexp_parse exp nctx2 in
if name = "_" then
loop tl merged (Some exp)
@@ -243,7 +222,7 @@ and lexp_call (fname: pexp) (_args: sexp list) ctx =
| Pcons (_, (loc, nm)) -> nm, loc
| _ -> raise Not_found in
- let largs, fctx = lexp_p_all pargs ctx in
+ let largs, fctx = lexp_parse_all pargs ctx in
let new_args = List.map (fun g -> (Aexplicit, g)) largs in
try
@@ -262,7 +241,7 @@ and lexp_call (fname: pexp) (_args: sexp list) ctx =
(* Call to a nameless function *)
with Not_found ->
- let largs, fctx = lexp_p_all pargs ctx in
+ let largs, fctx = lexp_parse_all pargs ctx in
let new_args = List.map (fun g -> (Aexplicit, g)) largs in
(* I think this should not modify context.
* if so, funny things might happen when evaluating *)
@@ -277,13 +256,19 @@ and lexp_read_pattern pattern exp target ctx:
| Ppatany (loc) -> (* Catch all expression nothing to do *)
("_", loc, []), ctx
- | Ppatvar (loc, name) ->
- (* FIXME What if it is a constructor with no arg ? *)
-
- (* Create a variable containing target *)
- let nctx = senv_add_var name loc ctx in
- let nctx = env_add_var_info (0, (loc, name), target, dltype) nctx in
- (name, loc, []), nctx
+ | Ppatvar (loc, name) ->(
+ (* FIXME better check *)
+ try
+ let idx = senv_lookup name ctx in
+ (* constructor with no args *)
+ (name, loc, []), ctx
+
+ (* would it not make a default match too? *)
+ with Not_found ->
+ (* Create a variable containing target *)
+ let nctx = senv_add_var name loc ctx in
+ let nctx = env_add_var_info (0, (loc, name), target, dltype) nctx in
+ ("_", loc, []), nctx)
| Ppatcons (ctor_name, args) ->
let (loc, name) = ctor_name in
@@ -294,7 +279,7 @@ and lexp_read_pattern pattern exp target ctx:
(* Read patterns inside a constructor *)
and lexp_read_pattern_args args ctx:
- (((arg_kind * vdef) option list) * lexp_context)=
+ (((arg_kind * vdef) option list) * lexp_context)=
let rec loop args acc ctx =
match args with
@@ -344,58 +329,24 @@ and lexp_parse_constructors ctors ctx =
end in
loop ctors SMap.empty ctx
-
-(* Merge Type info and variable declaration together *)
-(* Type info must be first then declaration else type will be inferred *)
-and lexp_merge_info (decls: (pvar * pexp * bool) list) =
- match decls with
- | [] -> lexp_fatal dloc "Empty Declaration List"
- | hd::tl -> (match hd with
- (* Declaration without type info *)
- | ((l, n1), expr, true) -> (
- match tl with
- | [] -> lexp_fatal l "Unused Type info declaration";
- | ((_, _), expr2, true)::_ -> lexp_merge_info tl
- | ((_, n2), expr2, _)::_ when n2 != n1 ->
- (lexp_warning l "Unused Type info declaration";
- lexp_merge_info tl)
- | ((_, _), expr2, _)::ttl ->
- ((l, n1), expr2, Some expr), (ttl))
-
- (* Declaration without type info *)
- | (v, expr, false) -> (v, expr, None), tl)
-
-(* Add declaration in the environment *)
-and lexp_p_decls (decl: (pvar * pexp * pexp option)) ctx =
- let ((loc, vname), pxp, _) = decl in
-
- (* we should add the defined var to ctx *)
- let nctx = senv_add_var vname loc ctx in
-
- (*let idx = senv_lookup vname nctx in *)
- let lxp, ltp = lexp_p_infer pxp nctx in
-
- (* Add Var info*)
- let nctx = env_add_var_info (0, (loc, vname), lxp, ltp) nctx in
-
- (* return processed var *)
- ((loc, vname), lxp, ltp), nctx
(* Parse let declaration *)
-and lexp_parse_let decls ctx =
+and lexp_decls decls ctx: (((vdef * lexp * ltype) list) * lexp_context) =
(* Merge Type info and declaration together *)
(* We use a list because order matters and Maps reorder elements *)
+ (*
let rec is_equal target (p:(vdef * pexp option * pexp option)): bool =
let ((_, name), _, _) = p in
- if name == target then true else false in
+ if name == target then true else false in *)
- let rec merge_decls (decls: (pvar * pexp * bool) list) merged:
- (vdef * pexp option * pexp option) list =
+ (* merge with a map to guarantee uniqueness. *)
+ let rec merge_decls (decls: (pvar * pexp * bool) list) merged acc:
+ ((location * pexp option * pexp option) SMap.t * string list) =
(* we cant evaluate here because variable are not in the environment *)
match decls with
- | [] -> List.rev merged
+ | [] -> merged, (List.rev acc)
| hd::tl ->
match hd with
(* Type Info: Var:Type *)
@@ -403,24 +354,35 @@ and lexp_parse_let decls ctx =
try
(* If found its means the instruction was declared
* before the type info. Should we allow this? *)
- let (vd, inst, _) = List.find (is_equal name) merged in
- let new_decl = (vd, inst, Some type_info) in
- (merge_decls tl (new_decl::merged))
+ let (l, inst, _) = SMap.find name merged in
+ let new_decl = (l, inst, Some type_info) in
+ let nmerged = SMap.add name new_decl merged in
+ (merge_decls tl nmerged acc)
with Not_found ->
- let new_decl = (loc, name), None, Some type_info in
- (merge_decls tl (new_decl::merged)) end
+ let new_decl = (loc, None, Some type_info) in
+ let nmerged = SMap.add name new_decl merged in
+ (merge_decls tl nmerged (name::acc)) end
(* Instruction: Var = expr *)
| ((loc, name), inst, false) -> begin
try
- let (vd, _, ptyp) = List.find (is_equal name) merged in
- let new_decl = (vd, Some inst, ptyp) in
- (merge_decls tl (new_decl::merged))
+ let (l, _, tp) = SMap.find name merged in
+ let new_decl = (l, Some inst, tp) in
+ let nmerged = SMap.add name new_decl merged in
+ (merge_decls tl nmerged acc)
+
with Not_found ->
- let new_decl = ((loc, name), Some inst, None) in
- (merge_decls tl (new_decl::merged)) end in
+ let new_decl = (loc, Some inst, None) in
+ let nmerged = SMap.add name new_decl merged in
+ (merge_decls tl nmerged (name::acc)) end in
- let decls = merge_decls decls [] in
+ let mdecls, ord = merge_decls decls SMap.empty [] in
+
+ (* cast map to list*)
+ let decls = List.map (fun name ->
+ let (l, inst, tp) = SMap.find name mdecls in
+ ((l, name), inst, tp) ) ord
+ in
(* Add Each Variable to the environment *)
let nctx = List.fold_left (fun ctx hd ->
@@ -428,9 +390,11 @@ and lexp_parse_let decls ctx =
| (_, None, _) -> ctx (* Unused variable: No Instruction *)
| ((loc, name), _, _) -> senv_add_var name loc ctx)
ctx decls in
+
+ let n_decls = List.length decls in
(* Add Variable info *)
- let rec process_var_info dcl_lst _ctx acc =
+ let rec process_var_info dcl_lst _ctx acc i =
match dcl_lst with
| [] -> (List.rev acc), _ctx
| hd::tl ->
@@ -438,33 +402,24 @@ and lexp_parse_let decls ctx =
| ((loc, name), Some pinst, None) ->(
let lxp, ltp = lexp_p_infer pinst _ctx in
let nacc = ((loc, name), lxp, ltp)::acc in
- let ctx2 = env_add_var_info (0, (loc, name), lxp, ltp) _ctx in
- process_var_info tl ctx2 nacc)
+ let ctx2 = env_add_var_info (n_decls - i, (loc, name), lxp, ltp) _ctx in
+ process_var_info tl ctx2 nacc (i + 1))
| ((loc, name), Some pinst, Some ptype) ->(
let linst, ctx1 = lexp_parse pinst _ctx in
let ltyp, ctx2 = lexp_parse ptype ctx1 in
let nacc = ((loc, name), linst, ltyp)::acc in
- let ctx3 = env_add_var_info (0, (loc, name), linst, ltyp) ctx2 in
- process_var_info tl ctx3 nacc)
+ let ctx3 = env_add_var_info (n_decls - i, (loc, name), linst, ltyp) ctx2 in
+ process_var_info tl ctx3 nacc (i + 1))
(* Skip the variable *)
- | ((loc, name), None, _) -> (lexp_warning loc "Unused Variable";
- process_var_info tl _ctx acc) in
+ | ((loc, name), None, _) -> (lexp_warning loc ("Unused Variable: " ^ name);
+ process_var_info tl _ctx acc i) in
- let acc, ctx = process_var_info decls nctx [] in
+ let acc, ctx = process_var_info decls nctx [] 0 in
acc, ctx
-and lexp_parse_all (p: ptop list) (ctx: lexp_context):
- (ltop list * lexp_context) =
- let rec loop (plst: ptop list) ctx (acc: ltop list) =
- match plst with
- | [] -> ((List.rev acc), ctx)
- | _ -> let lxp, new_ctx = lexp_p_toplevel (List.hd plst) ctx in
- (loop (List.tl plst) new_ctx (lxp::acc)) in
- (loop p ctx [])
-
-and lexp_p_all (p: pexp list) (ctx: lexp_context):
+and lexp_parse_all (p: pexp list) (ctx: lexp_context):
(lexp list * lexp_context) =
let rec loop (plst: pexp list) ctx (acc: lexp list) =
match plst with
@@ -472,7 +427,7 @@ and lexp_p_all (p: pexp list) (ctx: lexp_context):
| _ -> let lxp, new_ctx = lexp_parse (List.hd plst) ctx in
(loop (List.tl plst) new_ctx (lxp::acc)) in
(loop p ctx [])
-
+
(*
* Type Inference
* --------------------- *)
@@ -506,6 +461,7 @@ and lexp_p_check (p : pexp) (t : ltype) (env : lexp_context): lexp =
(*
* Printing
* --------------------- *)
+
(* Print back in CET (Close Enough Typer) easier to read *)
(* So print can be called while parsing *)
and lexp_print_adv opt exp =
@@ -676,18 +632,22 @@ and lexp_print_var_info ctx =
done;
;;
-let lexp_print e =
- match e with
- | Ltexp (x) -> lexp_print_adv (false, 0, true) x
- | Ltdecl ((_, x), lxp, ltp) ->
- print_string x;
- print_string " = ";
- lexp_print_adv (false, 0, true) lxp;
- print_string " : ";
- lexp_print_adv (false, 0, true) ltp
-;;
-
-let lexp_parse_string (str: string) tenv grm limit ctx =
+let lexp_print e = lexp_print_adv (false, 0, true) e;;
+
+
+(* add dummy definition helper *)
+let add_def name ctx =
+ let ctx = senv_add_var name dloc ctx in
+ env_add_var_info (0, (dloc, name), dlxp, dlxp) ctx
+;;
+
+
+(* String Parsing
+ * ------------------------ *)
+
+(* Lexp helper *)
+let _lexp_expr_str (str: string) (tenv: bool array)
+ (grm: grammar) (limit: string option) (ctx: lexp_context) =
let pretoks = prelex_string str in
let toks = lex tenv pretoks in
let sxps = sexp_parse_all_to_list grm toks limit in
@@ -695,8 +655,22 @@ let lexp_parse_string (str: string) tenv grm limit ctx =
lexp_parse_all pxps ctx
;;
-(* add dummy definition helper *)
-let add_def name ctx =
- let ctx = senv_add_var name dloc ctx in
- env_add_var_info (0, (dloc, name), dlxp, dlxp) ctx
+(* specialized version *)
+let lexp_expr_str str lctx =
+ _lexp_expr_str str default_stt default_grammar (Some ";") lctx
+;;
+
+
+let _lexp_decl_str (str: string) tenv grm limit ctx =
+ let pretoks = prelex_string str in
+ let toks = lex tenv pretoks in
+ let sxps = sexp_parse_all_to_list grm toks limit in
+ let pxps = pexp_decls_all sxps in
+ lexp_decls pxps ctx
;;
+
+(* specialized version *)
+let lexp_decl_str str lctx =
+ _lexp_decl_str str default_stt default_grammar (Some ";") lctx
+;;
+
=====================================
src/pexp.ml
=====================================
--- a/src/pexp.ml
+++ b/src/pexp.ml
@@ -24,6 +24,7 @@ open Util
open Sexp
open Lexer
open Prelexer
+open Grammar
let pexp_error = msg_error "PEXP"
@@ -62,14 +63,6 @@ type pexp =
| Pcons of pvar * symbol
| Pcase of location * pexp * (ppat * pexp) list
-(* Top level expression annotation *)
-type ptop =
- | Ptexp of pexp
- (* Declarations *)
- | Ptann of pvar * pexp (* Type annotation *)
- | Ptdecl of pvar * pexp (* Declaration *)
- | Ptanndecl of pvar * pexp * pexp (* Annotated declaration *)
- | Ptnone
let rec pexp_location e =
match e with
@@ -92,27 +85,9 @@ let rec pexp_pat_location e = match e with
| Ppatcons ((l, _), _) -> l
;;
-let pexp_location_toplevel e =
- match e with
- | Ptexp (x) -> pexp_location x
- | Ptdecl ((x, _), _) -> x
- | Ptann ((x, _), _) -> x
- | Ptanndecl((x, _), _, _) -> x
-;;
-
-(* We use a list so we can merge 2 contiguous definitions *)
-let rec pexp_p_toplevel (s : sexp): ptop =
-
- match s with
- | Node (Symbol (_, "_:_"), _) ->
- let (a, b, _)::_ = pexp_p_decls s in Ptann (a, b)
- | Node (Symbol (_, "_=_"), _) ->
- let (a, b, _)::_ = pexp_p_decls s in Ptdecl (a, b)
- | _ -> Ptexp(pexp_parse s)
-
(* In the following "pexp_p" the prefix for "parse a sexp, returning a pexp"
* and "pexp_u" is the prefix for "unparse a pexp, returning a sexp". *)
-and pexp_parse (s : sexp) : pexp =
+let rec pexp_parse (s : sexp) : pexp =
match s with
(* This is an internal error because Epsilon does not have any location
* information so it needs to be caught elsewhere. *)
@@ -378,23 +353,45 @@ and pexp_u_decls ds =
let pexp_print e = sexp_print (pexp_unparse e)
-let pexp_print_toplevel e =
- match e with
- | Ptexp (x) -> pexp_print x
- | Ptdecl ((_, n), e) -> print_string (n ^ " = "); pexp_print e;
- | Ptann ((_, n), e) -> print_string (n ^ " : "); pexp_print e;
- | Ptanndecl((_, n), e, t) -> print_string (n ^ " = "); pexp_print e;
+let pexp_decls_all (nodes: sexp list): ((pvar * pexp * bool) list) =
+ let rec loop nodes acc =
+ match nodes with
+ | [] -> acc
+ | hd::tl ->
+ let r = pexp_p_decls hd in
+ let nacc = List.append acc r in
+ loop tl nacc in
+ loop nodes []
;;
-
-
+
(* Parse All Pexp as a list *)
let pexp_parse_all (nodes: sexp list) =
- List.map pexp_p_toplevel nodes
+ List.map pexp_parse nodes
;;
-let pexp_parse_string (str: string) tenv grm limit =
+(* Pexp String
+ * ------------------- *)
+let _pexp_expr_str (str: string) tenv grm limit =
let pretoks = prelex_string str in
let toks = lex tenv pretoks in
let sxps = sexp_parse_all_to_list grm toks limit in
pexp_parse_all sxps
;;
+
+let pexp_expr_str str =
+ _pexp_expr_str str default_stt default_grammar (Some ";")
+;;
+
+
+let _pexp_decl_str (str: string) tenv grm limit =
+ let pretoks = prelex_string str in
+ let toks = lex tenv pretoks in
+ let sxps = sexp_parse_all_to_list grm toks limit in
+ pexp_decls_all sxps
+;;
+
+let pexp_decl_str str =
+ _pexp_decl_str str default_stt default_grammar (Some ";")
+;;
+
+
=====================================
tests/REPL.ml
=====================================
--- a/tests/REPL.ml
+++ b/tests/REPL.ml
@@ -45,7 +45,81 @@ let rec read_input i =
loop "" 1
;;
+(* Interactive mode is not usual typer
+ * It makes things easier to test out code *)
+type ptop =
+ | Pdecl of pvar * pexp * bool
+ | Pexpr of pexp
+
+let ipexp_parse p =
+ match p with
+ (* Declaration *)
+ | Node (Symbol (_, "_=_"), [Symbol s; t]) ->
+ let (a, b, c)::_ = pexp_p_decls nod in
+ Pdecl(a, b, c)
+ | Node (Symbol (_, "_:_"), [Symbol s; t]) ->
+ let (a, b, c)::_ = pexp_p_decls nod in
+ Pdecl(a, b, c)
+ (* Expression *)
+ | _ -> let a = pexp_parse nod in Pexpr(a)
+;;
+
+let ipexp_parse_all ps = List.map ipexp_parse ps;;
+
+type ltop =
+ | Ldecl of vdef * lexp * ltype
+ | Lexpr of lexp
+
+let ilexp_parse l lctx =
+ match l with
+ | Pdecl(_, _, _) -> let (a, b, c), d = lexp_decls [l] ctx in
+ Ldecl(a, b, c), d
+ | Pexpr(x) -> let v, c = lexp_parse x lctx in
+ Lexpr(v), c
+
+let ilexp_parse_all ls lctx =
+ let rec loop lst acc ctx =
+ match lst with
+ | [] -> List.rev acc, ctx
+ | hd::tl ->
+ let x, c = ilexp_parse hd ctx in
+ let nacc = acc::x in
+ loop tl nacc c in
+ loop ls [] lctx
+
+type ival =
+ | Ivoid
+ | Ival of lexp
+let ieval xpr rctx =
+ match xpr with
+ | Ldecl(_, _, _) -> let r = eval_decls xpr rctx in
+ Ivoid, rctx
+ | Lexpr(x) -> let v, _ = eval x rctx in
+ Ival(v), rctx
+
+let ieval_all xprs rctx =
+ let rec loop lst acc ctx =
+ match lst with
+ | [] -> List.rev acc, ctx
+ | hd::tl ->
+ let x, c = ieval hd ctx in
+ let nacc = acc::x in
+ loop tl nacc c in
+ loop xprs [] rctx
+
+let ieval_string str lctx rctx =
+ let pres = prelex_string str in
+ let sxps = lex default_stt pres in
+ let nods = sexp_parse_all_to_list default_grammar sxps (Some ";") in
+
+ (* Different from usual typer *)
+ let pxps = ipexp_parse_all nods in
+ let lxps, ctx = ilexp_parse_all pxps lctx in
+ let v, rctx = ieval_all lxps rctx in
+ v, lctx, rctx
+;;
+
(* Specials commands %[command-name] *)
let rec repl () =
let tenv = default_stt in
@@ -71,9 +145,15 @@ let rec repl () =
(print_call_trace (); loop (i + 1) clxp rctx)
(* Else Process Typer code *)
else
- let (ret, rctx), clxp = (eval_string ipt clxp rctx) in
- let print_e j v = print_eval_result i v in
+ let (ret, clxp, rctx) = (ieval_string ipt clxp rctx) in
+
+ let print_e j v =
+ match b with
+ | Ivoid -> ()
+ | Ival(x) -> print_eval_result i x in
+
List.iteri print_e ret;
+
loop (i + 1) clxp rctx in
loop 1 lxp_ctx rctx
=====================================
tests/debug.ml
=====================================
--- a/tests/debug.ml
+++ b/tests/debug.ml
@@ -42,6 +42,8 @@ open Lexp
open Lparse
open Debruijn
open Fmt
+open Grammar
+open Eval
(* Print aPretokens *)
let rec debug_pretokens_print pretoken =
@@ -116,30 +118,37 @@ let debug_sexp_print_all tokens =
(* Print a Pexp with debug info *)
let debug_pexp_print ptop =
print_string " ";
- let l = pexp_location_toplevel ptop in
+ let l = pexp_location ptop in
let print_info msg loc pex =
print_string msg; print_string "[";
print_loc loc;
print_string "]\t";
- pexp_print_toplevel pex in
+ pexp_print pex in
match ptop with
- | Ptdecl((l, n), pexp) -> print_info "PDecl " l ptop
- | Ptexp (pexp) -> (
- match pexp with
- | Pimm _ -> print_info "Pimm " l ptop
- | Pvar (_,_) -> print_info "Pvar " l ptop
- | Phastype (_,_,_) -> print_info "Phastype " l ptop
- | Pmetavar (_, _) -> print_info "Pmetavar " l ptop
- | Plet (_, _, _) -> print_info "Plet " l ptop
- | Parrow (_, _, _, _, _) -> print_info "Parrow " l ptop
- | Plambda (_,_, _, _) -> print_info "Plambda " l ptop
- | Pcall (_, _) -> print_info "Pcall " l ptop
- | Pinductive (_, _, _) -> print_info "Pinductive " l ptop
- | Pcons (_,_) -> print_info "Pcons " l ptop
- | Pcase (_, _, _) -> print_info "Pcase " l ptop
- | _ -> print_info "Not Impl " l ptop)
+ | Pimm _ -> print_info "Pimm " l ptop
+ | Pvar (_,_) -> print_info "Pvar " l ptop
+ | Phastype (_,_,_) -> print_info "Phastype " l ptop
+ | Pmetavar (_, _) -> print_info "Pmetavar " l ptop
+ | Plet (_, _, _) -> print_info "Plet " l ptop
+ | Parrow (_, _, _, _, _) -> print_info "Parrow " l ptop
+ | Plambda (_,_, _, _) -> print_info "Plambda " l ptop
+ | Pcall (_, _) -> print_info "Pcall " l ptop
+ | Pinductive (_, _, _) -> print_info "Pinductive " l ptop
+ | Pcons (_,_) -> print_info "Pcons " l ptop
+ | Pcase (_, _, _) -> print_info "Pcase " l ptop
+ | _ -> print_info "Not Impl " l ptop
;;
+let debug_pexp_decls decls =
+ List.iter (fun e ->
+ let ((_, name), pxp, tp) = e in
+ print_string name;
+ if tp then print_string " : " else print_string " = ";
+ pexp_print pxp; print_string "\n"
+ )
+ decls
+
+
(* Print a list of pexp *)
let debug_pexp_print_all pexps =
List.iter
@@ -158,11 +167,8 @@ let debug_lexp_print tlxp =
print_loc loc;
print_string "]\t";
lexp_print lex in
- let tloc = lexp_location_toplevel tlxp in
+ let tloc = lexp_location tlxp in
match tlxp with
- | Ltdecl ((_, x), lxp, ltp) -> print_info "Decl " tloc tlxp
- | Ltexp(lxp) ->
- match lxp with
| Var((loc, _), _) -> print_info "Var " tloc tlxp
| Imm(s) -> print_info "Imm " tloc tlxp
| Let(loc, _, _) -> print_info "Let " tloc tlxp
@@ -185,5 +191,34 @@ let debug_lexp_print_all lexps =
lexps
;;
+let debug_lexp_decls decls =
+ List.iter (fun e ->
+ let ((_, name), lxp, ltp) = e in
+ print_string name; print_string " : ";
+ lexp_print ltp;
+ print_string " = ";
+ lexp_print lxp;
+ print_string ";\n"
+ )
+ decls
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
=====================================
tests/eval_test.ml
=====================================
--- /dev/null
+++ b/tests/eval_test.ml
@@ -0,0 +1,152 @@
+open Lparse (* add_def *)
+open Debruijn (* make_lexp_context *)
+open Eval (* make_rte_ctx *)
+open Utest_lib
+
+
+(* default environment *)
+let lctx = make_lexp_context
+let lctx = add_def "_+_" lctx
+let lctx = add_def "_*_" lctx
+let rctx = make_runtime_ctx
+
+
+(* Let
+ * ------------------------ *)
+
+let _ = (add_test "EVAL" "Let" (fun () ->
+ (* Noise. Makes sure the correct variables are selected *)
+ let dcode = "
+ c = 3; a = 1; b = 2; d = 4;" in
+ let rctx, lctx = eval_decl_str dcode lctx rctx in
+
+ let ecode = "
+ let a = 10; x = 50; y = 60; b = 20; in a + b;" in
+
+ let ret = eval_expr_str ecode lctx rctx in
+ (* Expect a single result *)
+ match ret with
+ | [r] -> expect_equal_int 30 (get_int r)
+ | _ -> failure ())
+)
+;;
+
+
+(* Lambda
+ * ------------------------ *)
+let _ = (add_test "EVAL" "Lambda" (fun () ->
+ (* Declare lambda *)
+ let rctx, lctx = eval_decl_str "sqr = lambda x -> x * x;" lctx rctx in
+
+ (* Eval defined lambda *)
+ let ret = eval_expr_str "(sqr 4);" lctx rctx in
+ (* Expect a single result *)
+ match ret with
+ | [r] -> expect_equal_int (get_int r) (4 * 4)
+ | _ -> failure ())
+)
+;;
+
+let _ = (add_test "EVAL" "Nested Lambda" (fun () ->
+ let code = "
+ sqr = lambda x -> x * x;
+ cube = lambda x -> x * (sqr x); " in
+
+ (* Declare lambda *)
+ let rctx, lctx = eval_decl_str code lctx rctx in
+
+ (* Eval defined lambda *)
+ let ret = eval_expr_str "(cube 4);" lctx rctx in
+ (* Expect a single result *)
+ match ret with
+ | [r] -> expect_equal_int (get_int r) (4 * 4 * 4)
+ | _ -> failure ())
+)
+;;
+
+(* Cases + Inductive types
+ * ------------------------ *) (*
+
+let _ = (add_test "EVAL" "Case" (fun () ->
+ (* Inductive type declaration *)
+ let code = "
+ idt = inductive_ (idtd) (ctr0) (ctr1 idt) (ctr2 idt) (ctr3 idt);\n
+
+ ctr0 = inductive-cons idt ctr0;\n
+ ctr1 = inductive-cons idt ctr1;\n
+ ctr2 = inductive-cons idt ctr2;\n
+ ctr3 = inductive-cons idt ctr2;\n
+
+ a = (ctr1 (ctr2 ctr0));\n
+ b = (ctr2 (ctr2 ctr0));\n
+ c = (ctr3 (ctr2 ctr0));\n
+
+ test_fun = lambda x -> case x\n
+ | ctr1 y => 1\n
+ | ctr2 y => 2\n
+ | _ => 3;\n" in
+
+ let rctx, lctx = eval_decl_str code lctx rctx in
+
+ let rcode = "(test_fun a); (test_fun b); (test_fun c)"in
+
+ (* Eval defined lambda *)
+ let ret = eval_expr_str rcode lctx rctx in
+ (* Expect a 3 results *)
+ match ret with
+ | [a; b; c] ->
+ let t1 = expect_equal_int (get_int a) 1 in
+ let t2 = expect_equal_int (get_int b) 2 in
+ let t3 = expect_equal_int (get_int c) 3 in
+ if t1 = 0 && t2 = 0 && t3 = 0 then
+ success ()
+ else
+ failure ()
+ | _ -> failure ())
+)
+;; *)
+
+let _ = (add_test "EVAL" "Recursive Call" (fun () ->
+ (* Inductive type declaration *)
+ let code = "
+ Nat = inductive_ (dNat) (zero) (succ Nat);
+
+ zero = inductive-cons Nat zero;
+ succ = inductive-cons Nat succ;
+
+ one = (succ zero);
+ two = (succ one);
+ three = (succ three);
+
+ tonum = lambda x -> case x
+ | (succ y) => (1 + (tonum y))
+ | _ => 0;" in
+
+ let rctx, lctx = eval_decl_str code lctx rctx in
+
+ let rcode = "(tonum one);"in
+
+ (* Eval defined lambda *)
+ let ret = eval_expr_str rcode lctx rctx in
+ (* Expect a 3 results *)
+ match ret with
+ | [a] -> expect_equal_int (get_int a) 1
+
+ (*| [a; b; c] ->
+ let t1 = expect_equal_int (get_int a) 1 in
+ let t2 = expect_equal_int (get_int b) 2 in
+ let t3 = expect_equal_int (get_int c) 3 in
+ if t1 = 0 && t2 = 0 && t3 = 0 then
+ success ()
+ else
+ failure () *)
+ | _ -> failure ())
+)
+;;
+
+
+
+(* run all tests *)
+run_all ()
+;;
+
=====================================
tests/full_debug.ml
=====================================
--- a/tests/full_debug.ml
+++ b/tests/full_debug.ml
@@ -47,14 +47,10 @@ open Lparse
open Eval
open Lexp
-(* pexp and lexp can be done together, one by one *)
-let pexp_lexp_one node ctx =
- let pxp = pexp_parse node in
- lexp_parse pxp ctx
-;;
-
+let dummy_decl = Imm(String(dloc, "Dummy"));;
+(*
let pexp_lexp_all nodes ctx =
let rec loop nodes ctx acc =
@@ -66,7 +62,7 @@ let pexp_lexp_all nodes ctx =
(loop nodes ctx [])
;;
-let dummy_decl = Imm(String(dloc, "Dummy"));;
+
let add_rte_def name ctx =
(add_rte_variable (Some name) dummy_decl ctx);;
@@ -83,7 +79,9 @@ let eval_until_nth xpr n rctx =
print_eval_result nb c;
loop tl (nb + 1) rctx in
loop xpr 0 rctx
-;;
+;; *)
+
+let discard v = ();;
let main () =
@@ -100,7 +98,6 @@ let main () =
else
begin
let filename = Sys.argv.(1) in
-
(* Read additional Args if any *)
print_string (make_title " ERRORS ");
@@ -113,8 +110,9 @@ let main () =
(* get node sexp *)
let nodes = sexp_parse_all_to_list default_grammar toks (Some ";") in
- (* get pexp *)
- let pexps = pexp_parse_all nodes in
+ (* Parse All Declaration *)
+ let pexps = pexp_decls_all nodes in
+ (* let pexps = pexp_parse_all nodes in *)
(* get lexp *)
let ctx = make_lexp_context in
@@ -122,31 +120,53 @@ let main () =
let ctx = add_def "_+_" ctx in
let ctx = add_def "_*_" ctx in
- let lexps, new_ctx = lexp_parse_all pexps ctx in
-
+ (* let lexps, new_ctx = lexp_parse_all pexps ctx in *)
+ let lexps, nctx = lexp_decls pexps ctx in
+
print_string "\n\n";
(* Printing *)(*
print_title "PreTokens"; debug_pretokens_print_all pretoks;
print_title "Base Sexp"; debug_sexp_print_all toks; *)
- print_string (make_title " Node Sexp "); debug_sexp_print_all nodes;
+ print_string (make_title " Node Sexp "); debug_sexp_print_all nodes;
print_string "\n";
- print_string (make_title " Pexp "); debug_pexp_print_all pexps;
+ print_string (make_title " Pexp "); debug_pexp_decls pexps;
+ (*debug_pexp_print_all pexps;*)
print_string "\n";
- print_string (make_title " Lexp "); debug_lexp_print_all lexps;
+ print_string (make_title " Lexp "); debug_lexp_decls lexps;
+ (* debug_lexp_print_all lexps; *)
+ print_string "\n";
+
+ print_string "\n";
+ lexp_context_print nctx;
print_string "\n";
(* Eval Each Expression *)
print_string (make_title " Eval Print ");
- (* Eval One *)
+
+ (* Eval declaration *)
let rctx = make_runtime_ctx in
- let rctx = eval_until_nth lexps 500 rctx in
- print_string "\n\n";
- print_rte_ctx rctx;
+ let rctx = eval_decls lexps rctx in
+
+ let _ =
+ try
+ (* Check if main is present *)
+ let main = (senv_lookup "main" nctx) in
+ (* Push main args here if any *)
+
+ (* get main body *)
+ let body = (get_rte_variable main rctx) in
+ (* eval main *)
+ let r = (eval body rctx) in
+ print_eval_result 0 r
+
+ with
+ Not_found -> () in
+
+ (* Print info *)
+ print_string "\n\n";
+ print_rte_ctx rctx;
- print_string "\n";
- lexp_context_print new_ctx;
- print_string "\n";
print_call_trace ();
end
@@ -154,4 +174,3 @@ let main () =
main ()
;;
-
=====================================
tests/let_test.ml deleted
=====================================
--- a/tests/let_test.ml
+++ /dev/null
@@ -1,30 +0,0 @@
-
-open Eval
-
-
-(* How to make macro in ocaml? *)
-
-(*
-let EXPECT_EQUAL a b =
- if a = b then(print_string "[ OK]\n"; SUCCESS)
- else( print_string "[ FAIL]\n"; FAILURE)
-;;
-
-let EXPECT_THROW a error =
- try ((a); print_string "[ FAIL]\n"; FAILURE)
- with (print_string "[ OK]\n"; SUCCESS)
-;; *)
-
-
-let main () =
-
- let ret = easy_eval_string "let a = 3; b = 5; in a + b;" in
- match ret with
- | [xpr] -> let v = get_int xpr in
- if v = 8 then (exit 0) else (exit (-1))
- | _ -> exit (-1)
-
-;;
-
-main ()
-;;
\ No newline at end of file
=====================================
tests/lexp_test.ml
=====================================
--- /dev/null
+++ b/tests/lexp_test.ml
@@ -0,0 +1,47 @@
+open Lparse
+open Debruijn (* make_lexp_context *)
+open Lexp
+open Utest_lib
+
+(* default environment *)
+let lctx = make_lexp_context
+let lctx = add_def "_+_" lctx
+let lctx = add_def "_*_" lctx
+
+(* Check if annotation are parsed and kept *)
+(* Let and top level declarations are using the same code *)
+(* We only have to check if let's type parsing is correct *)
+let _ = (add_test "LEXP" "Type Parsing" (fun () ->
+
+ (* This is garbage. I just want Nat to be defined *)
+ let dcode = "
+ Nat = inductive_ (dNat) (zero) (succ Nat);\n" in
+
+ let _, lctx = lexp_decl_str dcode lctx in
+
+ let ecode = "
+ let a : Nat; a = 1; b : Nat; b = 3;
+ in
+ a + b;" in
+
+ let ret, _ = lexp_expr_str ecode lctx in
+ match ret with
+ | [expr] ->(
+ match expr with
+ | Let(_, arg, _) -> match arg with
+ | [] -> failure ()
+ | (_, xp, tp)::_ ->(
+ (* tp must match Nat *)
+ match tp with
+ | Var((_, name), _) -> expect_equal_str name "Nat"
+ | _ -> failure ()
+ )
+ | _ -> failure ())
+ | [] -> failure ())
+)
+;;
+
+
+
+run_all ()
+;;
\ No newline at end of file
=====================================
tests/pexp_test.ml
=====================================
--- /dev/null
+++ b/tests/pexp_test.ml
@@ -0,0 +1,29 @@
+open Pexp
+open Utest_lib
+
+
+let _ = (add_test "PEXP" "Type Parsing" (fun () ->
+
+ let dcode = "
+ let a : Nat; a = 1; b : Nat; b = 3; in a + b;" in
+
+ let ret = pexp_expr_str dcode in
+ match ret with
+ | [expr] ->(
+ match expr with
+ | Plet(_, arg, _) -> match arg with
+ | [] -> failure ()
+ | (_, tp, bl)::_ ->(
+ if bl = true then
+ success ()
+ else
+ failure ())
+ | _ -> failure ())
+ | [] -> failure ())
+)
+;;
+
+
+
+run_all ()
+;;
\ No newline at end of file
=====================================
tests/utest_lib.ml
=====================================
--- /dev/null
+++ b/tests/utest_lib.ml
@@ -0,0 +1,123 @@
+(*
+ * Typer Compiler
+ *
+ * ---------------------------------------------------------------------------
+ *
+ * Copyright (C) 2011-2016 Free Software Foundation, Inc.
+ *
+ * Author: Pierre Delaunay <pierre.delaunay(a)hec.ca>
+ * Keywords: languages, lisp, dependent types.
+ *
+ * This file is part of Typer.
+ *
+ * Typer is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ * Typer is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * ---------------------------------------------------------------------------
+ *
+ * Description:
+ * utest library utility. Tests register themselves
+ *
+ * --------------------------------------------------------------------------- *)
+
+
+
+module StringMap =
+ Map.Make (struct type t = string let compare = String.compare end)
+;;
+
+
+type test_fun = (unit -> int)
+type tests = (test_fun) StringMap.t
+type sections = (tests) StringMap.t
+
+let success () = 0;;
+let failure () = (-1);;
+
+(*
+ * SECTION NAME - TEST NAME - FUNCTION (() -> int)
+ * "Let" - "Base Case" - (fun () -> success )
+ * "Let" - "Recursive"
+ * "Lambda" - "Base Case"
+ * "Lambda" - "Nested"
+ *)
+let _global_sections = ref StringMap.empty
+
+
+(* USAGE *)
+(*
+ * (add_test "LET" "Base Case" (fun () ->
+ * let r = eval_string "let a = 2; b = 3; in a + b;" in
+ * let v = (get_int r) in
+ * if v = 5 then success () else failure ()))
+ *
+ * sname: Section Name
+ * tname: Test Name
+ * dcode: Typer's Declarations
+ * ecode: expression to eval
+ * tfun : test function (unit -> int)
+ *)
+let add_test sname tname tfun =
+
+ (* Does Section Exists ? *)
+ let tmap =
+ try
+ StringMap.find sname (!_global_sections)
+ with
+ Not_found -> StringMap.empty in
+
+ (* add test *)
+ let ntmap = StringMap.add tname tfun tmap in
+ _global_sections := StringMap.add sname ntmap (!_global_sections);
+;;
+
+(* Run all *)
+let run_all () =
+ (* iter over all sections *)
+ StringMap.iter (fun sk sv ->
+ print_string ("[RUN ] " ^ sk ^ " \n");
+ (* iter over all tests in the current sections *)
+ StringMap.iter (fun tk tv ->
+ (* RUN TEST*)
+ let r = tv () in
+ if r = 0 then
+ (print_string ("[ OK] " ^ sk ^ " - " ^ tk ^ "\n"))
+ else
+ (print_string ("[ FAIL] " ^ sk ^ " - " ^ tk ^ "\n"))
+ )
+ sv;
+ flush stdout;
+ )
+ (!_global_sections)
+
+
+let expect_equal_int value expect =
+ if value = expect then
+ success ()
+ else(
+ print_string ("[ ] EXPECTED: " ^ (string_of_int expect)^ "\n");
+ print_string ("[ ] GOT: " ^ (string_of_int value) ^ "\n");
+ failure ())
+;;
+
+
+let expect_equal_str value expect =
+ if value = expect then
+ success ()
+ else(
+ print_string ("[ ] EXPECTED: " ^ expect ^ "\n");
+ print_string ("[ ] GOT: " ^ value ^ "\n");
+ failure ())
+;;
+
+
=====================================
tests/utest_main.ml
=====================================
--- a/tests/utest_main.ml
+++ b/tests/utest_main.ml
@@ -59,6 +59,7 @@ let main () =
let root_folder = (if arg_n > 2 then Sys.argv.(2) else "./") in (* /_build/tests/ *)
for i = 0 to files_n - 1 do
+ flush stdout;
(* Check if file is a test => if it is run it *)
(if (Filename.check_suffix files.(i) "_test.byte") ||
(Filename.check_suffix files.(i) "_test.native") then
@@ -66,17 +67,8 @@ let main () =
tests_n := !tests_n + 1;
- print_endline ("[RUN ] TEST: " ^ (cut_name files.(i)));
-
exit_code := Sys.command (folder ^ files.(i) ^ " " ^ root_folder);
- if !exit_code <> 0 then begin
- print_string "[ FAIL]\n" ;
- print_endline " =========== TEST FAILURE ===========";
- failed_test := !failed_test + 1;
- end
- else
- print_string "[ OK]\n" ;
end)
done;
View it on GitLab: https://gitlab.com/monnier/typer/compare/772d85026102d81b874b60852ef71b5f29…
2
1
10 Mar '16
Setepenre pushed to branch master at Stefan / Typer
Commits:
6b432d51 by Pierre Delaunay at 2016-03-09T20:37:20-05:00
correct declaration handling
- - - - -
772d8502 by Pierre Delaunay at 2016-03-09T22:31:08-05:00
fix nested lambda offset
- - - - -
16 changed files:
- doc/Compiler Structure.md
- samples/case.typer
- samples/functions.typer
- samples/let.typer
- samples/lexp_test.typer
- src/eval.ml
- src/fmt.ml
- src/lexp.ml
- src/lparse.ml
- src/pexp.ml
- tests/REPL.ml
- − tests/debruijn_test.ml
- tests/debug.ml
- tests/full_debug.ml
- + tests/let_test.ml
- tests/utest_main.ml
Changes:
=====================================
doc/Compiler Structure.md
=====================================
--- a/doc/Compiler Structure.md
+++ b/doc/Compiler Structure.md
@@ -1,5 +1,3 @@
-Stream.of_string
-
Typer Compiler Structure
========================
@@ -8,54 +6,79 @@ Read tests/full_debug.ml for ocaml usage
* in_channel -> PreLexer: PreToken
- Skips Blocks and identifies Strings
-
- Blocks : {this is a block}
- String : "this is a string"
- PreToken: a pretoken is everything else
+Skips Blocks and identifies Strings
- Function:
- prelex_file file
-
- TODO:
- prelex_str "my code"
-
+ Blocks : {this is a block}
+ String : "this is a string"
+ PreToken: a pretoken is everything else
+
+Code: "a => 3;"
+ Pretoken: ['a', '=>', '3;']
+
+Functions:
+ prelex_file file
+ prelex_string str
+
* PreToken -> Lexer: Sexp
- Process PreToken. Cut them in smaller pieces according to [stt : token_env]
- For example:
+Process PreToken. Cut them in smaller pieces according to [stt : token_env]
+For example:
+
+ Code: "a => 3;"
+ Lexer => ['a', '=>', '3', ';']
- Code: "a => 3;"
-
- Pretoken: ['a', '=>', '3;']
-
- Lexer ['a', '=>', '3;'] => ['a', '=>', '3', ';']
-
- Here ';' is in stt which makes the '3;' pretoken to explode in two.
+Here ';' is in stt which makes the '3;' pretoken to explode in two.
+
+Functions:
+ lex stt pretoken
+ lex_string str
- Function:
- lex stt pretoken
+* Sexp -> sexp_parse: Node Sexp
-* Sexp -> sexp_parse: Sexp
+Group Sexp into Nodes according to the specified grammar.
+Create the program tree.
+
+ Code: "a => 3;"
+ sexp_parse => Node('_=>_', ['a', '3'])
- Group Sexp into Nodes according to the specified grammar.
- Create the program tree.
+Functions:
+ sexp_parse sexp
+ node_parse_string str
+
+* Sexp -> Pexp: ~ Check grammar
+Identify nodes and transform them into language primitives
+
Code: "a => 3;"
-
- Pretoken: ['a', '=>', '3;']
+ Pexp: PArrow(kind='=>', a, 3)
+
+Functions:
+ pexp_parse sexp % For evaluable expression
+ pexp_p_decls % For top level declaration
+ pexp_p_toplevel % Parses using the appropriate parsing function
- Lexer ['a', '=>', '3;'] => ['a', '=>', '3', ';'] (Sexp)
+* Pexp -> Lexp: ~ Check scopes/ declaration
+
+Replace variable name by their (reverse) index in the environment.
+Lexps are very close to pexps
+
+ Code: "a => 3;"
+ Lexp: Arrow(kind='=>', a, 3)
+
+Functions:
+ lexp_p_toplevel
+ lexp_parse
+ lexp_p_decls
+ lexp_parse_string
- sexp_parse ['a', '=>', '3', ';']
- => Node('_=>_', ['a', '3'])
-
- Function:
- sexp_parse sexp
-
-* Sexp -> Lexp
+* Lexp -> Value: ~ Evaluation
+
+Functions:
+ eval % Evals expression do not modify runtime
+ eval_decls % Evals declaration modify runtime env
+ eval_toplevel % uses the appropriate eval function
+ eval_string % uses eval_toplevel
- Replace variable name by their (reverse) index in the environment.
=====================================
samples/case.typer
=====================================
--- a/samples/case.typer
+++ b/samples/case.typer
@@ -2,6 +2,13 @@
% Inductive type
% -------------------------------------------
+
+%
+% Constructor with not args are not processed
+% correctly in case . I need type info to differentiate them
+% from variables
+%
+
% definition
inductive_ (dummy_Nat) (zero) (succ Nat);
@@ -24,14 +31,13 @@ x = (succ (succ zero));
% Simple
case x
- | zero => 0
| succ y => y
| _ => (2 + 4);
% recursive
tonum = lambda x -> case x
- | zero => 0
- | (succ y) => (1 + (tonum y));
+ | (succ y) => (1 + (tonum y))
+ | _ => 0;
(tonum x);
=====================================
samples/functions.typer
=====================================
--- a/samples/functions.typer
+++ b/samples/functions.typer
@@ -3,12 +3,12 @@
% -------------------------------------------
% define sqrt
-sqrt = lambda (x : Nat) -> x * x;
+sqr = lambda (x : Nat) -> x * x;
-(sqrt 2);
+(sqr 2);
% define cube
-cube = lambda (x : Nat) -> x * (sqrt x);
+cube = lambda (x : Nat) -> x * (sqr x);
(cube 3);
=====================================
samples/let.typer
=====================================
--- a/samples/let.typer
+++ b/samples/let.typer
@@ -20,4 +20,16 @@ let a = 3; g = 1; e = 1; f = 3; in
% Not Implemented
% ----------------------
+
+% Type definition
+Nat = inductive_ (dummy_Nat) (zero) (succ Nat);
+
+zero = inductive-cons Nat zero;
+succ = inductive-cons Nat succ;
+
+v = (succ (succ zero));
+
% Recursive Let
+let odd = lambda n -> case n | (zero) => false | (succ y) => (even y);
+ even = lambda n -> case n | (zero) => true | (succ y) => (odd y); in
+ (odd v)
\ No newline at end of file
=====================================
samples/lexp_test.typer
=====================================
--- a/samples/lexp_test.typer
+++ b/samples/lexp_test.typer
@@ -1,15 +1,18 @@
-% Constructor
-% -------------------------------------------
+% x : Nat;
+x = 4;
+x + x + x; % 12
+x * x * x; % 64
+sqr = lambda x -> x * x;
+% cube = lambda x -> x * x * x;
-% -------------------------------------------
-% Cases
-% -------------------------------------------
+(sqr x); % 16
+%(cube x);
+
+cube = lambda x -> x * (sqr x);
+(cube x); % 64
-case x
- | zero => y
- | succ x => succ (plus x y);
=====================================
src/eval.ml
=====================================
--- a/src/eval.ml
+++ b/src/eval.ml
@@ -36,39 +36,43 @@ open Lparse
open Myers
open Sexp
open Fmt
+open Debruijn
open Grammar
+(* Value type *)
+type value_type =
+ | Void
+ | Val of lexp
+
let _eval_error loc msg =
- msg_error "_eval" loc msg;
+ msg_error "eval" loc msg;
raise (internal_error msg)
;;
let dloc = dummy_location
-let _eval_warning = msg_warning "_eval"
+let _eval_warning = msg_warning "eval"
+
+type call_trace_type = (int * lexp) list
+let global_trace = ref []
+
+let add_call cll i = global_trace := (i, cll)::!global_trace
+let reinit_call_trace () = global_trace := []
let print_myers_list l print_fun =
- let n = (length l) in
+ let n = (length l) - 1 in
- let title = " EVAL ENVIRONMENT " in
- let title_n = String.length title in
- let sep_n = (80 - title_n - 4) / 2 in
- let sep_t = 80 - 4 in
- let psep = (make_line '=' sep_n) in
- let fsep = (make_line '=' sep_t) in
- let sep = " " ^ fsep ^ "\n" in
+ print_string (make_title " ENVIRONMENT ");
+ make_rheader [(None, "INDEX"); (None, "VARIABLE NAME"); (None, "VALUE")];
+ print_string (make_sep '-');
- print_string (" " ^ psep ^ title ^ psep ^ "\n");
- print_string " | INDEX | VARIABLE NAME | VALUE \n";
- print_string (" " ^ (make_line '-' sep_t) ^ "\n");
-
- for i = 0 to n - 1 do
+ for i = 0 to n do
print_string " | ";
- ralign_print_int i 5;
+ ralign_print_int (n - i) 5;
print_string " | ";
- print_fun (nth i l);
+ print_fun (nth (n - i) l);
done;
- print_string sep;
+ print_string (make_sep '=');
;;
let get_function_name fname =
@@ -79,8 +83,8 @@ let get_function_name fname =
let get_int lxp =
match lxp with
- | Imm(Integer(_, l)) -> l
- | _ -> lexp_print lxp; -1
+ | Imm(Integer(_, l)) -> l
+ | _ -> lexp_print (Ltexp(lxp)); -40
;;
(* Runtime Environ *)
@@ -96,12 +100,34 @@ let print_rte_ctx l = print_myers_list l
match n with
| Some m -> lalign_print_string m 12; print_string " | "
| None -> print_string (make_line ' ' 12); print_string " | " in
- lexp_print g; print_string "\n")
+ lexp_print (Ltexp(g)); print_string "\n")
;;
-(* _evaluation reduce an expression x to an Lexp.Imm *)
-let rec _eval lxp ctx: (lexp * runtime_env) =
-
+
+let nfirst_rte_var n ctx =
+ let rec loop i acc =
+ if i < n then
+ loop (i + 1) ((get_rte_variable i ctx)::acc)
+ else
+ List.rev acc in
+ loop 0 []
+;;
+
+(* *)
+let rec eval_toplevel ltop ctx: (value_type * runtime_env) =
+ global_trace := []; (* Clean up trace info *)
+ (* I have to use a sexp because declaration are not "carried" *)
+ match ltop with
+ (* Eval expression and return results *)
+ | Ltexp(x) ->
+ let a, b = _eval x ctx 0 in
+ Val(a), ctx
+ (* Add declaration to environment. return void *)
+ | Ltdecl(a, b, c) -> Void, (eval_decl (a, b, c) ctx)
+
+(* _eval is an internal definition you should use eval or eval_toplevel *)
+and _eval lxp ctx i: (lexp * runtime_env) =
+ add_call lxp i;
match lxp with
(* This is already a leaf *)
| Imm(v) -> lxp, ctx
@@ -113,59 +139,54 @@ let rec _eval lxp ctx: (lexp * runtime_env) =
with
Not_found ->
print_string ("Variable: " ^ name ^ " was not found | ");
- print_int idx; print_string "\n";
+ print_int idx; print_string "\n"; flush stdout;
raise Not_found end
(* this works for non recursive let *)
| Let(_, decls, inst) -> begin
(* First we _evaluate all declaration then we eval the instruction *)
- let nctx = build_ctx decls ctx in
+ let nctx = build_ctx decls ctx i in
- (*
- print_rte_ctx ctx;
- print_rte_ctx nctx; *)
-
- let value, nctx = _eval inst nctx in
+ let value, nctx = _eval inst nctx (i + 1) in
(* return old context as we exit let's scope*)
value, ctx end
(* Function call *)
| Call (lname, args) -> (
(* Try to extract name *)
+ let n = List.length args in
match lname with
- (* Function declaration *)
- | Var((loc, name), _) when name = "_=_" ->
- (* Save declaration in environment *)
- let (vr, body) = match args with
- | [(_, a); (_, b)] -> a, b
- | _ -> _eval_error loc "Wrong number of Args" in
-
- let vname = get_function_name vr in
- let nctx = add_rte_variable (Some vname) body ctx in
- body, nctx
-
(* Hardcoded functions *)
+
+ (* + is read as a nested binary operator *)
| Var((_, name), _) when name = "_+_" ->
- let nctx = build_arg_list args ctx in
+ let nctx = build_arg_list args ctx i in
+
let l = get_int (get_rte_variable 0 nctx) in
- let r = get_int (get_rte_variable 1 nctx) in
+ let r = get_int (get_rte_variable 1 nctx) in
Imm(Integer(dloc, l + r)), ctx
+ (* _*_ is reas as a single function with x args *)
| Var((_, name), _) when name = "_*_" ->
- let nctx = build_arg_list args ctx in
- let l = get_int (get_rte_variable 0 nctx) in
- let r = get_int (get_rte_variable 1 nctx) in
- Imm(Integer(dloc, l * r)), ctx
+ let nctx = build_arg_list args ctx i in
+
+ let vint = (nfirst_rte_var n nctx) in
+ let varg = List.map (fun g -> get_int g) vint in
+ let v = List.fold_left (fun a g -> a * g) 1 varg in
+
+ Imm(Integer(dloc, v)), ctx
(* This is a named function call *)
(* TODO: handle partial application *)
- | Var((_, _), idx) when idx >= 0 ->
+ | Var((_, name), idx) ->
+
(* get function body *)
let body = get_rte_variable idx ctx in
(* Add args in the scope *)
- let nctx = build_arg_list args ctx in
- let e, nctx = (_eval body nctx) in
+ let nctx = build_arg_list args ctx i in
+ let e, nctx = (_eval body nctx (i + 1)) in
+
(* we exit function and send back old ctx *)
e, ctx
@@ -175,6 +196,7 @@ let rec _eval lxp ctx: (lexp * runtime_env) =
| Lambda(_, vr, _, body) -> begin
let (loc, name) = vr in
+ (* Get first arg *)
let value = (get_rte_variable 0 ctx) in
let nctx = add_rte_variable (Some name) value ctx in
@@ -191,7 +213,7 @@ let rec _eval lxp ctx: (lexp * runtime_env) =
let body, nctx = build_body body 1 nctx in
- let e, nctx = _eval body nctx in
+ let e, nctx = _eval body nctx (i + 1) in
e, ctx end
(* Inductive is a type declaration. We have nothing to eval *)
@@ -204,7 +226,7 @@ let rec _eval lxp ctx: (lexp * runtime_env) =
| Case (loc, target, _, pat, dflt) -> begin
(* Eval target *)
- let v, nctx = _eval target ctx in
+ let v, nctx = _eval target ctx (i + 1) in
(* V must be a constructor Call *)
let ctor_name, args = match v with
@@ -222,14 +244,14 @@ let rec _eval lxp ctx: (lexp * runtime_env) =
Not_found ->
_eval_error loc "Constructor does not exist" end *)
- | _ -> lexp_print target;
+ | _ -> lexp_print (Ltexp(target));
_eval_error loc "Can't match expression" in
(* Check if a default is present *)
let run_default df =
match df with
| None -> Imm(String(loc, "Match Failure")), ctx
- | Some lxp -> _eval lxp ctx in
+ | Some lxp -> _eval lxp ctx (i + 1) in
let ctor_n = List.length args in
@@ -259,60 +281,132 @@ let rec _eval lxp ctx: (lexp * runtime_env) =
nctx pat_args args in
- let r, nctx = _eval exp nctx in
+ let r, nctx = _eval exp nctx (i + 1) in
(* return old context as we exist the case *)
r, ctx end
| _ -> Imm(String(dloc, "eval Not Implemented")), ctx
-and build_arg_list args ctx =
+and build_arg_list args ctx i =
(* _eval every args *)
- let arg_val = List.map (fun (k, e) -> let (v, c) = _eval e ctx in v) args in
+ let arg_val = List.map (
+ fun (k, e) ->
+ let (v, c) = _eval e ctx (i + 1) in v)
+ args in
+
(* Add args inside context *)
List.fold_left (fun c v -> add_rte_variable None v c) ctx arg_val
-and build_ctx decls ctx =
+and build_ctx decls ctx i =
match decls with
| [] -> ctx
| hd::tl ->
let (v, exp, tp) = hd in
- let (value, nctx) = _eval exp ctx in
+ let (value, nctx) = _eval exp ctx (i + 1) in
let nctx = add_rte_variable None value nctx in
- build_ctx tl nctx
-;;
-
-let eval lxp ctx =
- try
- _eval lxp ctx
- with
- e -> print_rte_ctx ctx;
- Imm(String(dloc, "Evaluation Failed")), ctx
-;;
-
-let print_eval_result i lxp =
+ build_ctx tl nctx (i + 1)
+
+and eval_decl ((l, n), lxp, ltp) ctx =
+ add_rte_variable (Some n) lxp ctx
+
+and print_eval_result i tlxp =
+ match tlxp with
+ | Void -> ()
+ | Val(lxp) ->
print_string " Out[";
ralign_print_int i 2;
print_string "] >> ";
match lxp with
| Imm(v) -> sexp_print v; print_string "\n"
- | e -> lexp_print e; print_string "\n"
+ | e -> lexp_print (Ltexp(e)); print_string "\n"
+;;
+
+
+let print_first n l f =
+ let rec loop i l =
+ match l with
+ | [] -> ()
+ | hd::tl ->
+ if i < n then ((f i hd); loop (i + 1) tl;)
+ else () in
+ loop 0 l
+;;
+
+let _print_ct_tree i =
+ print_string " ";
+ let rec loop j =
+ if j = i then () else
+ match j with
+ | _ when (j mod 2) = 0 -> print_char '|'; loop (j + 1)
+ | _ -> print_char ':'; loop (j + 1) in
+ loop 0
+;;
+
+let print_call_trace () =
+ print_string (make_title " CALL TRACE ");
+
+ let n = List.length !global_trace in
+ print_string " size = "; print_int n; print_string "\n";
+ print_string (make_sep '-');
+
+ let racc = List.rev !global_trace in
+ print_first 20 racc (fun j (i, g) ->
+ _print_ct_tree i; print_string "+- ";
+ print_string (lexp_to_string g); print_string ": ";
+ lexp_print (Ltexp(g)); print_string "\n");
+
+ print_string (make_sep '=');
;;
+let eval lxp ctx =
+ try
+ let r, c = eval_toplevel lxp ctx in
+ (r, c)
+ with e -> (
+ print_rte_ctx ctx;
+ print_call_trace ();
+ raise e)
+;;
+
+
+
let evalprint lxp ctx =
- let v, ctx = (eval lxp ctx) in
+ let v, ctx = (eval_toplevel lxp ctx) in
print_eval_result 0 v;
ctx
;;
-(*
+(* Eval a list of lexp *)
+let eval_all lxps rctx =
+ let rec _eval_all lxps acc rctx =
+ match lxps with
+ | [] -> (List.rev acc), rctx
+ | hd::tl ->
+ let lxp, rctx = eval hd rctx in
+ _eval_all tl (lxp::acc) rctx in
+ (_eval_all lxps [] rctx)
+;;
+
+(* Eval a string given a context *)
let eval_string (str: string) tenv grm limit lxp_ctx rctx =
- let pretoks = prelex_string str in
- let toks = lex tenv pretoks in
- let sxps = sexp_parse_all_to_list grm toks limit in
- let pxps = pexp_parse_all sxps in
- let lxp, lxp_ctx = lexp_parse_all pxps lxp_ctx in
- (eval lxp rctx), lxp_ctx
+ let lxps, lxp_ctx = lexp_parse_string str tenv grm limit lxp_ctx in
+ (eval_all lxps rctx), lxp_ctx
;;
-*)
+(* EVAL a string. Contexts are discarded *)
+let easy_eval_string str =
+ let tenv = default_stt in
+ let grm = default_grammar in
+ let limit = (Some ";") in
+ let eval_string str clxp rctx = eval_string str tenv grm limit clxp rctx in
+ let clxp = make_lexp_context in
+ (* Those are hardcoded operation *)
+ let clxp = add_def "_+_" clxp in
+ let clxp = add_def "_*_" clxp in
+ let clxp = add_def "_=_" clxp in
+
+ let rctx = make_runtime_ctx in
+ let (ret, rctx), clxp = (eval_string str clxp rctx) in
+ ret
+;;
=====================================
src/fmt.ml
=====================================
--- a/src/fmt.ml
+++ b/src/fmt.ml
@@ -76,3 +76,32 @@ let lalign_print_string =
let lalign_print_int =
lalign_generic str_size_int print_string print_int cut_int;;
+(* Table Printing helper *)
+let make_title title =
+ let title_n = String.length title in
+ let p = title_n mod 2 in
+ let sep_n = (80 - title_n - 4) / 2 in
+ let lsep = (make_line '=' sep_n) in
+ let rsep = (make_line '=' (sep_n + p)) in
+ (" " ^ lsep ^ title ^ rsep ^ "\n")
+;;
+
+let make_rheader (head: (((char* int) option * string) list)) =
+ print_string " | ";
+
+ List.iter (fun (o, name) ->
+ let _ = match o with
+ | Some ('r', size) -> ralign_print_string name size
+ | Some ('r', size) -> lalign_print_string name size
+ | _ -> print_string name in
+ print_string " | ")
+ head;
+
+ print_string "\n"
+;;
+
+let make_sep c = " " ^ (make_line c 76) ^ "\n";;
+
+
+
+
=====================================
src/lexp.ml
=====================================
--- a/src/lexp.ml
+++ b/src/lexp.ml
@@ -276,7 +276,21 @@ let rec lexp_location e =
| Case (l,_,_,_,_) -> l
(* | Susp (_, e) -> lexp_location e
* | Metavar ((l,_),_,_) -> l *)
-
+
+
+let lexp_to_string e =
+ match e with
+ | Imm _ -> "Imm"
+ | Var _ -> "Var"
+ | Let _ -> "Let"
+ | Arrow _ -> "Arrow"
+ | Lambda _ -> "Lambda"
+ | Call _ -> "Call"
+ | Inductive _ -> "Inductive"
+ | Cons _ -> "Cons"
+ | Case _ -> "Case"
+;;
+
let builtin_reduce b args arg =
match b,args,arg with
| IAdd, [(_,Imm (Integer (_, i1)))], (Imm (Integer (_, i2)))
=====================================
src/lparse.ml
=====================================
--- a/src/lparse.ml
+++ b/src/lparse.ml
@@ -61,20 +61,24 @@ let lexp_fatal loc msg =
raise (internal_error msg)
;;
-(* Print back in CET (Close Enough Typer) easier to read *)
+
(* pretty ? * indent level * print_type? *)
type print_context = (bool * int * bool)
(* Vdef is exactly similar to Pvar but need to modify our ctx *)
-let pvar_to_vdef p =
- p
+let pvar_to_vdef p = p;;
+
+type ltop =
+ | Ltexp of lexp
+ | Ltdecl of vdef * lexp * ltype
;;
-(*
-let _ab = senv_add_var;;
-let senv_add_var =
- _ab name loc ctx
-;;*)
+
+let lexp_location_toplevel ltp =
+ match ltp with
+ | Ltexp(x) -> lexp_location x
+ | Ltdecl((l, _), _, _) -> l
+;;
(* PEXP is not giving SEXP types this is why types are always unknown *)
@@ -97,7 +101,22 @@ let senv_add_var =
*
*)
-let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
+(* Process a top-level expression *)
+let rec lexp_p_toplevel (p: ptop) (ctx: lexp_context) =
+
+ (* Identify if the expression is a declaration *)
+ match p with
+ (* Declaration *)
+ | Ptdecl (x, p) ->
+ let (a, b, c), ctx = lexp_p_decls (x, p, None) ctx in
+ Ltdecl(a, b, c), ctx
+
+ (* Everything else*)
+ | Ptexp (x) -> let x, ctx = lexp_parse x ctx in
+ Ltexp(x), ctx
+
+(**)
+and lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
(* So I don't have to extract it *)
let tloc = pexp_location p in
match p with
@@ -112,10 +131,9 @@ let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
(make_var name idx loc), ctx;
with Not_found ->
- (* Add Variable *)
- let ctx = senv_add_var name loc ctx in
- let ctx = env_add_var_info (0, (loc, name), dlxp, dlxp) ctx in
- (make_var name 0 loc), ctx; end
+ (lexp_error loc ("The Variable: " ^ name ^ " was not declared");
+ (* Error recovery. The -1 index will raise an error later on *)
+ (make_var name (-1) loc), ctx) end
(* Let, Variable declaration + local scope *)
| Plet(loc, decls, body) ->
@@ -159,8 +177,7 @@ let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
let lbody, ctx = lexp_parse body nctx in
Lambda(kind, var, UnknownType(tloc), lbody), ctx
- | Pcall (fname, _args) ->
- lexp_call fname _args ctx
+ | Pcall (fname, _args) -> lexp_call fname _args ctx
(* Pinductive *)
| Pinductive (label, [], ctors) ->
@@ -184,7 +201,7 @@ let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
(* Pcase *)
| Pcase (loc, target, patterns) ->
-
+ (* I need type info HERE *)
let lxp, nctx = lexp_parse target ctx in
let ltp = UnknownType(loc) in
@@ -211,11 +228,11 @@ let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
| _
-> UnknownType(tloc), ctx
-
+
(* Identify Call Type and return processed call *)
-and lexp_call fname _args ctx =
+and lexp_call (fname: pexp) (_args: sexp list) ctx =
(* Process Arguments *)
- let pargs = pexp_parse_all _args in
+ let pargs = List.map pexp_parse _args in
(* Call to named function which must have been defined earlier *
* i.e they must be in the context *)
@@ -225,34 +242,8 @@ and lexp_call fname _args ctx =
| Pvar(loc, nm) -> nm, loc
| Pcons (_, (loc, nm)) -> nm, loc
| _ -> raise Not_found in
-
- (* _=_ is a special function *) (**)
- let n = List.length pargs in
- if name = "_=_" && n = 2 then(
- let (var, inst) = match pargs with
- | [a; b] -> a, b
- (* This was added to remove a warning but will never be true *)
- | _ -> lexp_fatal loc "Wrong Number of Args" in
-
- let vname = match var with Pvar(loc, name) -> name
- | e -> pexp_print var; "str" in
-
- (* we should add the defined var to ctx *)
- let nctx = senv_add_var vname loc ctx in
-
- let idx = senv_lookup vname nctx in
- let lxp, ltyp = lexp_p_infer inst nctx in
-
- (* Add Var info*)
- let nctx = env_add_var_info (0, (loc, vname), lxp, ltyp) nctx in
-
- (* _=_ is the only function with -2 index *)
- let vf = (make_var "_=_" (-2) loc) in
- let vr = (make_var vname idx loc) in
-
- Call(vf, [(Aexplicit, vr); (Aexplicit, lxp)]), nctx)
- else(**)
- let largs, fctx = lexp_parse_all pargs ctx in
+
+ let largs, fctx = lexp_p_all pargs ctx in
let new_args = List.map (fun g -> (Aexplicit, g)) largs in
try
@@ -271,7 +262,7 @@ and lexp_call fname _args ctx =
(* Call to a nameless function *)
with Not_found ->
- let largs, fctx = lexp_parse_all pargs ctx in
+ let largs, fctx = lexp_p_all pargs ctx in
let new_args = List.map (fun g -> (Aexplicit, g)) largs in
(* I think this should not modify context.
* if so, funny things might happen when evaluating *)
@@ -281,15 +272,15 @@ and lexp_call fname _args ctx =
(* Read a pattern and create the equivalent representation *)
and lexp_read_pattern pattern exp target ctx:
((string * location * (arg_kind * vdef) option list) * lexp_context) =
-
- (* lookup target val if its a var and extract its args *)
- (* TODO *)
-
+
match pattern with
| Ppatany (loc) -> (* Catch all expression nothing to do *)
("_", loc, []), ctx
- | Ppatvar (loc, name) -> (* Create a variable containing target *)
+ | Ppatvar (loc, name) ->
+ (* FIXME What if it is a constructor with no arg ? *)
+
+ (* Create a variable containing target *)
let nctx = senv_add_var name loc ctx in
let nctx = env_add_var_info (0, (loc, name), target, dltype) nctx in
(name, loc, []), nctx
@@ -353,7 +344,43 @@ and lexp_parse_constructors ctors ctx =
end in
loop ctors SMap.empty ctx
+
+(* Merge Type info and variable declaration together *)
+(* Type info must be first then declaration else type will be inferred *)
+and lexp_merge_info (decls: (pvar * pexp * bool) list) =
+ match decls with
+ | [] -> lexp_fatal dloc "Empty Declaration List"
+ | hd::tl -> (match hd with
+ (* Declaration without type info *)
+ | ((l, n1), expr, true) -> (
+ match tl with
+ | [] -> lexp_fatal l "Unused Type info declaration";
+ | ((_, _), expr2, true)::_ -> lexp_merge_info tl
+ | ((_, n2), expr2, _)::_ when n2 != n1 ->
+ (lexp_warning l "Unused Type info declaration";
+ lexp_merge_info tl)
+ | ((_, _), expr2, _)::ttl ->
+ ((l, n1), expr2, Some expr), (ttl))
+
+ (* Declaration without type info *)
+ | (v, expr, false) -> (v, expr, None), tl)
+(* Add declaration in the environment *)
+and lexp_p_decls (decl: (pvar * pexp * pexp option)) ctx =
+ let ((loc, vname), pxp, _) = decl in
+
+ (* we should add the defined var to ctx *)
+ let nctx = senv_add_var vname loc ctx in
+
+ (*let idx = senv_lookup vname nctx in *)
+ let lxp, ltp = lexp_p_infer pxp nctx in
+
+ (* Add Var info*)
+ let nctx = env_add_var_info (0, (loc, vname), lxp, ltp) nctx in
+
+ (* return processed var *)
+ ((loc, vname), lxp, ltp), nctx
+
(* Parse let declaration *)
and lexp_parse_let decls ctx =
@@ -428,7 +455,16 @@ and lexp_parse_let decls ctx =
let acc, ctx = process_var_info decls nctx [] in
acc, ctx
-and lexp_parse_all (p: pexp list) (ctx: lexp_context):
+and lexp_parse_all (p: ptop list) (ctx: lexp_context):
+ (ltop list * lexp_context) =
+ let rec loop (plst: ptop list) ctx (acc: ltop list) =
+ match plst with
+ | [] -> ((List.rev acc), ctx)
+ | _ -> let lxp, new_ctx = lexp_p_toplevel (List.hd plst) ctx in
+ (loop (List.tl plst) new_ctx (lxp::acc)) in
+ (loop p ctx [])
+
+and lexp_p_all (p: pexp list) (ctx: lexp_context):
(lexp list * lexp_context) =
let rec loop (plst: pexp list) ctx (acc: lexp list) =
match plst with
@@ -461,7 +497,7 @@ and lexp_p_infer (p : pexp) (env : lexp_context) : lexp * ltype =
let lxp, nctx = lexp_parse p env in
lxp, UnknownType(dummy_location)
-and lexp_p_check (env : lexp_context) (p : pexp) (t : ltype) : lexp =
+and lexp_p_check (p : pexp) (t : ltype) (env : lexp_context): lexp =
match p with
| _
-> let (e, inferred_t) = lexp_p_infer p env in
@@ -470,6 +506,7 @@ and lexp_p_check (env : lexp_context) (p : pexp) (t : ltype) : lexp =
(*
* Printing
* --------------------- *)
+(* Print back in CET (Close Enough Typer) easier to read *)
(* So print can be called while parsing *)
and lexp_print_adv opt exp =
let slexp_print = lexp_print_adv opt in (* short_lexp_print *)
@@ -589,15 +626,16 @@ and lexp_print_decls opt decls =
(* Print context *)
and lexp_context_print ctx =
let ((n, map), env) = ctx in
+
+ print_string (make_title " LEXP CONTEXT ");
- print_string (" " ^ (make_line '=' 20) ^ " LEXP CONTEXT " ^ (make_line '=' 20) ^ "\n");
- print_string " | ";
- ralign_print_string "NAME" 10; print_string " | ";
- ralign_print_string "INDEX" 7; print_string " | ";
- ralign_print_string "NAME" 10; print_string " | ";
- ralign_print_string "VALUE" 7; print_string ": ";
- print_string "TYPE"; print_string "\n";
- print_string (" " ^ (make_line '-' 54) ^ "\n");
+ make_rheader [
+ (Some ('r', 10), "NAME");
+ (Some ('r', 7), "INDEX");
+ (Some ('r', 10), "NAME");
+ (Some ('r', 20), "VALUE:TYPE")];
+
+ print_string (make_sep '-');
StringMap.iter (fun key idx ->
(* Print senv info *)
@@ -620,7 +658,7 @@ and lexp_context_print ctx =
map;
- print_string (" " ^ (make_line '=' 54) ^ "\n");
+ print_string (make_sep '=');
(* Only print var info *)
and lexp_print_var_info ctx =
@@ -638,18 +676,26 @@ and lexp_print_var_info ctx =
done;
;;
-let lexp_print = lexp_print_adv (false, 0, true)
-
+let lexp_print e =
+ match e with
+ | Ltexp (x) -> lexp_print_adv (false, 0, true) x
+ | Ltdecl ((_, x), lxp, ltp) ->
+ print_string x;
+ print_string " = ";
+ lexp_print_adv (false, 0, true) lxp;
+ print_string " : ";
+ lexp_print_adv (false, 0, true) ltp
+;;
-let lexp_parse_string (str: string) tenv grm limit =
+let lexp_parse_string (str: string) tenv grm limit ctx =
let pretoks = prelex_string str in
let toks = lex tenv pretoks in
let sxps = sexp_parse_all_to_list grm toks limit in
- let ctx = make_lexp_context in
let pxps = pexp_parse_all sxps in
lexp_parse_all pxps ctx
;;
+(* add dummy definition helper *)
let add_def name ctx =
let ctx = senv_add_var name dloc ctx in
env_add_var_info (0, (dloc, name), dlxp, dlxp) ctx
=====================================
src/pexp.ml
=====================================
--- a/src/pexp.ml
+++ b/src/pexp.ml
@@ -61,6 +61,15 @@ type pexp =
* (symbol * (arg_kind * pvar option * pexp) list) list
| Pcons of pvar * symbol
| Pcase of location * pexp * (ppat * pexp) list
+
+(* Top level expression annotation *)
+type ptop =
+ | Ptexp of pexp
+ (* Declarations *)
+ | Ptann of pvar * pexp (* Type annotation *)
+ | Ptdecl of pvar * pexp (* Declaration *)
+ | Ptanndecl of pvar * pexp * pexp (* Annotated declaration *)
+ | Ptnone
let rec pexp_location e =
match e with
@@ -81,11 +90,29 @@ let rec pexp_pat_location e = match e with
| Ppatany l -> l
| Ppatvar (l,_) -> l
| Ppatcons ((l, _), _) -> l
-
+;;
+
+let pexp_location_toplevel e =
+ match e with
+ | Ptexp (x) -> pexp_location x
+ | Ptdecl ((x, _), _) -> x
+ | Ptann ((x, _), _) -> x
+ | Ptanndecl((x, _), _, _) -> x
+;;
+
+(* We use a list so we can merge 2 contiguous definitions *)
+let rec pexp_p_toplevel (s : sexp): ptop =
+
+ match s with
+ | Node (Symbol (_, "_:_"), _) ->
+ let (a, b, _)::_ = pexp_p_decls s in Ptann (a, b)
+ | Node (Symbol (_, "_=_"), _) ->
+ let (a, b, _)::_ = pexp_p_decls s in Ptdecl (a, b)
+ | _ -> Ptexp(pexp_parse s)
+
(* In the following "pexp_p" the prefix for "parse a sexp, returning a pexp"
* and "pexp_u" is the prefix for "unparse a pexp, returning a sexp". *)
-
-let rec pexp_parse (s : sexp) : pexp =
+and pexp_parse (s : sexp) : pexp =
match s with
(* This is an internal error because Epsilon does not have any location
* information so it needs to be caught elsewhere. *)
@@ -350,9 +377,19 @@ and pexp_u_decls ds =
let pexp_print e = sexp_print (pexp_unparse e)
+
+let pexp_print_toplevel e =
+ match e with
+ | Ptexp (x) -> pexp_print x
+ | Ptdecl ((_, n), e) -> print_string (n ^ " = "); pexp_print e;
+ | Ptann ((_, n), e) -> print_string (n ^ " : "); pexp_print e;
+ | Ptanndecl((_, n), e, t) -> print_string (n ^ " = "); pexp_print e;
+;;
+
+
(* Parse All Pexp as a list *)
let pexp_parse_all (nodes: sexp list) =
- List.map pexp_parse nodes
+ List.map pexp_p_toplevel nodes
;;
let pexp_parse_string (str: string) tenv grm limit =
=====================================
tests/REPL.ml
=====================================
--- a/tests/REPL.ml
+++ b/tests/REPL.ml
@@ -23,37 +23,29 @@ let rec read_input i =
print_input_line i;
flush stdout;
- let rec loop str =
+ let rec loop str i =
+ flush stdout;
let line = input_line stdin in
let s = String.length str in
let n = String.length line in
- if n = 0 then loop str else
+ if s = 0 && n = 0 then read_input (i + 1) else
+ (if n = 0 then (
+ print_string " : ";
+ print_string (make_line ' ' (i * 4));
+ loop str (i + 1))
+ else
let str = if s > 0 then String.concat "\n" [str; line] else line in
if line.[n - 1] = ';' || line.[0] = '%' then
str
- else
- (print_string " "; loop str) in
+ else (
+ print_string " . ";
+ print_string (make_line ' ' (i * 4));
+ loop str (i + 1))) in
- loop ""
+ loop "" 1
;;
-let eval_string (str: string) tenv grm limit lxp_ctx rctx =
- let rec eval_all lxps acc rctx =
- match lxps with
- | [] -> (List.rev acc), rctx
- | hd::tl ->
- let lxp, rctx = eval hd rctx in
- eval_all tl (lxp::acc) rctx in
-
- let pretoks = prelex_string str in
- let toks = lex tenv pretoks in
- let sxps = sexp_parse_all_to_list grm toks limit in
- let pxps = pexp_parse_all sxps in
- let lxp, lxp_ctx = lexp_parse_all pxps lxp_ctx in
- (eval_all lxp [] rctx), lxp_ctx
-;;
-
(* Specials commands %[command-name] *)
let rec repl () =
let tenv = default_stt in
@@ -64,7 +56,6 @@ let rec repl () =
(* Those are hardcoded operation *)
let lxp_ctx = add_def "_+_" lxp_ctx in
let lxp_ctx = add_def "_*_" lxp_ctx in
- let lxp_ctx = add_def "_=_" lxp_ctx in
let rctx = make_runtime_ctx in
@@ -76,24 +67,25 @@ let rec repl () =
(print_rte_ctx rctx; loop (i + 1) clxp rctx)
else if ipt = "%info" then
(lexp_context_print clxp; loop (i + 1) clxp rctx)
+ else if ipt = "%calltrace" then
+ (print_call_trace (); loop (i + 1) clxp rctx)
(* Else Process Typer code *)
else
let (ret, rctx), clxp = (eval_string ipt clxp rctx) in
- let printe j v = print_eval_result i v in
- List.iteri printe ret;
- print_string "\n";
+ let print_e j v = print_eval_result i v in
+ List.iteri print_e ret;
loop (i + 1) clxp rctx in
loop 1 lxp_ctx rctx
;;
let main () =
- print_string ((make_line '-' 80) ^ "\n");
- print_string " Typer REPL \n";
- print_string " %quit : to leave\n";
- print_string " %who : to print runtime environment\n";
- print_string " %info : to print elaboration environment\n";
- print_string ((make_line '-' 80) ^ "\n\n");
+ print_string (make_title " TYPER REPL ");
+ print_string " %quit : leave REPL\n";
+ print_string " %who : print runtime environment\n";
+ print_string " %info : print elaboration environment\n";
+ print_string " %calltrace : print call trace of last call \n";
+ print_string (make_sep '=');
flush stdout;
repl ()
=====================================
tests/debruijn_test.ml deleted
=====================================
--- a/tests/debruijn_test.ml
+++ /dev/null
@@ -1,32 +0,0 @@
-(* TODO make some real test *)
-open Debruijn
-open Util
-
-let main () =
- (* Tests *)
- (* Create a new scope: global scope *)
- let loc = dummy_location in
- let g0 = make_context in
- let g1 = add_variable "a" loc g0 in
- let g2 = add_variable "a" loc g1 in
- let g3 = add_variable "b" loc g2 in
- let g4 = add_variable "c" loc g3 in
- let g5 = add_variable "d" loc g4 in
-
- (* we enter a let or whatever *)
- let l0 = add_scope g5 in
- let l1 = add_variable "a" loc l0 in
- let l2 = add_variable "e" loc l1 in
-
- (* Testing is done *)
- print_string "Inner Context\n";
- print_lexp_context l2;
-
- (* We exit the scope *)
- print_string "Outer Context\n";
- print_lexp_context g5
-;;
-
-
-main ()
-;;
\ No newline at end of file
=====================================
tests/debug.ml
=====================================
--- a/tests/debug.ml
+++ b/tests/debug.ml
@@ -114,27 +114,30 @@ let debug_sexp_print_all tokens =
(* Print a Pexp with debug info *)
-let debug_pexp_print pexp =
+let debug_pexp_print ptop =
print_string " ";
- let l = pexp_location pexp in
+ let l = pexp_location_toplevel ptop in
let print_info msg loc pex =
print_string msg; print_string "[";
print_loc loc;
print_string "]\t";
- pexp_print pexp in
- match pexp with
- | Pimm _ -> print_info "Pimm " l pexp
- | Pvar (_,_) -> print_info "Pvar " l pexp
- | Phastype (_,_,_) -> print_info "Phastype " l pexp
- | Pmetavar (_, _) -> print_info "Pmetavar " l pexp
- | Plet (_, _, _) -> print_info "Plet " l pexp
- | Parrow (_, _, _, _, _) -> print_info "Parrow " l pexp
- | Plambda (_,_, _, _) -> print_info "Plambda " l pexp
- | Pcall (_, _) -> print_info "Pcall " l pexp
- | Pinductive (_, _, _) -> print_info "Pinductive " l pexp
- | Pcons (_,_) -> print_info "Pcons " l pexp
- | Pcase (_, _, _) -> print_info "Pcase " l pexp
- | _ -> print_info "Not Impl " l pexp
+ pexp_print_toplevel pex in
+ match ptop with
+ | Ptdecl((l, n), pexp) -> print_info "PDecl " l ptop
+ | Ptexp (pexp) -> (
+ match pexp with
+ | Pimm _ -> print_info "Pimm " l ptop
+ | Pvar (_,_) -> print_info "Pvar " l ptop
+ | Phastype (_,_,_) -> print_info "Phastype " l ptop
+ | Pmetavar (_, _) -> print_info "Pmetavar " l ptop
+ | Plet (_, _, _) -> print_info "Plet " l ptop
+ | Parrow (_, _, _, _, _) -> print_info "Parrow " l ptop
+ | Plambda (_,_, _, _) -> print_info "Plambda " l ptop
+ | Pcall (_, _) -> print_info "Pcall " l ptop
+ | Pinductive (_, _, _) -> print_info "Pinductive " l ptop
+ | Pcons (_,_) -> print_info "Pcons " l ptop
+ | Pcase (_, _, _) -> print_info "Pcase " l ptop
+ | _ -> print_info "Not Impl " l ptop)
;;
(* Print a list of pexp *)
@@ -147,7 +150,7 @@ let debug_pexp_print_all pexps =
;;
(* Print lexp with debug info *)
-let debug_lexp_print lxp =
+let debug_lexp_print tlxp =
print_string " ";
let dloc = dummy_location in
let print_info msg loc lex =
@@ -155,18 +158,21 @@ let debug_lexp_print lxp =
print_loc loc;
print_string "]\t";
lexp_print lex in
- let tloc = lexp_location lxp in
+ let tloc = lexp_location_toplevel tlxp in
+ match tlxp with
+ | Ltdecl ((_, x), lxp, ltp) -> print_info "Decl " tloc tlxp
+ | Ltexp(lxp) ->
match lxp with
- | Var((loc, _), _) -> print_info "Var " tloc lxp
- | Imm(s) -> print_info "Imm " tloc lxp
- | Let(loc, _, _) -> print_info "Let " tloc lxp
- | Arrow(_, _, _, loc, _) -> print_info "Arrow " tloc lxp
- | Lambda(_, (loc, _), _, _) -> print_info "Lambda " tloc lxp
- | Call(_, _) -> print_info "Call " tloc lxp
- | Inductive(loc, _, _, _) -> print_info "Inductive " tloc lxp
- | UnknownType(loc) -> print_info "UnknownType " tloc lxp
- | Case(loc, _, _, _, _) -> print_info "Case " tloc lxp
- | Cons (rf, sym) -> print_info "Cons " tloc lxp
+ | Var((loc, _), _) -> print_info "Var " tloc tlxp
+ | Imm(s) -> print_info "Imm " tloc tlxp
+ | Let(loc, _, _) -> print_info "Let " tloc tlxp
+ | Arrow(_, _, _, loc, _) -> print_info "Arrow " tloc tlxp
+ | Lambda(_, (loc, _), _, _) -> print_info "Lambda " tloc tlxp
+ | Call(_, _) -> print_info "Call " tloc tlxp
+ | Inductive(loc, _, _, _) -> print_info "Inductive " tloc tlxp
+ | UnknownType(loc) -> print_info "UnknownType " tloc tlxp
+ | Case(loc, _, _, _, _) -> print_info "Case " tloc tlxp
+ | Cons (rf, sym) -> print_info "Cons " tloc tlxp
| _ -> print_string "Debug Printing Not Implemented";
;;
=====================================
tests/full_debug.ml
=====================================
--- a/tests/full_debug.ml
+++ b/tests/full_debug.ml
@@ -36,11 +36,15 @@ open Lexer
open Sexp
open Grammar
open Pexp
+open Util
+open Fmt
+
+let dloc = dummy_location;;
+
open Debruijn
-open Lparse
open Myers
+open Lparse
open Eval
-open Util
open Lexp
(* pexp and lexp can be done together, one by one *)
@@ -49,7 +53,7 @@ let pexp_lexp_one node ctx =
lexp_parse pxp ctx
;;
-let dloc = dummy_location;;
+
let pexp_lexp_all nodes ctx =
@@ -75,11 +79,11 @@ let eval_until_nth xpr n rctx =
| [], _ -> rctx
| _, nb when nb = n -> rctx
| hd::tl, _ ->
- let c, rctx = eval hd rctx in
+ let c, rctx = eval_toplevel hd rctx in
print_eval_result nb c;
loop tl (nb + 1) rctx in
loop xpr 0 rctx
-;;
+;;
let main () =
@@ -87,11 +91,6 @@ let main () =
let usage =
" Usage: \n " ^ Sys.argv.(0) ^ " <file_name> [options] \n\n" in
- let print_title msg =
- print_string "\n\t====\n";
- print_string ("\t " ^ msg ^ "\n");
- print_string "\t=======================\n" in
-
(* Print Usage *)
if arg_n == 1 then
begin
@@ -104,6 +103,7 @@ let main () =
(* Read additional Args if any *)
+ print_string (make_title " ERRORS ");
(* get pretokens*)
let pretoks = prelex_file filename in
@@ -121,28 +121,34 @@ let main () =
(* Those are hardcoded operation *)
let ctx = add_def "_+_" ctx in
let ctx = add_def "_*_" ctx in
- let ctx = add_def "_=_" ctx in
- let lexps, new_ctx = lexp_parse_all pexps ctx in
+ let lexps, new_ctx = lexp_parse_all pexps ctx in
+ print_string "\n\n";
(* Printing *)(*
print_title "PreTokens"; debug_pretokens_print_all pretoks;
print_title "Base Sexp"; debug_sexp_print_all toks; *)
- print_title "Node Sexp"; debug_sexp_print_all nodes;
- print_title "Pexp"; debug_pexp_print_all pexps;
- print_title "Lexp"; debug_lexp_print_all lexps;
-
- print_string "\n\n";
- lexp_context_print new_ctx;
+ print_string (make_title " Node Sexp "); debug_sexp_print_all nodes;
+ print_string "\n";
+ print_string (make_title " Pexp "); debug_pexp_print_all pexps;
+ print_string "\n";
+ print_string (make_title " Lexp "); debug_lexp_print_all lexps;
+ print_string "\n";
(* Eval Each Expression *)
- print_title "Eval Print";
+ print_string (make_title " Eval Print ");
(* Eval One *)
let rctx = make_runtime_ctx in
let rctx = eval_until_nth lexps 500 rctx in
print_string "\n\n";
- print_rte_ctx rctx;
+ print_rte_ctx rctx;
+
+ print_string "\n";
+ lexp_context_print new_ctx;
+ print_string "\n";
+
+ print_call_trace ();
end
;;
=====================================
tests/let_test.ml
=====================================
--- /dev/null
+++ b/tests/let_test.ml
@@ -0,0 +1,30 @@
+
+open Eval
+
+
+(* How to make macro in ocaml? *)
+
+(*
+let EXPECT_EQUAL a b =
+ if a = b then(print_string "[ OK]\n"; SUCCESS)
+ else( print_string "[ FAIL]\n"; FAILURE)
+;;
+
+let EXPECT_THROW a error =
+ try ((a); print_string "[ FAIL]\n"; FAILURE)
+ with (print_string "[ OK]\n"; SUCCESS)
+;; *)
+
+
+let main () =
+
+ let ret = easy_eval_string "let a = 3; b = 5; in a + b;" in
+ match ret with
+ | [xpr] -> let v = get_int xpr in
+ if v = 8 then (exit 0) else (exit (-1))
+ | _ -> exit (-1)
+
+;;
+
+main ()
+;;
\ No newline at end of file
=====================================
tests/utest_main.ml
=====================================
--- a/tests/utest_main.ml
+++ b/tests/utest_main.ml
@@ -66,10 +66,7 @@ let main () =
tests_n := !tests_n + 1;
- print_string " " ;
- print_int !tests_n;
- print_endline (") " ^ (cut_name files.(i)));
- print_endline "[RUN ]";
+ print_endline ("[RUN ] TEST: " ^ (cut_name files.(i)));
exit_code := Sys.command (folder ^ files.(i) ^ " " ^ root_folder);
View it on GitLab: https://gitlab.com/monnier/typer/compare/c6d73fd58240616b5dd5c60c80b96d586e…
2
1
Setepenre pushed to branch master at Stefan / Typer
Commits:
573e2b5b by Pierre Delaunay at 2016-03-01T23:12:57-05:00
PCase
- - - - -
496106a8 by Pierre Delaunay at 2016-03-02T00:11:28-05:00
simple eval
- - - - -
81fa9435 by Pierre Delaunay at 2016-03-02T09:26:56-05:00
merged equivalent definition + moved inference routine to lparse
- - - - -
7 changed files:
- samples/lexp_test.typer
- src/debruijn.ml
- + src/eval.ml
- src/lexp.ml
- src/lparse.ml
- tests/debug.ml
- tests/full_debug.ml
Changes:
=====================================
samples/lexp_test.typer
=====================================
--- a/samples/lexp_test.typer
+++ b/samples/lexp_test.typer
@@ -1,62 +1,52 @@
-ab;
-
-% Type is read as a Pvar ?????
-add = lambda (a : Type) -> lambda (b : Type) -> (add a b);
-
-% How typer is supposed to read this
-p:int -> int;
-
-% this is a call to _=_
-odd n = case n | 0 => false | S n' => even (n');
-
-%
-% Here we test that two declaration with different
-% name are EXACLTY equivalent in the eyes
-% of the compiler
-%
-% Declaration order STILL MATTERS
-%
-
-% let
-let a:Nat; d:Nat; c:Nat; b:Nat;
- a = b;
- d = a;
- c = d;
- b = c;
- in a + b + c + d
-;
-
-% let: Different naming
-let e:Nat; f:Nat; g:Nat; h:Nat;
- e = h;
- f = e;
- g = f;
- h = g;
- in e + h + g + f
-;
-
-% let: Different Ordering
-let b:Nat; c:Nat; d:Nat; a:Nat;
- c = d;
- d = a;
- b = c;
- a = b;
- in a + b + c + d
-;
-
-%
-% Recursivity detection
-%
-
-let odd: (int -> int);
- even: (int -> int);
- odd n = case n | 0 => false | S n' => even (n');
- even n = case n | 0 => true | S n' => odd (n');
- in a + b;
-
-
-% Do I consider functions as variable ?? Yes
-
-
-
-
+% Eval test
+
+let c = 1; a = 5; b = 10; d = 3; in
+ a + b;
+
+% -------------------------------------------
+% Function Calls
+% -------------------------------------------
+
+% define sqrt
+sqrt x = lambda (x : Nat) -> x * x;
+
+% define cube
+cube = lambda (x : Nat) -> x * (sqrt x);
+
+% explicit
+mult = lambda (x : Nat) -> lambda (y : Nat) -> (y * x);
+
+% implicit (Type annotation introduce a bug)
+cube = lambda x y -> (x * y);
+
+
+% -------------------------------------------
+% Inductive type
+% -------------------------------------------
+
+inductive_ (dummy_Nat) (zero) (succ Nat);
+
+% Usage
+Nat : Type % This line is not parsed
+Nat = inductive_ (dummy_Nat) (zero) (succ Nat); % zero is not parsed
+
+% Constructor
+% -------------------------------------------
+
+% only inductive-cons is available
+
+inductive-cons Nat succ;
+
+% Usage
+zero = inductive-cons Nat zero; % those are aliases
+succ = inductive-cons Nat succ;
+
+one = (succ (zero));
+
+% -------------------------------------------
+% Cases
+% -------------------------------------------
+
+case x
+ | zero => y
+ | succ x => succ (plus x y);
=====================================
src/debruijn.ml
=====================================
--- a/src/debruijn.ml
+++ b/src/debruijn.ml
@@ -30,18 +30,11 @@
* methods starting with '_' are considered private and should not
* elsewhere in the project
*
- * Methods:
- * make_context : make an empty context
- * add_scope ctx : add new scope to the current context
- * find_var name ctx: return the index of the variable 'name'
- * add_variable name loc ctx : add a variable to the current context
- *
- * TODO:
- * ADD meyers list <index -> (type, name?)>
- *
* ---------------------------------------------------------------------------*)
open Util
+open Lexp
+open Myers
let debruijn_error = msg_error "DEBRUIJN"
let debruijn_warning = msg_warning "DEBRUIJN"
@@ -49,6 +42,10 @@ let debruijn_warning = msg_warning "DEBRUIJN"
(* Type definitions
* ---------------------------------- *)
+(* Index -> Variable Info *)
+type env_elem = (int * (location * string) * lexp * ltype)
+type env_type = env_elem myers
+
(* This exist because I don't want that file to depend on anything *)
module StringMap
= Map.Make (struct type t = string let compare = String.compare end)
@@ -60,50 +57,55 @@ type scope = (int) StringMap.t (* Map<String, int>*)
(* Offset is the number to take us out of the inner scope
* Scope is the Mapping between Variable's names and its current index loc
* Offset + Scope *)
-type context_impl = int * scope
+type senv_type = int * scope
(* The recursive type that does everything
* inner Scope * Outer Scope *)
-type lexp_context = context_impl * lexp_context option
+type lexp_context = senv_type * lexp_context option * env_type
(* internal definitions: DO NOT USE
* ---------------------------------- *)
-
+
let _make_scope = StringMap.empty;;
let _make_context_impl = (0, _make_scope);;
+let _make_myers = nil
let _get_inner_ctx (ctx: lexp_context) =
- match ctx with
- | (ct, _) -> ct
+ let (ct, _, _) = ctx in ct
;;
let _get_inner_scope (ctx: lexp_context): scope =
- let ictx = _get_inner_ctx ctx in
- match ictx with
- | (_, scope) -> scope
+ let ((_, scope), _, _) = ctx in scope
+;;
+
+let _get_environ (ctx: lexp_context) =
+ let (_, _, env) = ctx in env
;;
(* get current offset *)
let _get_offset (ctx: lexp_context): int =
- let inner = _get_inner_ctx ctx in
- match inner with
- | offset, _ -> offset
+ let ((offset, _), _, _) = ctx in offset
;;
(* increase the offset *)
let _inc_offset (ctx: lexp_context): lexp_context =
(* Because using ref is hell, we make a copy *)
match ctx with
- | ((offset, scope), None) -> ((offset + 1, scope), None)
- | ((offset, scope), Some outter) -> ((offset + 1, scope), Some outter)
+ | ((offset, scope), None, e) -> ((offset + 1, scope), None, e)
+ | ((offset, scope), Some outter, e) ->
+ ((offset + 1, scope), Some outter, e)
;;
(* Increase the indexes of all inner variables *)
let _inc_index (ctx: lexp_context): lexp_context =
- let ((offset, scope), otr) = ctx in
+ let ((offset, scope), otr, env) = ctx in
let scope = StringMap.map (fun value -> value + 1) scope in
- ((offset, scope), otr)
+ ((offset, scope), otr, env)
+;;
+
+let _add_var_environ variable ctx =
+ let (a, b, env) = ctx in cons variable env
;;
(* Public methods: DO USE
@@ -112,7 +114,7 @@ let _inc_index (ctx: lexp_context): lexp_context =
(* return its current DeBruijn index
* return -1 if the variable does not exist
* return closest variable *)
-let rec find_var (name: string) (ctx: lexp_context) =
+let rec senv_lookup (name: string) (ctx: lexp_context) =
(* Search *)
let local_index = find_local name ctx in
if local_index >= 0 then
@@ -137,14 +139,16 @@ and find_local (name: string) (ctx: lexp_context): int =
* the reason is _find_outer does not send back a correct index *)
and _find_outer (name: string) (ctx: lexp_context): int =
match ctx with
- | (_, Some ct) -> (find_var name ct)
+ | (_, Some ct, _) -> (senv_lookup name ct)
| _ -> -1
;;
-
-(* Alias *)
-let get_var_index name ctx = find_var name ctx;;
-let add_variable name loc ctx =
+(* We first add variable into our map later on we will add them into
+ * the environment. The reason for this is that the type info is
+ * known after lexp parsing which need the index fist *)
+let senv_add_var name loc ctx =
+ (*let (name, loc, exp, type_info) = var in *)
+
(* I think this should be illegal *)
let local_index = find_local name ctx in
if local_index >= 0 then (* This is the index not the number of element *)
@@ -156,21 +160,46 @@ let add_variable name loc ctx =
(* Increase distance *)
let scope = StringMap.map (fun value -> value + 1) (_get_inner_scope ctx) in
- (* Add new Value *)
+ (* Add new Value to the map *)
let new_scope = StringMap.add name 0 scope in
(* build new context *)
match ctx with
- | ((offset, _), None)
- -> ((offset + 1, new_scope), None)
- | ((offset, _), Some outter)
- -> ((offset + 1, new_scope), Some outter)
+ | ((offset, _), None, e)
+ -> ((offset + 1, new_scope), None, e)
+ | ((offset, _), Some outter, e)
+ -> ((offset + 1, new_scope), Some outter, e)
;;
+(* *)
+let env_add_var_info var ctx =
+ let (rof, (loc, name), value, ltyp) = var in
+ let nenv = _add_var_environ (rof, (loc, name), value, ltyp) ctx in
+ let (a, b, env) = ctx in
+ (a, b, nenv)
+;;
+
+let env_lookup_type_by_index index ctx =
+ try
+ let (roffset, (_, name), _, t) = Myers.nth index (_get_environ ctx) in
+ Shift (index - roffset, t)
+ with
+ Not_found -> internal_error "DeBruijn index out of bounds!"
+;;
+
+let env_lookup_type (env : env_type) (v : vref) =
+ let ((_, rname), dbi) = v in
+ try let (recursion_offset, (_, dname), _, t) = Myers.nth dbi env in
+ if dname = rname then
+ Shift (dbi - recursion_offset, t)
+ else
+ internal_error "DeBruijn index refers to wrong name!"
+ with Not_found -> internal_error "DeBruijn index out of bounds!"
+
(* Make a Global context *)
-let make_context = (_make_context_impl, None);;
+let make_context = (_make_context_impl, None, _make_myers);;
(* Make a new Scope inside the outer context 'ctx' *)
-let add_scope ctx = (_make_context_impl, Some ctx);;
+let add_scope ctx = (_make_context_impl, Some ctx, _make_myers);;
(* Print Functions for testing *)
let print_scope (scp: scope) (offset: int): unit =
@@ -188,7 +217,7 @@ let print_lexp_context (ctx: lexp_context): unit =
let rec impl (ctx2: lexp_context) (offset: int) =
let inner = _get_inner_scope ctx2 in
match ctx2 with
- | (_, Some ct)
+ | (_, Some ct, _)
-> impl ct ((_get_offset ctx2) + offset);
(print_scope inner offset);
| _ -> (print_scope inner offset) in
=====================================
src/eval.ml
=====================================
--- /dev/null
+++ b/src/eval.ml
@@ -0,0 +1,159 @@
+(*
+ * Typer Compiler
+ *
+ * ---------------------------------------------------------------------------
+ *
+ * Copyright (C) 2011-2016 Free Software Foundation, Inc.
+ *
+ * Author: Pierre Delaunay <pierre.delaunay(a)hec.ca>
+ * Keywords: languages, lisp, dependent types.
+ *
+ * This file is part of Typer.
+ *
+ * Typer is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ * Typer is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * ---------------------------------------------------------------------------
+ *
+ * Description:
+ * Simple interpreter
+ *
+ * --------------------------------------------------------------------------- *)
+
+open Util
+open Lexp
+open Lparse
+open Myers
+open Sexp
+open Fmt
+
+
+
+let print_myers_list l print_fun =
+ let n = (length l) in
+
+ print_string "-------------------\n";
+ print_string " Environement: \n";
+ print_string "-------------------\n";
+
+ for i = 0 to n - 1 do
+ ralign_print_int (i + 1) 4;
+ print_string ") ";
+ print_fun (nth i l);
+ done;
+ print_string "-------------------\n";
+;;
+
+let get_function_name fname =
+ match fname with
+ | Var(v) -> let ((loc, name), idx) = v in name
+ | _ -> "Name Lookup failure"
+;;
+
+let get_int lxp =
+ match lxp with
+ | Imm(Integer(_, l)) -> l
+ | _ -> lexp_print lxp; -1
+;;
+
+(* Runtime Environ *)
+type runtime_env = lexp myers
+let make_runtime_ctx = nil;;
+let add_rte_variable x l = (cons x l);;
+let get_rte_variable idx l = (nth (idx) l);;
+
+let print_rte_ctx l = print_myers_list l
+ (fun g -> lexp_print g; print_string "\n")
+;;
+
+(* Evaluation reduce an expression x to an Lexp.Imm *)
+let rec eval lxp ctx: (lexp * runtime_env) =
+
+ match lxp with
+ (* This is already a leaf *)
+ | Imm(v) -> lxp, ctx
+
+ (* Return a value stored in the environ *)
+ | Var((loc, name), idx) -> begin
+ try
+ (get_rte_variable idx ctx), ctx
+ with
+ Not_found ->
+ print_string ("Variable: " ^ name ^ " was not found | ");
+ print_int idx; print_string "\n";
+ raise Not_found end
+
+ (* this works for non recursive let *)
+ | Let(_, decls, inst) -> begin
+ (* First we evaluate all declaration then we evaluate the instruction *)
+ let nctx = build_ctx decls ctx in
+ let value, nctx = eval inst nctx in
+ (* return old context as we exit let's scope*)
+ value, ctx end
+
+ (* Function call *)
+ | Call (fname, args) ->
+ (* Add args in the scope *)
+ let nctx = build_arg_list args ctx in
+
+ (* We need to seek out the function declaration and eval the body *)
+ (* but currently we cannot declare functions so I hardcoded + *)
+ (* let bdy = get_body fname in
+ eval bdy nctx *)
+
+ (* fname is currently a var *)
+ let name = get_function_name fname in
+ (* Hardcoded function for now *)
+ if name = "_+_" then begin
+
+ (* Get the two args *)
+ let l = get_int (get_rte_variable 0 nctx) in
+ let r = get_int (get_rte_variable 1 nctx) in
+
+ Imm(Integer(dummy_location, l + r)), ctx end
+ else
+ Imm(String(dummy_location, "Funct Not Implemented")), ctx
+
+ | _ -> Imm(String(dummy_location, "Eval Not Implemented")), ctx
+
+and build_arg_list args ctx =
+
+ (* Eval every args *)
+ let arg_val = List.map (fun (k, e) -> let (v, c) = eval e ctx in v) args in
+
+ (* Add args inside context *)
+ List.fold_left (fun c v -> add_rte_variable v c) ctx arg_val
+
+and build_ctx decls ctx =
+ match decls with
+ | [] -> ctx
+ | hd::tl ->
+ let (v, exp, tp) = hd in
+ let (value, nctx) = eval exp ctx in
+ let nctx = add_rte_variable value nctx in
+ build_ctx tl nctx
+;;
+
+let print_eval_result lxp =
+ print_string " >> ";
+ match lxp with
+ | Imm(v) -> sexp_print v; print_string "\n"
+ | _ -> print_string "Evaluation Failed\n"
+;;
+
+let evalprint lxp ctx =
+ let v, ctx = (eval lxp ctx) in
+ print_eval_result v;
+ ctx
+;;
+
=====================================
src/lexp.ml
=====================================
--- a/src/lexp.ml
+++ b/src/lexp.ml
@@ -192,17 +192,6 @@ let builtins =
*)
-type env_elem = (db_offset * vdef * lexp option * ltype)
-type env_type = env_elem myers
-let env_lookup_type (env : env_type) (v : vref) =
- let ((_, rname), dbi) = v in
- try let (recursion_offset, (_, dname), _, t) = Myers.nth dbi env in
- if dname = rname then
- Shift (dbi - recursion_offset, t)
- else
- internal_error "DeBruijn index refers to wrong name!"
- with Not_found -> internal_error "DeBruijn index out of bounds!"
-
(***** SMap fold2 helper *****)
let smap_fold2 c f m1 m2 init
@@ -659,39 +648,4 @@ let lexp_print e = sexp_print (pexp_unparse (lexp_unparse e))
* | _ -> msg_error l "Uninstantiated metavar of unknown type";
* mk_meta_dummy env l *)
-(*
-let rec lexp_parse (p : pexp) (env : (vdef * lexp option * ltype) myers) = *)
*)
-
-(* FIXME
-type senv_type = (db_revindex SMap.t * db_index)
-let senv_lookup senv s : db_index =
- let (m, i) = senv in
- i - SMap.find s senv *)
-
-(* Parsing a Pexp into an Lexp is really "elaboration", i.e. it needs to
- * infer the types and perform macro-expansion. For won't really
- * do any of that, but we can already start structuring it accordingly.
- *
- * More specifically, we do it with 2 mutually recursive functions:
- * one takes a Pexp along with its expected type and return an Lexp
- * of that type (hopefully), whereas the other takes a Pexp and
- * infers its type (which it returns along with the Lexp).
- * This is the idea of "bidirectional type checking", which minimizes
- * the amount of "guessing" and/or annotations. Basically guessing/annotations
- * is only needed at those few places where the code is not fully-normalized,
- * which in normal programs is only in "let" definitions.
- * So the rule of thumbs are:
- * - use lexp_p_infer for destructors, and use lexp_p_check for constructors.
- * - use lexp_p_check whenever you can.
- *)
-
-let rec lexp_p_infer (env : env_type) (p : pexp) : lexp * ltype =
- (UnknownType(dummy_location), UnknownType(dummy_location))
-
-and lexp_p_check (env : env_type) (p : pexp) (t : ltype) : lexp =
- match p with
- | _
- -> let (e, inferred_t) = lexp_p_infer env p in
- (* FIXME: check that inferred_t = t! *)
- e
=====================================
src/lparse.ml
=====================================
--- a/src/lparse.ml
+++ b/src/lparse.ml
@@ -47,9 +47,18 @@ let not_implemented_error () =
internal_error "not implemented"
;;
-let lexp_error = msg_error "LEXP"
+let lexp_error loc msg =
+ msg_error "LEXP" loc msg;
+ raise (internal_error msg)
+;;
+
+let dloc = dummy_location
let lexp_warning = msg_warning "LEXP"
+(* Print back in CET (Close Enough Typer) easier to read *)
+ (* pretty ? * indent level * print_type? *)
+type print_context = (bool * int * bool)
+
(* Vdef is exactly similar to Pvar but need to modify our ctx *)
let pvar_to_vdef p =
p
@@ -70,17 +79,16 @@ let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
(* Symbol i.e identifier /!\ A lot of Pvar are not variables /!\ *)
| Pvar (loc, name) ->
- let idx = get_var_index name ctx in
+ let idx = senv_lookup name ctx in
(* This should be an error but we accept it for debugging *)
if idx < 0 then
lexp_warning tloc ("Variable: '" ^ name ^ "' does not exist");
- (make_var name (idx + 1) loc), ctx;
+ (make_var name (idx) loc), ctx;
(* Let, Variable declaration + local scope *)
| Plet(loc, decls, body) -> (* /!\ HERE *)
let decl, nctx = lexp_parse_let decls (add_scope ctx) in
let bdy, nctx = lexp_parse body nctx in
- (* print_lexp_context nctx; *)
(* Send back old context as we exit the inner scope *)
Let(tloc, decl, bdy), ctx
@@ -110,7 +118,9 @@ let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
(* Function Call *)
| Pcall (fname, _args) ->
+ (* Why function names are pexp ? *)
let fname, ctx = lexp_parse fname ctx in
+
let pargs = pexp_parse_all _args in
let largs, fctx = lexp_parse_all pargs ctx in
@@ -118,15 +128,118 @@ let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
let new_args = List.map (fun g -> (Aexplicit, g)) largs in
Call(fname, new_args), ctx
-
+
+ (* Pinductive *)
+ | Pinductive (label, _, ctors) ->
+ let dummy = (Aexplicit, (dummy_location, "a"), UnknownType(tloc))::[] in
+ let map_ctor, nctx = lexp_parse_constructors ctors ctx in
+ (* We exit current context, return old context *)
+ Inductive(tloc, label, dummy, map_ctor), ctx
+
(* Pcons *)
+ | Pcons(var, sym) -> (* vref, symbol*)
+ let (loc, name) = var in
+ let idx = 0 in
+ Cons(((pvar_to_vdef var), idx), sym), ctx
+
(* Pcase *)
- (* Pinductive *) (* Pinductive Pexp implementation is not ready *)
-
+ | Pcase (loc, target, patterns) ->
+
+ let lxp, ltp = lexp_p_infer target ctx in
+
+ (* Read patterns one by one *)
+ let rec loop ptrns merged dflt =
+ match ptrns with
+ | [] -> merged, dflt
+ | hd::tl ->
+ let (pat, exp) = hd in
+ (* Parse the pattern first then parse the expr *)
+ let (name, iloc, arg) = lexp_read_pattern pat exp lxp in
+ let exp, nctx = lexp_parse exp ctx in
+ if name = "_" then
+ loop tl merged (Some exp)
+ else
+ let merged = SMap.add name (iloc, arg, exp) merged in
+ loop tl merged dflt in
+
+ let (lpattern, dflt) = loop patterns SMap.empty None in
+ Case(loc, lxp, ltp, lpattern, dflt), ctx
+
| _
-> UnknownType(tloc), ctx
+
+(* Read a pattern and create the equivalent representation *)
+and lexp_read_pattern pattern exp target:
+ (string * location * (arg_kind * vdef) option list) =
+
+ match pattern with
+ | Ppatany (loc) -> (* Catch all expression nothing to do *)
+ ("_", loc, [])
+ | Ppatvar (loc, name) -> (* Create a variable containing target *)
+ (*let nctx = add_variable name loc ctx in
+ let idx = get_var_index name nctx in
+ let info = (idx, (loc, name), target, UnknownType(loc)) in
+ let nctx = add_variable_info info nctx in *)
+ (name, loc, [])
+
+ | Ppatcons (ctor_name, args) ->
+ let (loc, name) = ctor_name in
+ (* read pattern args *)
+ let args = lexp_read_pattern_args args in
+ (name, loc, args)
+
+(* Read patterns inside a constructor *)
+and lexp_read_pattern_args args:((arg_kind * vdef) option list) =
+
+ let rec loop args acc =
+ match args with
+ | [] -> (List.rev acc)
+ | hd::tl ->
+ let (_, pat) = hd in
+ match pat with
+ (* Nothing to do *)
+ | Ppatany (loc) -> loop tl (None::acc)
+ | Ppatvar (loc, name) ->
+ (* get kind from the call *)
+ let nacc = (Some (Aexplicit, (loc, name)))::acc in
+ loop tl nacc
+ | _ -> lexp_error dloc "Constructor inside a Constructor";
+
+ in loop args []
+
+(* Parse inductive constructor *)
+and lexp_parse_constructors ctors ctx =
+
+ let make_args (args:(arg_kind * pvar option * pexp) list):
+ (arg_kind * ltype) list * lexp_context =
+ let rec loop args acc ctx =
+ match args with
+ | [] -> (List.rev acc), ctx
+ | hd::tl -> begin
+ match hd with
+ (* What does the optional Pvar do ?
+ that expression does not exist in LEXP*)
+ | (kind, _, exp) ->
+ let lxp, nctx = lexp_parse exp ctx in
+ loop tl ((kind, lxp)::acc) nctx end in
+ loop args [] ctx in
+
+ let rec loop ctors merged ctx =
+ match ctors with
+ | [] -> merged, ctx
+ | hd::tl -> begin
+ match hd with
+ | ((loc, name), args) ->
+ let largs, nctx = make_args args in
+ let nmerged = SMap.add name largs merged in
+ (loop tl nmerged ctx)
+ end in
+
+ loop ctors SMap.empty ctx
+
+(* Parse let declaration *)
and lexp_parse_let decls ctx =
(* Merge Type info and declaration together *)
@@ -177,7 +290,7 @@ and lexp_parse_let decls ctx =
(* Warning will be printed later *)
| ((loc, name), None, _) -> add_var_env tl ctx
| ((loc, name), _, _) ->
- let ctx = add_variable name loc ctx in
+ let ctx = senv_add_var name loc ctx in
add_var_env tl ctx end in
let nctx = add_var_env decls ctx in
@@ -192,12 +305,16 @@ and lexp_parse_let decls ctx =
let linst, nctx = lexp_parse pinst ctx in
let ltyp, nctx = lexp_parse ptype nctx in
let nacc = ((loc, name), linst, ltyp)::acc in
+ let nctx =
+ env_add_var_info (0, (loc, name), linst, ltyp) nctx in
(parse_decls tl nctx nacc)
| ((loc, name), Some pinst, None) ->
let linst, nctx = lexp_parse pinst ctx in
(* This is where UnknownType are introduced *)
(* need Inference HERE *)
let nacc = ((loc, name), linst, UnknownType(loc))::acc in
+ let nctx =
+ env_add_var_info (0, (loc, name), linst, UnknownType(loc)) nctx in
(parse_decls tl nctx nacc)
(* Skip the variable *)
| ((loc, name), None, _) ->
@@ -215,13 +332,42 @@ and lexp_parse_all (p: pexp list) (ctx: lexp_context):
| _ -> let lxp, new_ctx = lexp_parse (List.hd plst) ctx in
(loop (List.tl plst) new_ctx (lxp::acc)) in
(loop p ctx [])
-;;
-(* Print back in CET (Close Enough Typer) easier to read *)
- (* pretty ? * indent level * print_type? *)
-type print_context = (bool * int * bool)
+(*
+ * Type Inference
+ * --------------------- *)
+(* Parsing a Pexp into an Lexp is really "elaboration", i.e. it needs to
+ * infer the types and perform macro-expansion. For won't really
+ * do any of that, but we can already start structuring it accordingly.
+ *
+ * More specifically, we do it with 2 mutually recursive functions:
+ * one takes a Pexp along with its expected type and return an Lexp
+ * of that type (hopefully), whereas the other takes a Pexp and
+ * infers its type (which it returns along with the Lexp).
+ * This is the idea of "bidirectional type checking", which minimizes
+ * the amount of "guessing" and/or annotations. Basically guessing/annotations
+ * is only needed at those few places where the code is not fully-normalized,
+ * which in normal programs is only in "let" definitions.
+ * So the rule of thumbs are:
+ * - use lexp_p_infer for destructors, and use lexp_p_check for constructors.
+ * - use lexp_p_check whenever you can.
+ *)
-let rec lexp_print_adv opt exp =
+and lexp_p_infer (p : pexp) (env : lexp_context) : lexp * ltype =
+ let lxp, nctx = lexp_parse p env in
+ lxp, UnknownType(dummy_location)
+
+and lexp_p_check (env : lexp_context) (p : pexp) (t : ltype) : lexp =
+ match p with
+ | _
+ -> let (e, inferred_t) = lexp_p_infer p env in
+ (* FIXME: check that inferred_t = t! *)
+ e
+(*
+ * Printing
+ * --------------------- *)
+(* So print can be called while parsing *)
+and lexp_print_adv opt exp =
let slexp_print = lexp_print_adv opt in (* short_lexp_print *)
let (pty, indent, prtp) = opt in
match exp with
@@ -247,6 +393,11 @@ let rec lexp_print_adv opt exp =
print_string "lambda ("; print_string (name ^ ": ");
slexp_print ltype; print_string ") -> "; slexp_print lbody;
+ | Cons(vf, symbol) ->
+ let (loc, name) = symbol in
+ let ((loc, vname), idx) = vf in
+ print_string (name ^ "("); print_string (vname ^ ")");
+
| Call(fname, args) -> begin (* /!\ Partial Print *)
(* get function name *)
let str = match fname with
@@ -272,10 +423,50 @@ let rec lexp_print_adv opt exp =
List.iter (fun arg -> print_string " "; print_arg arg) args;
print_string ")" end
+ | Inductive (_, (_, name), _, ctors) ->
+ print_string ("inductive_ " ^ name ^ " ");
+ lexp_print_ctors opt ctors;
+
+ | Case (_, target, tpe, map, dflt) -> begin
+ print_string "case "; slexp_print target;
+ print_string ": "; slexp_print tpe;
+
+ if pty then print_string "\n";
+
+ let print_arg arg =
+ List.iter (fun v ->
+ match v with
+ | None -> print_string " _"
+ | Some (kind, (l, n)) -> print_string (" " ^ n)) arg in
+
+ SMap.iter (fun key (loc, arg, exp) ->
+ make_line " " (indent * 4);
+ print_string ("| " ^ key); print_arg arg;
+ print_string " -> ";
+ slexp_print exp; print_string "; ";
+ if pty then print_string "\n";)
+ map;
+
+ match dflt with
+ | None -> ()
+ | Some df ->
+ make_line " " (indent * 4);
+ print_string "| _ -> "; slexp_print df;
+ print_string ";"; if pty then print_string "\n"; end
+
(* debug catch all *)
| UnknownType (loc) -> print_string "unkwn";
- | _ -> print_string "expr"
-
+ | _ -> print_string "Printint Not Implemented"
+
+
+and lexp_print_ctors opt ctors =
+ SMap.iter (fun key value ->
+ print_string ("(" ^ key ^ ": ");
+ List.iter (fun (kind, arg) ->
+ lexp_print_adv opt arg; print_string " ") value;
+ print_string ")")
+ ctors
+
and lexp_print_decls opt decls =
let (pty, indent, prtp) = opt in
let print_type nm tp =
=====================================
tests/debug.ml
=====================================
--- a/tests/debug.ml
+++ b/tests/debug.ml
@@ -147,20 +147,25 @@ let debug_pexp_print_all pexps =
(* Print lexp with debug info *)
let debug_lexp_print lxp =
print_string " ";
- let print_info msg loc expr=
+ let dloc = dummy_location in
+ let print_info msg loc lex =
print_string msg; print_string "[";
print_loc loc;
print_string "]\t";
- lexp_print lxp in
+ lexp_print lex in
+ let tloc = lexp_location lxp in
match lxp with
- | Var((loc, _), _) -> print_info "Var " loc lxp
- | Imm(s) -> print_info "Imm " dummy_location lxp
- | Let(loc, _, _) -> print_info "Let " loc lxp
- | Arrow(_, _, _, loc, _) -> print_info "Arrow " loc lxp
- | Lambda(_, (loc, _), _, _) -> print_info "Lambda " loc lxp
- | Call(_, _) -> print_info "Call " dummy_location lxp
- | UnknownType(loc) -> print_info "UnknownType " loc lxp
- | _ -> print_string "Nothing";
+ | Var((loc, _), _) -> print_info "Var " tloc lxp
+ | Imm(s) -> print_info "Imm " tloc lxp
+ | Let(loc, _, _) -> print_info "Let " tloc lxp
+ | Arrow(_, _, _, loc, _) -> print_info "Arrow " tloc lxp
+ | Lambda(_, (loc, _), _, _) -> print_info "Lambda " tloc lxp
+ | Call(_, _) -> print_info "Call " tloc lxp
+ | Inductive(loc, _, _, _) -> print_info "Inductive " tloc lxp
+ | UnknownType(loc) -> print_info "UnknownType " tloc lxp
+ | Case(loc, _, _, _, _) -> print_info "Case " tloc lxp
+ | Cons (rf, sym) -> print_info "Cons " tloc lxp
+ | _ -> print_string "Debug Printing Not Implemented";
;;
(* Print a list of lexp *)
=====================================
tests/full_debug.ml
=====================================
--- a/tests/full_debug.ml
+++ b/tests/full_debug.ml
@@ -38,8 +38,26 @@ open Grammar
open Pexp
open Debruijn
open Lparse
+open Myers
+open Eval
+(* pexp and lexp can be done together, one by one *)
+let pexp_lexp_one node ctx =
+ let pxp = pexp_parse node in
+ lexp_parse pxp ctx
+;;
+
+let pexp_lexp_all nodes ctx =
+ let rec loop nodes ctx acc =
+ match nodes with
+ | [] -> ((List.rev acc), ctx)
+ | hd::tl ->
+ let lxp, new_ctx = pexp_lexp_one hd ctx in
+ (loop tl new_ctx (lxp::acc)) in
+ (loop nodes ctx [])
+;;
+
let main () =
let arg_n = Array.length Sys.argv in
@@ -71,7 +89,7 @@ let main () =
(* get node sexp *)
let nodes = sexp_parse_all_to_list default_grammar toks (Some ";") in
-
+
(* get pexp *)
let pexps = pexp_parse_all nodes in
@@ -87,7 +105,12 @@ let main () =
print_title "Lexp"; debug_lexp_print_all lexps;
(* Eval Each Expression *)
+ print_title "Eval Print";
+ (* Eval One *)
+ let rctx = make_runtime_ctx in
+ let c, rctx = eval (List.hd lexps) rctx in
+ print_eval_result c
end
;;
View it on GitLab: https://gitlab.com/monnier/typer/compare/62596a778dd66f8c2784fa876c444ff83d…
4
9
Setepenre pushed to branch master at Stefan / Typer
Commits:
36520963 by Pierre Delaunay at 2016-03-04T20:31:09-05:00
prelex_string hack
- - - - -
e8c42357 by Pierre Delaunay at 2016-03-04T23:44:41-05:00
call + lambda eval
- - - - -
b3a7eafb by Pierre Delaunay at 2016-03-06T13:13:10-05:00
simple repl for interactive testing
- - - - -
cd150174 by Pierre Delaunay at 2016-03-06T15:06:10-05:00
fix inductive pexp parsing
- - - - -
bbeff6f8 by Pierre Delaunay at 2016-03-06T16:47:12-05:00
eval case
- - - - -
c6d73fd5 by Pierre Delaunay at 2016-03-06T21:16:28-05:00
env_info fix
- - - - -
15 changed files:
- .gitignore
- GNUmakefile
- + samples/case.typer
- + samples/functions.typer
- + samples/inductives.typer
- + samples/let.typer
- samples/lexp_test.typer
- src/debruijn.ml
- src/eval.ml
- src/lexer.ml
- src/lparse.ml
- src/pexp.ml
- src/prelexer.ml
- + tests/REPL.ml
- tests/full_debug.ml
Changes:
=====================================
.gitignore
=====================================
--- a/.gitignore
+++ b/.gitignore
@@ -16,3 +16,4 @@ manual.??
*~
#*#
test__.ml
+_temp_hack
=====================================
GNUmakefile
=====================================
--- a/GNUmakefile
+++ b/GNUmakefile
@@ -1,21 +1,27 @@
RM=rm -f
TEST_FILES := $(wildcard ./tests/*_test.ml)
-# This is for windows: Make windows version is old
+# This is for windows: windows version is old
ifeq ($(OS),Windows_NT)
SHELL=C:/Windows/System32/cmd.exe
endif
-all: typer debug tests
+all: ityper typer debug tests
typer:
ocamlbuild src/main.byte -cflag -rectypes
mv _build/src/main.byte _build/typer # move and rename executable
+# debug file eval
debug:
ocamlbuild tests/full_debug.native -I src -cflag -rectypes
mv _build/tests/full_debug.native _build/full_debug
+# interactive typer
+ityper:
+ ocamlbuild tests/REPL.native -I src -cflag -rectypes
+ mv _build/tests/REPL.native _build/ityper
+
tests:
# Build tests
$(foreach test, $(TEST_FILES), ocamlbuild $(subst ./,,$(subst .ml,.native,$(test))) -I src -cflag -rectypes;)
@@ -29,9 +35,10 @@ doc-tex:
texi2pdf ./doc/manual.texi --pdf --build=clean
# Make implementation doc
-doc-ocaml:
- ocamldoc
+#doc-ocaml:
+# ocamldoc
+.PHONY: ityper
.PHONY: typer
.PHONY: debug
.PHONY: tests
=====================================
samples/case.typer
=====================================
--- /dev/null
+++ b/samples/case.typer
@@ -0,0 +1,39 @@
+% -------------------------------------------
+% Inductive type
+% -------------------------------------------
+
+% definition
+inductive_ (dummy_Nat) (zero) (succ Nat);
+
+% declaration
+% Nat : Type; % This line is not parsed
+Nat = inductive_ (dummy_Nat) (zero) (succ Nat); % zero is not parsed
+
+% only inductive-cons is available
+inductive-cons Nat succ;
+
+% Usage
+zero = inductive-cons Nat zero; % those are aliases
+succ = inductive-cons Nat succ;
+
+one = (succ (zero));
+
+% Case test
+% x = (succ zero);
+x = (succ (succ zero));
+
+% Simple
+case x
+ | zero => 0
+ | succ y => y
+ | _ => (2 + 4);
+
+% recursive
+tonum = lambda x -> case x
+ | zero => 0
+ | (succ y) => (1 + (tonum y));
+
+(tonum x);
+
+
+
\ No newline at end of file
=====================================
samples/functions.typer
=====================================
--- /dev/null
+++ b/samples/functions.typer
@@ -0,0 +1,32 @@
+% -------------------------------------------
+% Function Calls
+% -------------------------------------------
+
+% define sqrt
+sqrt = lambda (x : Nat) -> x * x;
+
+(sqrt 2);
+
+% define cube
+cube = lambda (x : Nat) -> x * (sqrt x);
+
+(cube 3);
+
+% explicit
+mult = lambda (x : Nat) -> lambda (y : Nat) -> (y * x);
+
+(mult 2 3);
+
+% Not Working
+% ---------------------
+
+% implicit (Type annotation introduce a bug)
+% cube = lambda x y -> (x * y);
+
+
+% partial application
+partial_mul = (mult 2);
+
+(partial_mul 3);
+
+"FUNCTION END";
\ No newline at end of file
=====================================
samples/inductives.typer
=====================================
--- /dev/null
+++ b/samples/inductives.typer
@@ -0,0 +1,23 @@
+% -------------------------------------------
+% Inductive type
+% -------------------------------------------
+
+% definition
+inductive_ (dummy_Nat) (zero) (succ Nat);
+
+
+% declaration
+% Nat : Type; % This line is not parsed
+Nat = inductive_ (dummy_Nat) (zero) (succ Nat); % zero is not parsed
+
+
+% only inductive-cons is available
+inductive-cons Nat succ;
+
+% Usage
+zero = inductive-cons Nat zero; % those are aliases
+succ = inductive-cons Nat succ;
+
+one = (succ (zero));
+one = (succ (zero));
+one = (succ (zero));
\ No newline at end of file
=====================================
samples/let.typer
=====================================
--- /dev/null
+++ b/samples/let.typer
@@ -0,0 +1,23 @@
+% -------------------------------------------
+% Let
+% -------------------------------------------
+
+
+let c = 1; a = 5; b = 10; d = 3; in
+ a + b;
+
+
+a = 1;
+b = 2;
+c = 3;
+d = 4;
+
+
+let a = 3; g = 1; e = 1; f = 3; in
+ e + a + f + d;
+
+
+% Not Implemented
+% ----------------------
+
+% Recursive Let
=====================================
samples/lexp_test.typer
=====================================
--- a/samples/lexp_test.typer
+++ b/samples/lexp_test.typer
@@ -1,47 +1,10 @@
-% Eval test
-let c = 1; a = 5; b = 10; d = 3; in
- a + b;
-
-% -------------------------------------------
-% Function Calls
-% -------------------------------------------
-
-% define sqrt
-sqrt = lambda (x : Nat) -> x * x;
-
-% define cube
-cube = lambda (x : Nat) -> x * (sqrt x);
-
-% explicit
-mult = lambda (x : Nat) -> lambda (y : Nat) -> (y * x);
-
-% implicit (Type annotation introduce a bug)
-cube = lambda x y -> (x * y);
-% -------------------------------------------
-% Inductive type
-% -------------------------------------------
-
-inductive_ (dummy_Nat) (zero) (succ Nat);
-
-% Usage
-Nat : Type % This line is not parsed
-Nat = inductive_ (dummy_Nat) (zero) (succ Nat); % zero is not parsed
-
% Constructor
% -------------------------------------------
-% only inductive-cons is available
-
-inductive-cons Nat succ;
-
-% Usage
-zero = inductive-cons Nat zero; % those are aliases
-succ = inductive-cons Nat succ;
-one = (succ (zero));
% -------------------------------------------
% Cases
=====================================
src/debruijn.ml
=====================================
--- a/src/debruijn.ml
+++ b/src/debruijn.ml
@@ -113,10 +113,8 @@ let senv_add_var name loc ctx =
(* *)
let env_add_var_info var (ctx: lexp_context) =
- let (a, _) = ctx in
- (* let (rof, (loc, name), value, ltyp) = var in *)
- let nenv = _add_var_env var ctx in
- (a, nenv)
+ let (a, env) = ctx in
+ (a, cons var env)
;;
let env_lookup_type_by_index index ctx =
=====================================
src/eval.ml
=====================================
--- a/src/eval.ml
+++ b/src/eval.ml
@@ -36,29 +36,39 @@ open Lparse
open Myers
open Sexp
open Fmt
+open Grammar
-let eval_error loc msg =
- msg_error "EVAL" loc msg;
+let _eval_error loc msg =
+ msg_error "_eval" loc msg;
raise (internal_error msg)
;;
let dloc = dummy_location
-let eval_warning = msg_warning "EVAL"
+let _eval_warning = msg_warning "_eval"
let print_myers_list l print_fun =
let n = (length l) in
- print_string "-------------------\n";
- print_string " Environement: \n";
- print_string "-------------------\n";
+ let title = " EVAL ENVIRONMENT " in
+ let title_n = String.length title in
+ let sep_n = (80 - title_n - 4) / 2 in
+ let sep_t = 80 - 4 in
+ let psep = (make_line '=' sep_n) in
+ let fsep = (make_line '=' sep_t) in
+ let sep = " " ^ fsep ^ "\n" in
+
+ print_string (" " ^ psep ^ title ^ psep ^ "\n");
+ print_string " | INDEX | VARIABLE NAME | VALUE \n";
+ print_string (" " ^ (make_line '-' sep_t) ^ "\n");
for i = 0 to n - 1 do
- ralign_print_int (i + 1) 4;
- print_string ") ";
+ print_string " | ";
+ ralign_print_int i 5;
+ print_string " | ";
print_fun (nth i l);
done;
- print_string "-------------------\n";
+ print_string sep;
;;
let get_function_name fname =
@@ -74,17 +84,23 @@ let get_int lxp =
;;
(* Runtime Environ *)
-type runtime_env = lexp myers
+type runtime_env = (string option * lexp) myers
let make_runtime_ctx = nil;;
-let add_rte_variable x l = (cons x l);;
-let get_rte_variable idx l = (nth (idx) l);;
+let add_rte_variable name x l = (cons (name, x) l);;
+
+let get_rte_variable idx l = let (_, x) = (nth (idx) l) in x;;
let print_rte_ctx l = print_myers_list l
- (fun g -> lexp_print g; print_string "\n")
+ (fun (n, g) ->
+ let _ =
+ match n with
+ | Some m -> lalign_print_string m 12; print_string " | "
+ | None -> print_string (make_line ' ' 12); print_string " | " in
+ lexp_print g; print_string "\n")
;;
-(* Evaluation reduce an expression x to an Lexp.Imm *)
-let rec eval lxp ctx: (lexp * runtime_env) =
+(* _evaluation reduce an expression x to an Lexp.Imm *)
+let rec _eval lxp ctx: (lexp * runtime_env) =
match lxp with
(* This is already a leaf *)
@@ -102,80 +118,201 @@ let rec eval lxp ctx: (lexp * runtime_env) =
(* this works for non recursive let *)
| Let(_, decls, inst) -> begin
- (* First we evaluate all declaration then we evaluate the instruction *)
+ (* First we _evaluate all declaration then we eval the instruction *)
+
let nctx = build_ctx decls ctx in
- let value, nctx = eval inst nctx in
+
+ (*
+ print_rte_ctx ctx;
+ print_rte_ctx nctx; *)
+
+ let value, nctx = _eval inst nctx in
(* return old context as we exit let's scope*)
value, ctx end
(* Function call *)
- | Call (lname, args) ->
- (* Try to extract name *)(*
- let tname = match lname with
- | Var((loc, name), _) -> name
- | _ -> lexp_print lname; eval_error "Incorrect Function Name" in
-
- (* Save declaration in environment *)
- let n = List.length args in
- if tname = "_=_" && n == 2 then
- let (((_, name), _), expr) = args in
- let nctx = add_rte_variable *)
-
-
- (* Add args in the scope *)
- print_rte_ctx ctx;
- let nctx = build_arg_list args ctx in
- print_rte_ctx nctx;
-
- (* We need to seek out the function declaration and eval the body *)
- (* but currently we cannot declare functions so I hardcoded + *)
- (* let bdy = get_body fname in
- eval bdy nctx *)
-
- (* fname is currently a var *)
- let name = get_function_name lname in
- (* Hardcoded function for now *)
- if name = "_+_" then begin
+ | Call (lname, args) -> (
+ (* Try to extract name *)
+ match lname with
+ (* Function declaration *)
+ | Var((loc, name), _) when name = "_=_" ->
+ (* Save declaration in environment *)
+ let (vr, body) = match args with
+ | [(_, a); (_, b)] -> a, b
+ | _ -> _eval_error loc "Wrong number of Args" in
+
+ let vname = get_function_name vr in
+ let nctx = add_rte_variable (Some vname) body ctx in
+ body, nctx
- (* Get the two args *)
+ (* Hardcoded functions *)
+ | Var((_, name), _) when name = "_+_" ->
+ let nctx = build_arg_list args ctx in
let l = get_int (get_rte_variable 0 nctx) in
let r = get_int (get_rte_variable 1 nctx) in
+ Imm(Integer(dloc, l + r)), ctx
- (*print_int l; print_string " ";
- print_int r; print_string "\n"; *)
+ | Var((_, name), _) when name = "_*_" ->
+ let nctx = build_arg_list args ctx in
+ let l = get_int (get_rte_variable 0 nctx) in
+ let r = get_int (get_rte_variable 1 nctx) in
+ Imm(Integer(dloc, l * r)), ctx
+
+ (* This is a named function call *)
+ (* TODO: handle partial application *)
+ | Var((_, _), idx) when idx >= 0 ->
+ (* get function body *)
+ let body = get_rte_variable idx ctx in
+ (* Add args in the scope *)
+ let nctx = build_arg_list args ctx in
+ let e, nctx = (_eval body nctx) in
+ (* we exit function and send back old ctx *)
+ e, ctx
+
+ (* TODO Everything else *)
+ (* Which includes a call to a lambda *)
+ | _ -> Imm(String(dloc, "Funct Not Implemented")), ctx)
+
+ | Lambda(_, vr, _, body) -> begin
+ let (loc, name) = vr in
+ let value = (get_rte_variable 0 ctx) in
+ let nctx = add_rte_variable (Some name) value ctx in
+
+ let rec build_body bd idx nctx =
+ match bd with
+ | Lambda(_, vr, _, body) ->
+ let (loc, name) = vr in
+ (* Get Variable from call context *)
+ let value = (get_rte_variable idx ctx) in
+ (* Build lambda context *)
+ let nctx = add_rte_variable (Some name) value nctx in
+ (build_body body (idx + 1) nctx)
+ | _ -> bd, nctx in
- Imm(Integer(dummy_location, l + r)), ctx end
+ let body, nctx = build_body body 1 nctx in
+
+ let e, nctx = _eval body nctx in
+ e, ctx end
+
+ (* Inductive is a type declaration. We have nothing to eval *)
+ | Inductive (_, _, _, _) as e -> e, ctx
+
+ (* inductive-cons build a type too? *)
+ | Cons (_, _) as e -> e, ctx
+
+ (* Case *)
+ | Case (loc, target, _, pat, dflt) -> begin
+
+ (* Eval target *)
+ let v, nctx = _eval target ctx in
+
+ (* V must be a constructor Call *)
+ let ctor_name, args = match v with
+ | Call(lname, args) -> (match lname with
+ | Var((_, ctor_name), _) -> ctor_name, args
+ | _ -> _eval_error loc "Target is not a Constructor" )
+ (*
+ | Cons((_, idx), (_, cname)) -> begin
+ (* retrieve type definition *)
+ let info = get_rte_variable idx ctx in
+ let Inductive(_, _, _, ctor_def) = info in
+ try let args = SMap.find cname ctor_def in
+ cname, args
+ with
+ Not_found ->
+ _eval_error loc "Constructor does not exist" end *)
+
+ | _ -> lexp_print target;
+ _eval_error loc "Can't match expression" in
+
+ (* Check if a default is present *)
+ let run_default df =
+ match df with
+ | None -> Imm(String(loc, "Match Failure")), ctx
+ | Some lxp -> _eval lxp ctx in
+
+ let ctor_n = List.length args in
+
+ (* Build a filter option *)
+ let is_true key value =
+ let (_, pat_args, _) = value in
+ let pat_n = List.length pat_args in
+ if pat_n = ctor_n && ctor_name = key then
+ true
+ else
+ false in
+
+ (* Search for the working pattern *)
+ let sol = SMap.filter is_true pat in
+ if SMap.is_empty sol then
+ run_default dflt
else
- Imm(String(dummy_location, "Funct Not Implemented")), ctx
-
- | _ -> Imm(String(dummy_location, "Eval Not Implemented")), ctx
+ (* Get working pattern *)
+ let key, (_, pat_args, exp) = SMap.min_binding sol in
+
+ (* build context *)
+ let nctx = List.fold_left2 (fun nctx pat cl ->
+ match pat with
+ | None -> nctx
+ | Some (_, (_, name)) -> let (_, xp) = cl in
+ add_rte_variable (Some name) xp nctx)
+
+ nctx pat_args args in
+
+ let r, nctx = _eval exp nctx in
+ (* return old context as we exist the case *)
+ r, ctx end
+
+ | _ -> Imm(String(dloc, "eval Not Implemented")), ctx
and build_arg_list args ctx =
- (* Eval every args *)
- let arg_val = List.map (fun (k, e) -> let (v, c) = eval e ctx in v) args in
+ (* _eval every args *)
+ let arg_val = List.map (fun (k, e) -> let (v, c) = _eval e ctx in v) args in
(* Add args inside context *)
- List.fold_left (fun c v -> add_rte_variable v c) ctx arg_val
+ List.fold_left (fun c v -> add_rte_variable None v c) ctx arg_val
and build_ctx decls ctx =
match decls with
| [] -> ctx
| hd::tl ->
let (v, exp, tp) = hd in
- let (value, nctx) = eval exp ctx in
- let nctx = add_rte_variable value nctx in
+ let (value, nctx) = _eval exp ctx in
+ let nctx = add_rte_variable None value nctx in
build_ctx tl nctx
;;
-let print_eval_result lxp =
- print_string " >> ";
+let eval lxp ctx =
+ try
+ _eval lxp ctx
+ with
+ e -> print_rte_ctx ctx;
+ Imm(String(dloc, "Evaluation Failed")), ctx
+;;
+
+let print_eval_result i lxp =
+ print_string " Out[";
+ ralign_print_int i 2;
+ print_string "] >> ";
match lxp with
| Imm(v) -> sexp_print v; print_string "\n"
- | _ -> print_string "Evaluation Failed\n"
+ | e -> lexp_print e; print_string "\n"
;;
let evalprint lxp ctx =
let v, ctx = (eval lxp ctx) in
- print_eval_result v;
+ print_eval_result 0 v;
ctx
;;
+(*
+let eval_string (str: string) tenv grm limit lxp_ctx rctx =
+ let pretoks = prelex_string str in
+ let toks = lex tenv pretoks in
+ let sxps = sexp_parse_all_to_list grm toks limit in
+ let pxps = pexp_parse_all sxps in
+ let lxp, lxp_ctx = lexp_parse_all pxps lxp_ctx in
+ (eval lxp rctx), lxp_ctx
+;;
+
+*)
+
=====================================
src/lexer.ml
=====================================
--- a/src/lexer.ml
+++ b/src/lexer.ml
@@ -117,4 +117,16 @@ let lex tenv (pts : pretoken list) : sexp list =
| _ -> let (tok, pts, bpos, cpos) = nexttoken tenv pts bpos cpos
in gettokens pts bpos cpos (tok :: acc) in
gettokens pts 0 0 []
+;;
+
+let lex_string (str: string) tenv =
+ let pretoks = prelex_string str in
+ lex tenv pretoks
+;;
+
+let node_parse_string (str: string) tenv grm limit =
+ let pretoks = prelex_string str in
+ let toks = lex tenv pretoks in
+ sexp_parse_all_to_list grm toks limit
+;;
=====================================
src/lparse.ml
=====================================
--- a/src/lparse.ml
+++ b/src/lparse.ml
@@ -38,6 +38,9 @@ open Grammar
open Debruijn
open Fmt
+open Lexer
+open Prelexer
+
(* Shortcut => Create a Var *)
let make_var name index loc =
Var(((loc, name), index))
@@ -47,6 +50,8 @@ let not_implemented_error () =
internal_error "not implemented"
;;
+let dlxp = UnknownType(dloc)
+let dltype = UnknownType(dloc)
let dloc = dummy_location
let lexp_warning = msg_warning "LEXP"
@@ -64,11 +69,32 @@ type print_context = (bool * int * bool)
let pvar_to_vdef p =
p
;;
+
+(*
+let _ab = senv_add_var;;
+let senv_add_var =
+ _ab name loc ctx
+;;*)
+
(* PEXP is not giving SEXP types this is why types are always unknown *)
(*
* The main job of lexp (currently) is to determine variable name (index)
* and to regroup type specification with their variable
+ *
+ * lexp_context is composed of two environment: senv and env.
+ * the senv environment is used to find the correct debruijn index
+ * while the env environment is used to save variable information.
+ * the env environment look a lot like the runtime environment that will be
+ * used in the eval section.
+ *
+ * While most of the time senv and env will be synchronised it is
+ * possible for env to hold more variables than senv since senv is a map
+ * which does not allow multiple definition while env does.
+ *
+ * a = 1;
+ * let a = 3; b = 5 in a + b;
+ *
*)
let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
@@ -88,13 +114,14 @@ let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
with Not_found ->
(* Add Variable *)
let ctx = senv_add_var name loc ctx in
- (make_var name 0 loc), ctx; end
+ let ctx = env_add_var_info (0, (loc, name), dlxp, dlxp) ctx in
+ (make_var name 0 loc), ctx; end
(* Let, Variable declaration + local scope *)
| Plet(loc, decls, body) ->
let decl, nctx = lexp_parse_let decls ctx in
- lexp_context_print nctx;
- let bdy, nctx = lexp_parse body nctx in
+ (* Body cannot modify context *)
+ let bdy, _ = lexp_parse body nctx in
(* Send back old context as we exit the inner scope *)
Let(tloc, decl, bdy), ctx
@@ -112,79 +139,66 @@ let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
(* *)
| Plambda (kind, var, Some ptype, body) ->
- let nvar = pvar_to_vdef var in (* /!\ HERE *)
- let ltyp, ctx = lexp_parse ptype ctx in
- let lbody, ctx = lexp_parse body ctx in
- Lambda(kind, nvar, ltyp, lbody), ctx
+ (* Add argument to context *)
+ let (loc, vname) = var in
+ let nctx = senv_add_var vname loc ctx in
+ let ltp, nctx = lexp_parse ptype nctx in (* Get Type *)
+ let nctx = env_add_var_info (0, (loc, vname), dlxp, ltp) nctx in
+
+ let ltyp, nctx = lexp_parse ptype nctx in
+ let lbody, nctx = lexp_parse body nctx in
+
+ (* Return old context as we exit lambda scope*)
+ Lambda(kind, var, ltyp, lbody), ctx
| Plambda (kind, var, None, body) ->
- let nvar = pvar_to_vdef var in (* /!\ HERE *)(* /!\ Missing Type *)
- let lbody, ctx = lexp_parse body ctx in
- Lambda(kind, nvar, UnknownType(tloc), lbody), ctx
+ let (loc, vname) = var in
+ let nctx = senv_add_var vname loc ctx in
+ let nctx = env_add_var_info (0, (loc, vname), dlxp, dltype) nctx in
+
+ let lbody, ctx = lexp_parse body nctx in
+ Lambda(kind, var, UnknownType(tloc), lbody), ctx
| Pcall (fname, _args) ->
- (* Process Arguments *)
- let pargs = pexp_parse_all _args in
- let largs, fctx = lexp_parse_all pargs ctx in
- (* Make everything explicit for now *)
- let new_args = List.map (fun g -> (Aexplicit, g)) largs in
-
- (* Call to named function which must have been defined earlier *
- * i.e they must be in the context *)
- begin try begin
- (* Get function name *)
- let name, loc = match fname with
- | Pvar(loc, nm) -> nm, loc
- | Pcons (_, (loc, nm)) -> nm, loc
- | _ -> raise Not_found in
-
- try
- (* Check if the function was defined *)
- let idx = senv_lookup name ctx in
- let vf = (make_var name idx loc) in
- Call(vf, new_args), ctx
-
- with Not_found ->
- (* Don't stop even if an error was found *)
- lexp_error loc ("The function \"" ^ name ^
- "\" was not defined");
- let vf = (make_var name (-1) loc) in
- Call(vf, new_args), ctx end
-
- (* Call to a nameless function *)
- with Not_found ->
- (* I think this should not modify context.
- * if so, funny things might happen when evaluating *)
- let fname, ctx = lexp_parse fname ctx in
- Call(fname, new_args), ctx end
+ lexp_call fname _args ctx
(* Pinductive *)
- | Pinductive (label, _, ctors) ->
- let dummy = (Aexplicit, (dummy_location, "a"), UnknownType(tloc))::[] in
+ | Pinductive (label, [], ctors) ->
let map_ctor, nctx = lexp_parse_constructors ctors ctx in
- (* We exit current context, return old context *)
- Inductive(tloc, label, dummy, map_ctor), ctx
+ Inductive(tloc, label, [], map_ctor), nctx
(* Pcons *)
- | Pcons(var, sym) -> (* vref, symbol*)
- let (loc, name) = var in
- let idx = 0 in
- Cons(((pvar_to_vdef var), idx), sym), ctx
+ | Pcons(vr, sym) -> (
+ let (loc, type_name) = vr in
+ let (_, ctor_name) = sym in
+
+ (* An inductive type named type_name must be in the environment *)
+ try let idx = senv_lookup type_name ctx in
+ (* Check if the constructor exists *)
+ (* TODO *)
+ Cons((vr, idx), sym), ctx
+ with Not_found ->
+ lexp_error loc
+ ("The inductive type: " ^ type_name ^ " was not declared");
+ Cons((vr, -1), sym), ctx)
(* Pcase *)
| Pcase (loc, target, patterns) ->
- let lxp, ltp = lexp_p_infer target ctx in
-
+ let lxp, nctx = lexp_parse target ctx in
+ let ltp = UnknownType(loc) in
+
(* Read patterns one by one *)
let rec loop ptrns merged dflt =
match ptrns with
| [] -> merged, dflt
| hd::tl ->
let (pat, exp) = hd in
- (* Parse the pattern first then parse the expr *)
- let (name, iloc, arg) = lexp_read_pattern pat exp lxp in
- let exp, nctx = lexp_parse exp ctx in
+ (* Create pattern context *)
+ let (name, iloc, arg), nctx = lexp_read_pattern pat exp lxp nctx in
+ (* parse using pattern context *)
+ let exp, nctx = lexp_parse exp nctx in
+
if name = "_" then
loop tl merged (Some exp)
else
@@ -192,53 +206,123 @@ let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
loop tl merged dflt in
let (lpattern, dflt) = loop patterns SMap.empty None in
+ (* Exit case, send back old context *)
Case(loc, lxp, ltp, lpattern, dflt), ctx
| _
-> UnknownType(tloc), ctx
+
+(* Identify Call Type and return processed call *)
+and lexp_call fname _args ctx =
+ (* Process Arguments *)
+ let pargs = pexp_parse_all _args in
+
+ (* Call to named function which must have been defined earlier *
+ * i.e they must be in the context *)
+ begin try begin
+ (* Get function name *)
+ let name, loc = match fname with
+ | Pvar(loc, nm) -> nm, loc
+ | Pcons (_, (loc, nm)) -> nm, loc
+ | _ -> raise Not_found in
+
+ (* _=_ is a special function *) (**)
+ let n = List.length pargs in
+ if name = "_=_" && n = 2 then(
+ let (var, inst) = match pargs with
+ | [a; b] -> a, b
+ (* This was added to remove a warning but will never be true *)
+ | _ -> lexp_fatal loc "Wrong Number of Args" in
+
+ let vname = match var with Pvar(loc, name) -> name
+ | e -> pexp_print var; "str" in
+
+ (* we should add the defined var to ctx *)
+ let nctx = senv_add_var vname loc ctx in
+
+ let idx = senv_lookup vname nctx in
+ let lxp, ltyp = lexp_p_infer inst nctx in
+
+ (* Add Var info*)
+ let nctx = env_add_var_info (0, (loc, vname), lxp, ltyp) nctx in
+
+ (* _=_ is the only function with -2 index *)
+ let vf = (make_var "_=_" (-2) loc) in
+ let vr = (make_var vname idx loc) in
+
+ Call(vf, [(Aexplicit, vr); (Aexplicit, lxp)]), nctx)
+ else(**)
+ let largs, fctx = lexp_parse_all pargs ctx in
+ let new_args = List.map (fun g -> (Aexplicit, g)) largs in
+ try
+ (* Check if the function was defined *)
+ let idx = senv_lookup name ctx in
+ let vf = (make_var name idx loc) in
+
+ Call(vf, new_args), ctx
+
+ with Not_found ->
+ (* Don't stop even if an error was found *)
+ lexp_error loc ("The function \"" ^ name ^
+ "\" was not defined");
+ let vf = (make_var name (-1) loc) in
+ Call(vf, new_args), ctx end
+
+ (* Call to a nameless function *)
+ with Not_found ->
+ let largs, fctx = lexp_parse_all pargs ctx in
+ let new_args = List.map (fun g -> (Aexplicit, g)) largs in
+ (* I think this should not modify context.
+ * if so, funny things might happen when evaluating *)
+ let fname, ctx = lexp_parse fname ctx in
+ Call(fname, new_args), ctx end
+
(* Read a pattern and create the equivalent representation *)
-and lexp_read_pattern pattern exp target:
- (string * location * (arg_kind * vdef) option list) =
+and lexp_read_pattern pattern exp target ctx:
+ ((string * location * (arg_kind * vdef) option list) * lexp_context) =
(* lookup target val if its a var and extract its args *)
(* TODO *)
match pattern with
| Ppatany (loc) -> (* Catch all expression nothing to do *)
- ("_", loc, [])
+ ("_", loc, []), ctx
| Ppatvar (loc, name) -> (* Create a variable containing target *)
- (*let nctx = add_variable name loc ctx in
- let idx = get_var_index name nctx in
- let info = (idx, (loc, name), target, UnknownType(loc)) in
- let nctx = add_variable_info info nctx in *)
- (name, loc, [])
+ let nctx = senv_add_var name loc ctx in
+ let nctx = env_add_var_info (0, (loc, name), target, dltype) nctx in
+ (name, loc, []), nctx
| Ppatcons (ctor_name, args) ->
let (loc, name) = ctor_name in
(* read pattern args *)
- let args = lexp_read_pattern_args args in
- (name, loc, args)
+ let args, nctx = lexp_read_pattern_args args ctx in
+ (name, loc, args), nctx
(* Read patterns inside a constructor *)
-and lexp_read_pattern_args args:((arg_kind * vdef) option list) =
+and lexp_read_pattern_args args ctx:
+ (((arg_kind * vdef) option list) * lexp_context)=
- let rec loop args acc =
+ let rec loop args acc ctx =
match args with
- | [] -> (List.rev acc)
- | hd::tl ->
+ | [] -> (List.rev acc), ctx
+ | hd::tl -> (
let (_, pat) = hd in
match pat with
(* Nothing to do *)
- | Ppatany (loc) -> loop tl (None::acc)
+ | Ppatany (loc) -> loop tl (None::acc) ctx
| Ppatvar (loc, name) ->
+ (* Add var *)
+ let nctx = senv_add_var name loc ctx in
+ let nctx = env_add_var_info (0, (loc, name), dlxp, dltype) nctx in
let nacc = (Some (Aexplicit, (loc, name)))::acc in
- loop tl nacc
- | _ -> lexp_fatal dloc "Constructor inside a Constructor";
+ loop tl nacc nctx
+ | _ -> lexp_error dloc "Constructor inside a Constructor";
+ loop tl (None::acc) ctx)
- in loop args []
+ in loop args [] ctx
(* Parse inductive constructor *)
and lexp_parse_constructors ctors ctx =
@@ -279,7 +363,7 @@ and lexp_parse_let decls ctx =
let ((_, name), _, _) = p in
if name == target then true else false in
- let rec loop (decls: (pvar * pexp * bool) list) merged:
+ let rec merge_decls (decls: (pvar * pexp * bool) list) merged:
(vdef * pexp option * pexp option) list =
(* we cant evaluate here because variable are not in the environment *)
@@ -294,22 +378,22 @@ and lexp_parse_let decls ctx =
* before the type info. Should we allow this? *)
let (vd, inst, _) = List.find (is_equal name) merged in
let new_decl = (vd, inst, Some type_info) in
- (loop tl (new_decl::merged))
+ (merge_decls tl (new_decl::merged))
with Not_found ->
let new_decl = (loc, name), None, Some type_info in
- (loop tl (new_decl::merged)) end
+ (merge_decls tl (new_decl::merged)) end
(* Instruction: Var = expr *)
| ((loc, name), inst, false) -> begin
try
let (vd, _, ptyp) = List.find (is_equal name) merged in
let new_decl = (vd, Some inst, ptyp) in
- (loop tl (new_decl::merged))
+ (merge_decls tl (new_decl::merged))
with Not_found ->
let new_decl = ((loc, name), Some inst, None) in
- (loop tl (new_decl::merged)) end in
+ (merge_decls tl (new_decl::merged)) end in
- let decls = loop decls [] in
+ let decls = merge_decls decls [] in
(* Add Each Variable to the environment *)
let nctx = List.fold_left (fun ctx hd ->
@@ -318,32 +402,32 @@ and lexp_parse_let decls ctx =
| ((loc, name), _, _) -> senv_add_var name loc ctx)
ctx decls in
- (* lexp_parse instruction and types *)
- let rec parse_decls decls ctx acc =
- match decls with
- | [] -> (List.rev acc), ctx
- | hd::tl -> begin
- match hd with
- | ((loc, name), Some pinst, Some ptype) ->
- let linst, nctx = lexp_parse pinst ctx in
- let ltyp, nctx = lexp_parse ptype nctx in
- let nacc = ((loc, name), linst, ltyp)::acc in
- let nctx =
- env_add_var_info (0, (loc, name), linst, ltyp) nctx in
- (parse_decls tl nctx nacc)
- | ((loc, name), Some pinst, None) ->
- let lxp, ltp = lexp_p_infer pinst ctx in
+ (* Add Variable info *)
+ let rec process_var_info dcl_lst _ctx acc =
+ match dcl_lst with
+ | [] -> (List.rev acc), _ctx
+ | hd::tl ->
+ match hd with
+ | ((loc, name), Some pinst, None) ->(
+ let lxp, ltp = lexp_p_infer pinst _ctx in
let nacc = ((loc, name), lxp, ltp)::acc in
- let nctx =
- env_add_var_info (0, (loc, name), lxp, ltp) nctx in
- (parse_decls tl nctx nacc)
+ let ctx2 = env_add_var_info (0, (loc, name), lxp, ltp) _ctx in
+ process_var_info tl ctx2 nacc)
+
+ | ((loc, name), Some pinst, Some ptype) ->(
+ let linst, ctx1 = lexp_parse pinst _ctx in
+ let ltyp, ctx2 = lexp_parse ptype ctx1 in
+ let nacc = ((loc, name), linst, ltyp)::acc in
+ let ctx3 = env_add_var_info (0, (loc, name), linst, ltyp) ctx2 in
+ process_var_info tl ctx3 nacc)
+
(* Skip the variable *)
- | ((loc, name), None, _) ->
- lexp_warning loc "Unused Variable";
- (parse_decls tl ctx acc) end in
-
- parse_decls decls nctx []
-
+ | ((loc, name), None, _) -> (lexp_warning loc "Unused Variable";
+ process_var_info tl _ctx acc) in
+
+ let acc, ctx = process_var_info decls nctx [] in
+ acc, ctx
+
and lexp_parse_all (p: pexp list) (ctx: lexp_context):
(lexp list * lexp_context) =
let rec loop (plst: pexp list) ctx (acc: lexp list) =
@@ -394,8 +478,7 @@ and lexp_print_adv opt exp =
| Imm(value) -> sexp_print value
| Var ((loc, name), idx) ->
print_string name;
- if idx > 0 then begin
- print_string "("; print_int idx; print_string ")"; end
+ print_string "["; print_int idx; print_string "]"
| Let (_, decls, body) ->
print_string "let"; lexp_print_decls (pty, indent + 1, prtp) decls;
@@ -416,13 +499,14 @@ and lexp_print_adv opt exp =
| Cons(vf, symbol) ->
let (loc, name) = symbol in
let ((loc, vname), idx) = vf in
- print_string (name ^ "("); print_string (vname ^ ")");
+ print_string (name ^ "("); print_string vname;
+ print_string "["; print_int idx; print_string "])"
| Call(fname, args) -> begin (* /!\ Partial Print *)
(* get function name *)
- let str = match fname with
- | Var((_, name), _) -> name
- | _ -> "unkwn" in
+ let str, idx = match fname with
+ | Var((_, name), idx) -> name, idx
+ | _ -> "unkwn", -1 in
let print_arg arg = match arg with | (kind, lxp) ->
lexp_print_adv (pty, 0, prtp) lxp in
@@ -439,7 +523,7 @@ and lexp_print_adv opt exp =
| ("_*_", [lhs; rhs]) -> print_binop " * " lhs rhs
(* not an operator *)
| _ ->
- print_string ("(" ^ str);
+ print_string ("(" ^ str ^ "["); print_int idx; print_string "]";
List.iter (fun arg -> print_string " "; print_arg arg) args;
print_string ")" end
@@ -506,26 +590,67 @@ and lexp_print_decls opt decls =
and lexp_context_print ctx =
let ((n, map), env) = ctx in
+ print_string (" " ^ (make_line '=' 20) ^ " LEXP CONTEXT " ^ (make_line '=' 20) ^ "\n");
+ print_string " | ";
+ ralign_print_string "NAME" 10; print_string " | ";
+ ralign_print_string "INDEX" 7; print_string " | ";
+ ralign_print_string "NAME" 10; print_string " | ";
+ ralign_print_string "VALUE" 7; print_string ": ";
+ print_string "TYPE"; print_string "\n";
+ print_string (" " ^ (make_line '-' 54) ^ "\n");
+
StringMap.iter (fun key idx ->
(* Print senv info *)
- print_string " ";
- ralign_print_string key 20;
- print_string " => ";
- ralign_print_int idx 4;
- print_string " => ";
+ print_string " | ";
+ ralign_print_string key 10;
+ print_string " | ";
+ ralign_print_int (n - idx - 1) 7;
+ print_string " | ";
(* Print env Info *)
- try let (_, (_, name), exp, tp) = env_lookup_by_index (n - idx) ctx in
- print_string name; (* name must match *)
- print_string " = ";
+ try let (_, (_, name), exp, tp) = env_lookup_by_index (n - idx - 1) ctx in
+ ralign_print_string name 10; (* name must match *)
+ print_string " | ";
lexp_print_adv (false, 0, true) exp;
print_string ": ";
lexp_print_adv (false, 0, true) tp;
print_string "\n"
with
Not_found -> print_string "Not_found \n")
- map
+
+ map;
+
+ print_string (" " ^ (make_line '=' 54) ^ "\n");
+
+(* Only print var info *)
+and lexp_print_var_info ctx =
+ let ((_, _), env) = ctx in
+ let n = Myers.length env in
+
+ for i = 0 to n - 1 do (
+ let (_, (_, name), exp, tp) = Myers.nth i env in
+ print_string name; (* name must match *)
+ print_string " = ";
+ lexp_print_adv (false, 0, true) exp;
+ print_string ": ";
+ lexp_print_adv (false, 0, true) tp;
+ print_string "\n")
+ done;
;;
let lexp_print = lexp_print_adv (false, 0, true)
-
+
+
+let lexp_parse_string (str: string) tenv grm limit =
+ let pretoks = prelex_string str in
+ let toks = lex tenv pretoks in
+ let sxps = sexp_parse_all_to_list grm toks limit in
+ let ctx = make_lexp_context in
+ let pxps = pexp_parse_all sxps in
+ lexp_parse_all pxps ctx
+;;
+
+let add_def name ctx =
+ let ctx = senv_add_var name dloc ctx in
+ env_add_var_info (0, (dloc, name), dlxp, dlxp) ctx
+;;
=====================================
src/pexp.ml
=====================================
--- a/src/pexp.ml
+++ b/src/pexp.ml
@@ -22,6 +22,8 @@ this program. If not, see <http://www.gnu.org/licenses/>. *)
open Util
open Sexp
+open Lexer
+open Prelexer
let pexp_error = msg_error "PEXP"
@@ -142,6 +144,9 @@ let rec pexp_parse (s : sexp) : pexp =
(* read Constructor name + args => Type ((Symbol * args) list) *)
| Node (Symbol s, cases)
-> (s, List.map pexp_p_ind_arg cases)::pcases
+ (* This is a constructor with no args *)
+ | Symbol s -> (s, [])::pcases
+
| _ -> pexp_error (sexp_location case)
"Unrecognized constructor declaration"; pcases)
cases [] in
@@ -349,3 +354,10 @@ let pexp_print e = sexp_print (pexp_unparse e)
let pexp_parse_all (nodes: sexp list) =
List.map pexp_parse nodes
;;
+
+let pexp_parse_string (str: string) tenv grm limit =
+ let pretoks = prelex_string str in
+ let toks = lex tenv pretoks in
+ let sxps = sexp_parse_all_to_list grm toks limit in
+ pexp_parse_all sxps
+;;
=====================================
src/prelexer.ml
=====================================
--- a/src/prelexer.ml
+++ b/src/prelexer.ml
@@ -140,8 +140,17 @@ let prelex_file file =
let fin = open_in file
in prelex file fin 1 [] [] (* Traditionally, line numbers start at 1 :-( *)
+(* Since current implementation is not compatible with stream *
+ * we write a temporary file and use this file as input. *
+ * This is a terrible solution but for the things we do it does not *
+ * really matters. Plus it will make testing easier *)
let prelex_string str =
- prelex "string" str 1 [] []
+ let fin = open_out "_temp_hack" in
+ output_string fin str;
+ (flush_all);
+ close_out fin;
+ let fin = open_in "_temp_hack" in
+ prelex "string" fin 1 [] []
let rec pretokens_print pretokens =
List.iter (fun pt ->
@@ -153,3 +162,8 @@ let rec pretokens_print pretokens =
| Prestring(_, str)
-> print_string "\""; print_string str; print_string "\"")
pretokens
+
+
+
+
+
\ No newline at end of file
=====================================
tests/REPL.ml
=====================================
--- /dev/null
+++ b/tests/REPL.ml
@@ -0,0 +1,104 @@
+open Debug
+open Prelexer
+open Lexer
+open Sexp
+open Grammar
+open Pexp
+open Debruijn
+open Lparse
+open Myers
+open Eval
+open Util
+open Lexp
+open Fmt
+
+let print_input_line i =
+ print_string " In[";
+ ralign_print_int i 2;
+ print_string "] >> "
+;;
+
+(* Read stdin for input. Returns only when the last char is ';' *)
+let rec read_input i =
+ print_input_line i;
+ flush stdout;
+
+ let rec loop str =
+ let line = input_line stdin in
+ let s = String.length str in
+ let n = String.length line in
+ if n = 0 then loop str else
+ let str = if s > 0 then String.concat "\n" [str; line] else line in
+ if line.[n - 1] = ';' || line.[0] = '%' then
+ str
+ else
+ (print_string " "; loop str) in
+
+ loop ""
+;;
+
+
+let eval_string (str: string) tenv grm limit lxp_ctx rctx =
+ let rec eval_all lxps acc rctx =
+ match lxps with
+ | [] -> (List.rev acc), rctx
+ | hd::tl ->
+ let lxp, rctx = eval hd rctx in
+ eval_all tl (lxp::acc) rctx in
+
+ let pretoks = prelex_string str in
+ let toks = lex tenv pretoks in
+ let sxps = sexp_parse_all_to_list grm toks limit in
+ let pxps = pexp_parse_all sxps in
+ let lxp, lxp_ctx = lexp_parse_all pxps lxp_ctx in
+ (eval_all lxp [] rctx), lxp_ctx
+;;
+
+(* Specials commands %[command-name] *)
+let rec repl () =
+ let tenv = default_stt in
+ let grm = default_grammar in
+ let limit = (Some ";") in
+ let eval_string str clxp rctx = eval_string str tenv grm limit clxp rctx in
+ let lxp_ctx = make_lexp_context in
+ (* Those are hardcoded operation *)
+ let lxp_ctx = add_def "_+_" lxp_ctx in
+ let lxp_ctx = add_def "_*_" lxp_ctx in
+ let lxp_ctx = add_def "_=_" lxp_ctx in
+
+ let rctx = make_runtime_ctx in
+
+ let rec loop i clxp rctx =
+ let ipt = read_input i in
+ (* Check special keywords *)
+ if ipt = "%quit" then () (* Stop REPL *)
+ else if ipt = "%who" then (* Print environment *)
+ (print_rte_ctx rctx; loop (i + 1) clxp rctx)
+ else if ipt = "%info" then
+ (lexp_context_print clxp; loop (i + 1) clxp rctx)
+ (* Else Process Typer code *)
+ else
+ let (ret, rctx), clxp = (eval_string ipt clxp rctx) in
+ let printe j v = print_eval_result i v in
+ List.iteri printe ret;
+ print_string "\n";
+ loop (i + 1) clxp rctx in
+
+ loop 1 lxp_ctx rctx
+;;
+
+let main () =
+ print_string ((make_line '-' 80) ^ "\n");
+ print_string " Typer REPL \n";
+ print_string " %quit : to leave\n";
+ print_string " %who : to print runtime environment\n";
+ print_string " %info : to print elaboration environment\n";
+ print_string ((make_line '-' 80) ^ "\n\n");
+ flush stdout;
+
+ repl ()
+;;
+
+
+main ()
+;;
\ No newline at end of file
=====================================
tests/full_debug.ml
=====================================
--- a/tests/full_debug.ml
+++ b/tests/full_debug.ml
@@ -41,6 +41,7 @@ open Lparse
open Myers
open Eval
open Util
+open Lexp
(* pexp and lexp can be done together, one by one *)
let pexp_lexp_one node ctx =
@@ -48,6 +49,8 @@ let pexp_lexp_one node ctx =
lexp_parse pxp ctx
;;
+let dloc = dummy_location;;
+
let pexp_lexp_all nodes ctx =
let rec loop nodes ctx acc =
@@ -58,6 +61,25 @@ let pexp_lexp_all nodes ctx =
(loop tl new_ctx (lxp::acc)) in
(loop nodes ctx [])
;;
+
+let dummy_decl = Imm(String(dloc, "Dummy"));;
+
+let add_rte_def name ctx =
+ (add_rte_variable (Some name) dummy_decl ctx);;
+
+
+let eval_until_nth xpr n rctx =
+
+ let rec loop xpr nb rctx =
+ match xpr, nb with
+ | [], _ -> rctx
+ | _, nb when nb = n -> rctx
+ | hd::tl, _ ->
+ let c, rctx = eval hd rctx in
+ print_eval_result nb c;
+ loop tl (nb + 1) rctx in
+ loop xpr 0 rctx
+;;
let main () =
@@ -96,6 +118,11 @@ let main () =
(* get lexp *)
let ctx = make_lexp_context in
+ (* Those are hardcoded operation *)
+ let ctx = add_def "_+_" ctx in
+ let ctx = add_def "_*_" ctx in
+ let ctx = add_def "_=_" ctx in
+
let lexps, new_ctx = lexp_parse_all pexps ctx in
(* Printing *)(*
@@ -105,14 +132,17 @@ let main () =
print_title "Pexp"; debug_pexp_print_all pexps;
print_title "Lexp"; debug_lexp_print_all lexps;
+ print_string "\n\n";
+ lexp_context_print new_ctx;
+
(* Eval Each Expression *)
print_title "Eval Print";
(* Eval One *)
- let rctx = make_runtime_ctx in
- let c, rctx = eval (List.hd lexps) rctx in
- print_eval_result c
-
+ let rctx = make_runtime_ctx in
+ let rctx = eval_until_nth lexps 500 rctx in
+ print_string "\n\n";
+ print_rte_ctx rctx;
end
;;
View it on GitLab: https://gitlab.com/monnier/typer/compare/02f84cd7fba45500f403b339740adf9277…
1
0
Setepenre pushed to branch master at Stefan / Typer
Commits:
693aa3fa by Pierre Delaunay at 2016-03-02T15:39:55-05:00
simplified lexp_context
- - - - -
02f84cd7 by Pierre Delaunay at 2016-03-03T12:27:34-05:00
PCall improved, + use lexp_p_infer when needed
- - - - -
9 changed files:
- doc/Compiler Structure.md
- samples/lexp_test.typer
- src/debruijn.ml
- src/eval.ml
- src/fmt.ml
- src/lparse.ml
- src/util.ml
- tests/debug.ml
- tests/full_debug.ml
Changes:
=====================================
doc/Compiler Structure.md
=====================================
--- a/doc/Compiler Structure.md
+++ b/doc/Compiler Structure.md
@@ -53,4 +53,10 @@ Read tests/full_debug.ml for ocaml usage
Function:
sexp_parse sexp
-* Sexp -> Lexp
\ No newline at end of file
+* Sexp -> Lexp
+
+ Replace variable name by their (reverse) index in the environment.
+
+
+
+
=====================================
samples/lexp_test.typer
=====================================
--- a/samples/lexp_test.typer
+++ b/samples/lexp_test.typer
@@ -8,7 +8,7 @@ let c = 1; a = 5; b = 10; d = 3; in
% -------------------------------------------
% define sqrt
-sqrt x = lambda (x : Nat) -> x * x;
+sqrt = lambda (x : Nat) -> x * x;
% define cube
cube = lambda (x : Nat) -> x * (sqrt x);
=====================================
src/debruijn.ml
=====================================
--- a/src/debruijn.ml
+++ b/src/debruijn.ml
@@ -35,6 +35,7 @@
open Util
open Lexp
open Myers
+open Fmt
let debruijn_error = msg_error "DEBRUIJN"
let debruijn_warning = msg_warning "DEBRUIJN"
@@ -54,172 +55,93 @@ module StringMap
(* Map matching variable name and its distance in the current scope *)
type scope = (int) StringMap.t (* Map<String, int>*)
-(* Offset is the number to take us out of the inner scope
- * Scope is the Mapping between Variable's names and its current index loc
- * Offset + Scope *)
-type senv_type = int * scope
-
-(* The recursive type that does everything
- * inner Scope * Outer Scope *)
-type lexp_context = senv_type * lexp_context option * env_type
+type senv_length = int (* it is not the map true length *)
+type senv_type = senv_length * scope
+ (* name -> index * index -> info *)
+type lexp_context = senv_type * env_type
(* internal definitions: DO NOT USE
* ---------------------------------- *)
let _make_scope = StringMap.empty;;
-let _make_context_impl = (0, _make_scope);;
+let _make_senv_type = (0, _make_scope);;
let _make_myers = nil
-let _get_inner_ctx (ctx: lexp_context) =
- let (ct, _, _) = ctx in ct
-;;
-
-let _get_inner_scope (ctx: lexp_context): scope =
- let ((_, scope), _, _) = ctx in scope
-;;
-
-let _get_environ (ctx: lexp_context) =
- let (_, _, env) = ctx in env
-;;
-
-(* get current offset *)
-let _get_offset (ctx: lexp_context): int =
- let ((offset, _), _, _) = ctx in offset
+let _get_senv (ctx: lexp_context) =
+ let (ct, _) = ctx in ct
;;
-(* increase the offset *)
-let _inc_offset (ctx: lexp_context): lexp_context =
- (* Because using ref is hell, we make a copy *)
- match ctx with
- | ((offset, scope), None, e) -> ((offset + 1, scope), None, e)
- | ((offset, scope), Some outter, e) ->
- ((offset + 1, scope), Some outter, e)
+let _get_scope(ctx: lexp_context): scope =
+ let ((_, ev), _) = ctx in ev
;;
-(* Increase the indexes of all inner variables *)
-let _inc_index (ctx: lexp_context): lexp_context =
- let ((offset, scope), otr, env) = ctx in
- let scope = StringMap.map (fun value -> value + 1) scope in
- ((offset, scope), otr, env)
+let _get_env(ctx: lexp_context): env_type =
+ let (_, ev) = ctx in ev
;;
-let _add_var_environ variable ctx =
- let (a, b, env) = ctx in cons variable env
+let _add_var_env variable ctx =
+ let (a, env) = ctx in cons variable env
;;
(* Public methods: DO USE
* ---------------------------------- *)
-(* return its current DeBruijn index
- * return -1 if the variable does not exist
- * return closest variable *)
+let make_lexp_context = (_make_senv_type, _make_myers);;
+
+(* return its current DeBruijn index *)
let rec senv_lookup (name: string) (ctx: lexp_context) =
- (* Search *)
- let local_index = find_local name ctx in
- if local_index >= 0 then
- local_index
- else
- begin
- let outter_index = _find_outer name ctx in
- if outter_index >= 0 then
- outter_index + (_get_offset ctx)
- else
- -1
- end
-
-and find_local (name: string) (ctx: lexp_context): int =
- try
- let inner = _get_inner_scope ctx in
- StringMap.find name inner
- with
- Not_found -> -1
-
-(* You should not use this function 'find_var' is the way
- * the reason is _find_outer does not send back a correct index *)
-and _find_outer (name: string) (ctx: lexp_context): int =
- match ctx with
- | (_, Some ct, _) -> (senv_lookup name ct)
- | _ -> -1
+ let ((n, map), _) = ctx in
+ n - (StringMap.find name map) - 1
;;
-(* We first add variable into our map later on we will add them into
+(* We first add variable into our map. Later on, we will add them into
* the environment. The reason for this is that the type info is
* known after lexp parsing which need the index fist *)
let senv_add_var name loc ctx =
- (*let (name, loc, exp, type_info) = var in *)
-
- (* I think this should be illegal *)
- let local_index = find_local name ctx in
- if local_index >= 0 then (* This is the index not the number of element *)
- debruijn_warning loc ("Variable Redefinition: " ^ name);
-
- let outer_index = _find_outer name ctx in
- if outer_index >= 0 then
- debruijn_warning loc ("Variable Shadowing: " ^ name);
-
- (* Increase distance *)
- let scope = StringMap.map (fun value -> value + 1) (_get_inner_scope ctx) in
- (* Add new Value to the map *)
- let new_scope = StringMap.add name 0 scope in
- (* build new context *)
- match ctx with
- | ((offset, _), None, e)
- -> ((offset + 1, new_scope), None, e)
- | ((offset, _), Some outter, e)
- -> ((offset + 1, new_scope), Some outter, e)
+ let ((n, map), e) = ctx in
+ try
+ let idx = senv_lookup name ctx in
+ debruijn_warning loc ("Variable Shadowing " ^ name);
+ let nmap = StringMap.add name n map in
+ ((n + 1, nmap), e)
+ with
+ Not_found ->
+ let nmap = StringMap.add name n map in
+ ((n + 1, nmap), e)
;;
(* *)
-let env_add_var_info var ctx =
- let (rof, (loc, name), value, ltyp) = var in
- let nenv = _add_var_environ (rof, (loc, name), value, ltyp) ctx in
- let (a, b, env) = ctx in
- (a, b, nenv)
+let env_add_var_info var (ctx: lexp_context) =
+ let (a, _) = ctx in
+ (* let (rof, (loc, name), value, ltyp) = var in *)
+ let nenv = _add_var_env var ctx in
+ (a, nenv)
;;
let env_lookup_type_by_index index ctx =
try
- let (roffset, (_, name), _, t) = Myers.nth index (_get_environ ctx) in
+ let (roffset, (_, name), _, t) = Myers.nth index (_get_env ctx) in
Shift (index - roffset, t)
with
Not_found -> internal_error "DeBruijn index out of bounds!"
;;
-let env_lookup_type (env : env_type) (v : vref) =
+let env_lookup_type ctx (v : vref) =
let ((_, rname), dbi) = v in
- try let (recursion_offset, (_, dname), _, t) = Myers.nth dbi env in
+ try let (recursion_offset, (_, dname), _, t) = Myers.nth dbi (_get_env ctx) in
if dname = rname then
Shift (dbi - recursion_offset, t)
else
internal_error "DeBruijn index refers to wrong name!"
with Not_found -> internal_error "DeBruijn index out of bounds!"
-(* Make a Global context *)
-let make_context = (_make_context_impl, None, _make_myers);;
-
-(* Make a new Scope inside the outer context 'ctx' *)
-let add_scope ctx = (_make_context_impl, Some ctx, _make_myers);;
-
-(* Print Functions for testing *)
-let print_scope (scp: scope) (offset: int): unit =
- StringMap.iter
- (fun key value
- -> print_string (key ^ "\t");
- print_int (value + offset);
- print_string "\n")
- scp
-;;
-
-let print_lexp_context (ctx: lexp_context): unit =
- print_string " Context Print\n";
-
- let rec impl (ctx2: lexp_context) (offset: int) =
- let inner = _get_inner_scope ctx2 in
- match ctx2 with
- | (_, Some ct, _)
- -> impl ct ((_get_offset ctx2) + offset);
- (print_scope inner offset);
- | _ -> (print_scope inner offset) in
- (impl ctx 0)
-;;
\ No newline at end of file
+let env_lookup_by_index index ctx = Myers.nth index (_get_env ctx);;
+
+
+
+
+
+
+
+
\ No newline at end of file
=====================================
src/eval.ml
=====================================
--- a/src/eval.ml
+++ b/src/eval.ml
@@ -37,6 +37,13 @@ open Myers
open Sexp
open Fmt
+let eval_error loc msg =
+ msg_error "EVAL" loc msg;
+ raise (internal_error msg)
+;;
+
+let dloc = dummy_location
+let eval_warning = msg_warning "EVAL"
let print_myers_list l print_fun =
@@ -102,9 +109,23 @@ let rec eval lxp ctx: (lexp * runtime_env) =
value, ctx end
(* Function call *)
- | Call (fname, args) ->
+ | Call (lname, args) ->
+ (* Try to extract name *)(*
+ let tname = match lname with
+ | Var((loc, name), _) -> name
+ | _ -> lexp_print lname; eval_error "Incorrect Function Name" in
+
+ (* Save declaration in environment *)
+ let n = List.length args in
+ if tname = "_=_" && n == 2 then
+ let (((_, name), _), expr) = args in
+ let nctx = add_rte_variable *)
+
+
(* Add args in the scope *)
+ print_rte_ctx ctx;
let nctx = build_arg_list args ctx in
+ print_rte_ctx nctx;
(* We need to seek out the function declaration and eval the body *)
(* but currently we cannot declare functions so I hardcoded + *)
@@ -112,14 +133,17 @@ let rec eval lxp ctx: (lexp * runtime_env) =
eval bdy nctx *)
(* fname is currently a var *)
- let name = get_function_name fname in
+ let name = get_function_name lname in
(* Hardcoded function for now *)
if name = "_+_" then begin
-
+
(* Get the two args *)
let l = get_int (get_rte_variable 0 nctx) in
let r = get_int (get_rte_variable 1 nctx) in
+ (*print_int l; print_string " ";
+ print_int r; print_string "\n"; *)
+
Imm(Integer(dummy_location, l + r)), ctx end
else
Imm(String(dummy_location, "Funct Not Implemented")), ctx
@@ -127,10 +151,8 @@ let rec eval lxp ctx: (lexp * runtime_env) =
| _ -> Imm(String(dummy_location, "Eval Not Implemented")), ctx
and build_arg_list args ctx =
-
(* Eval every args *)
let arg_val = List.map (fun (k, e) -> let (v, c) = eval e ctx in v) args in
-
(* Add args inside context *)
List.fold_left (fun c v -> add_rte_variable v c) ctx arg_val
=====================================
src/fmt.ml
=====================================
--- a/src/fmt.ml
+++ b/src/fmt.ml
@@ -36,55 +36,43 @@ let str_size_int value =
;;
(* print n char 'c' *)
-let rec make_line c n =
- print_string c;
- if n >= 1 then (make_line c (n - 1));
-;;
-
-(* print an integer right-aligned *)
-let ralign_print_int value nb =
- make_line " " (nb - (str_size_int value));
- print_int value;
-;;
+let rec make_line c n = String.make n c;;
-let lalign_print_int value nb =
- print_int value;
- make_line " " (nb - (str_size_int value));
-;;
-
-let ralign_print_string str nb =
- make_line " " (nb - String.length str);
- print_string str;
+(* Big numbers are replaced by #### *)
+let cut_int (v:int) (start:int) (len:int): int = 0;;
+
+(* LALIGN
+ * ----------------------- *)
+let ralign_generic get_size print_str print_elem cut_elem elem col =
+ let n = get_size elem in
+ if n > col then
+ print_elem (cut_elem elem 0 col)
+ else begin
+ print_str (make_line ' ' (col - n));
+ print_elem elem; end
;;
-let lalign_print_string str nb =
- print_string str;
- make_line " " (nb - String.length str);
-;;
+let ralign_print_string =
+ ralign_generic String.length print_string print_string String.sub;;
-(* print n char 'c' *)
-let rec prerr_make_line c n =
- prerr_string c;
- if n >= 1 then (make_line c (n - 1));
-;;
-
-(* print an integer right-aligned *)
-let ralign_prerr_int value nb =
- prerr_make_line " " (nb - (str_size_int value));
- prerr_int value;
-;;
+let ralign_print_int =
+ ralign_generic str_size_int print_string print_int cut_int;;
+
-let lalign_prerr_int value nb =
- prerr_int value;
- prerr_make_line " " (nb - (str_size_int value));
-;;
+(* LALIGN
+ * ----------------------- *)
+let lalign_generic get_size print_str print_elem cut_elem elem col =
+ let n = get_size elem in
+ if n > col then
+ print_elem (cut_elem elem 0 col)
+ else begin
+ print_elem elem;
+ print_str (make_line ' ' (col - n)); end
+;;
+
+let lalign_print_string =
+ lalign_generic String.length print_string print_string String.sub;;
-let ralign_prerr_string str nb =
- prerr_make_line " " (nb - String.length str);
- prerr_string str;
-;;
+let lalign_print_int =
+ lalign_generic str_size_int print_string print_int cut_int;;
-let lalign_prerr_string str nb =
- prerr_string str;
- prerr_make_line " " (nb - String.length str);
-;;
=====================================
src/lparse.ml
=====================================
--- a/src/lparse.ml
+++ b/src/lparse.ml
@@ -47,14 +47,15 @@ let not_implemented_error () =
internal_error "not implemented"
;;
-let lexp_error loc msg =
+let dloc = dummy_location
+
+let lexp_warning = msg_warning "LEXP"
+let lexp_error = msg_error "LEXP"
+let lexp_fatal loc msg =
msg_error "LEXP" loc msg;
raise (internal_error msg)
;;
-let dloc = dummy_location
-let lexp_warning = msg_warning "LEXP"
-
(* Print back in CET (Close Enough Typer) easier to read *)
(* pretty ? * indent level * print_type? *)
type print_context = (bool * int * bool)
@@ -77,17 +78,22 @@ let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
(* Block/String/Integer/Float *)
| Pimm value -> Imm(value), ctx
- (* Symbol i.e identifier /!\ A lot of Pvar are not variables /!\ *)
- | Pvar (loc, name) ->
- let idx = senv_lookup name ctx in
- (* This should be an error but we accept it for debugging *)
- if idx < 0 then
- lexp_warning tloc ("Variable: '" ^ name ^ "' does not exist");
- (make_var name (idx) loc), ctx;
-
+ (* Symbol i.e identifier *)
+ | Pvar (loc, name) -> begin
+ try
+ (* Send Variable loc *)
+ let idx = senv_lookup name ctx in
+ (make_var name idx loc), ctx;
+
+ with Not_found ->
+ (* Add Variable *)
+ let ctx = senv_add_var name loc ctx in
+ (make_var name 0 loc), ctx; end
+
(* Let, Variable declaration + local scope *)
- | Plet(loc, decls, body) -> (* /!\ HERE *)
- let decl, nctx = lexp_parse_let decls (add_scope ctx) in
+ | Plet(loc, decls, body) ->
+ let decl, nctx = lexp_parse_let decls ctx in
+ lexp_context_print nctx;
let bdy, nctx = lexp_parse body nctx in
(* Send back old context as we exit the inner scope *)
Let(tloc, decl, bdy), ctx
@@ -115,19 +121,42 @@ let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
let nvar = pvar_to_vdef var in (* /!\ HERE *)(* /!\ Missing Type *)
let lbody, ctx = lexp_parse body ctx in
Lambda(kind, nvar, UnknownType(tloc), lbody), ctx
-
- (* Function Call *)
+
| Pcall (fname, _args) ->
- (* Why function names are pexp ? *)
- let fname, ctx = lexp_parse fname ctx in
-
+ (* Process Arguments *)
let pargs = pexp_parse_all _args in
let largs, fctx = lexp_parse_all pargs ctx in
-
(* Make everything explicit for now *)
let new_args = List.map (fun g -> (Aexplicit, g)) largs in
-
- Call(fname, new_args), ctx
+
+ (* Call to named function which must have been defined earlier *
+ * i.e they must be in the context *)
+ begin try begin
+ (* Get function name *)
+ let name, loc = match fname with
+ | Pvar(loc, nm) -> nm, loc
+ | Pcons (_, (loc, nm)) -> nm, loc
+ | _ -> raise Not_found in
+
+ try
+ (* Check if the function was defined *)
+ let idx = senv_lookup name ctx in
+ let vf = (make_var name idx loc) in
+ Call(vf, new_args), ctx
+
+ with Not_found ->
+ (* Don't stop even if an error was found *)
+ lexp_error loc ("The function \"" ^ name ^
+ "\" was not defined");
+ let vf = (make_var name (-1) loc) in
+ Call(vf, new_args), ctx end
+
+ (* Call to a nameless function *)
+ with Not_found ->
+ (* I think this should not modify context.
+ * if so, funny things might happen when evaluating *)
+ let fname, ctx = lexp_parse fname ctx in
+ Call(fname, new_args), ctx end
(* Pinductive *)
| Pinductive (label, _, ctors) ->
@@ -172,6 +201,9 @@ let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
and lexp_read_pattern pattern exp target:
(string * location * (arg_kind * vdef) option list) =
+ (* lookup target val if its a var and extract its args *)
+ (* TODO *)
+
match pattern with
| Ppatany (loc) -> (* Catch all expression nothing to do *)
("_", loc, [])
@@ -202,10 +234,9 @@ and lexp_read_pattern_args args:((arg_kind * vdef) option list) =
(* Nothing to do *)
| Ppatany (loc) -> loop tl (None::acc)
| Ppatvar (loc, name) ->
- (* get kind from the call *)
let nacc = (Some (Aexplicit, (loc, name)))::acc in
loop tl nacc
- | _ -> lexp_error dloc "Constructor inside a Constructor";
+ | _ -> lexp_fatal dloc "Constructor inside a Constructor";
in loop args []
@@ -281,19 +312,11 @@ and lexp_parse_let decls ctx =
let decls = loop decls [] in
(* Add Each Variable to the environment *)
- let rec add_var_env decls ctx =
- match decls with
- | [] -> ctx
- | hd::tl -> begin
- match hd with
- (* Unused variable: No Instruction *)
- (* Warning will be printed later *)
- | ((loc, name), None, _) -> add_var_env tl ctx
- | ((loc, name), _, _) ->
- let ctx = senv_add_var name loc ctx in
- add_var_env tl ctx end in
-
- let nctx = add_var_env decls ctx in
+ let nctx = List.fold_left (fun ctx hd ->
+ match hd with
+ | (_, None, _) -> ctx (* Unused variable: No Instruction *)
+ | ((loc, name), _, _) -> senv_add_var name loc ctx)
+ ctx decls in
(* lexp_parse instruction and types *)
let rec parse_decls decls ctx acc =
@@ -309,19 +332,16 @@ and lexp_parse_let decls ctx =
env_add_var_info (0, (loc, name), linst, ltyp) nctx in
(parse_decls tl nctx nacc)
| ((loc, name), Some pinst, None) ->
- let linst, nctx = lexp_parse pinst ctx in
- (* This is where UnknownType are introduced *)
- (* need Inference HERE *)
- let nacc = ((loc, name), linst, UnknownType(loc))::acc in
- let nctx =
- env_add_var_info (0, (loc, name), linst, UnknownType(loc)) nctx in
+ let lxp, ltp = lexp_p_infer pinst ctx in
+ let nacc = ((loc, name), lxp, ltp)::acc in
+ let nctx =
+ env_add_var_info (0, (loc, name), lxp, ltp) nctx in
(parse_decls tl nctx nacc)
(* Skip the variable *)
| ((loc, name), None, _) ->
- lexp_warning loc "Unused Variable";
- (parse_decls tl ctx acc)
- end in
-
+ lexp_warning loc "Unused Variable";
+ (parse_decls tl ctx acc) end in
+
parse_decls decls nctx []
and lexp_parse_all (p: pexp list) (ctx: lexp_context):
@@ -379,7 +399,7 @@ and lexp_print_adv opt exp =
| Let (_, decls, body) ->
print_string "let"; lexp_print_decls (pty, indent + 1, prtp) decls;
- if pty then make_line " " (indent * 4 + 4);
+ if pty then print_string (make_line ' ' (indent * 4 + 4));
print_string " in "; lexp_print_adv (pty, indent + 2, prtp) body
| Arrow(kind, Some (_, name), tp, loc, expr) ->
@@ -440,7 +460,7 @@ and lexp_print_adv opt exp =
| Some (kind, (l, n)) -> print_string (" " ^ n)) arg in
SMap.iter (fun key (loc, arg, exp) ->
- make_line " " (indent * 4);
+ print_string (make_line ' ' (indent * 4));
print_string ("| " ^ key); print_arg arg;
print_string " -> ";
slexp_print exp; print_string "; ";
@@ -450,7 +470,7 @@ and lexp_print_adv opt exp =
match dflt with
| None -> ()
| Some df ->
- make_line " " (indent * 4);
+ print_string (make_line ' ' (indent * 4));
print_string "| _ -> "; slexp_print df;
print_string ";"; if pty then print_string "\n"; end
@@ -475,14 +495,37 @@ and lexp_print_decls opt decls =
List.iteri (fun idx g -> match g with
| ((loc, name), expr, ltyp) ->
- if pty && idx > 0 then make_line " " (indent * 4);
+ if pty && idx > 0 then print_string (make_line ' ' (indent * 4));
if prtp then print_type name ltyp; print_string " ";
print_string (name ^ " = ");
lexp_print_adv opt expr; print_string ";";
if pty then print_string "\n")
decls
-;;
+(* Print context *)
+and lexp_context_print ctx =
+ let ((n, map), env) = ctx in
+
+ StringMap.iter (fun key idx ->
+ (* Print senv info *)
+ print_string " ";
+ ralign_print_string key 20;
+ print_string " => ";
+ ralign_print_int idx 4;
+ print_string " => ";
+
+ (* Print env Info *)
+ try let (_, (_, name), exp, tp) = env_lookup_by_index (n - idx) ctx in
+ print_string name; (* name must match *)
+ print_string " = ";
+ lexp_print_adv (false, 0, true) exp;
+ print_string ": ";
+ lexp_print_adv (false, 0, true) tp;
+ print_string "\n"
+ with
+ Not_found -> print_string "Not_found \n")
+ map
+;;
let lexp_print = lexp_print_adv (false, 0, true)
=====================================
src/util.ml
=====================================
--- a/src/util.ml
+++ b/src/util.ml
@@ -36,15 +36,6 @@ let print_loc (loc: location) =
Fmt.ralign_print_int loc.column 3;
;;
-(* print debug info *)
-let prerr_loc (loc: location) =
- (*print_string loc.file; *) (* Printing the file is too much*)
- prerr_string "ln ";
- Fmt.ralign_prerr_int loc.line 3;
- prerr_string ", cl ";
- Fmt.ralign_prerr_int loc.column 3;
-;;
-
(* File is not printed because currently we parse only one file... *)
(* Section is the name of the compilation step [for debugging] *)
(* 'prerr' output is ugly *)
=====================================
tests/debug.ml
=====================================
--- a/tests/debug.ml
+++ b/tests/debug.ml
@@ -40,6 +40,8 @@ open Sexp
open Pexp
open Lexp
open Lparse
+open Debruijn
+open Fmt
(* Print aPretokens *)
let rec debug_pretokens_print pretoken =
@@ -178,3 +180,4 @@ let debug_lexp_print_all lexps =
;;
+
=====================================
tests/full_debug.ml
=====================================
--- a/tests/full_debug.ml
+++ b/tests/full_debug.ml
@@ -40,6 +40,7 @@ open Debruijn
open Lparse
open Myers
open Eval
+open Util
(* pexp and lexp can be done together, one by one *)
let pexp_lexp_one node ctx =
@@ -94,7 +95,7 @@ let main () =
let pexps = pexp_parse_all nodes in
(* get lexp *)
- let ctx = make_context in
+ let ctx = make_lexp_context in
let lexps, new_ctx = lexp_parse_all pexps ctx in
(* Printing *)(*
View it on GitLab: https://gitlab.com/monnier/typer/compare/81fa9435dd8e8bca722405fad32e939f6a…
2
1
[Git][monnier/typer][master] 15 commits: sexp_parse_to_list + debugs in one files
by Setepenre 01 Mar '16
by Setepenre 01 Mar '16
01 Mar '16
Setepenre pushed to branch master at Stefan / Typer
Commits:
59caf4c8 by Pierre Delaunay at 2016-02-18T17:04:36-05:00
sexp_parse_to_list + debugs in one files
- - - - -
2c1f85fe by Pierre Delaunay at 2016-02-19T17:42:47-05:00
pexp debug_print
- - - - -
1617fc49 by Pierre Delaunay at 2016-02-19T18:11:50-05:00
add pexp test file
- - - - -
f27e2fe6 by Pierre Delaunay at 2016-02-20T11:04:54-05:00
Pinductive fix
- - - - -
15297a8c by Pierre Delaunay at 2016-02-22T16:52:39-05:00
debuijn data structure
- - - - -
d5019e4a by Pierre Delaunay at 2016-02-24T23:10:18-05:00
let/Arrow/Lambda lexp
- - - - -
24668c78 by Pierre Delaunay at 2016-02-24T23:47:20-05:00
comment cleaning
- - - - -
fc20af3d by Pierre Delaunay at 2016-02-25T00:50:45-05:00
pexp_decls function node activated
- - - - -
4115d3ff by Pierre Delaunay at 2016-02-25T01:29:52-05:00
add 'Section' (sexp, pexp, lexp, ...) in error message
- - - - -
a0c7ef21 by Pierre Delaunay at 2016-02-25T19:16:48-05:00
merging
- - - - -
25508a29 by Pierre Delaunay at 2016-02-25T20:41:14-05:00
add Debruijn index
- - - - -
f9d3f518 by Pierre Delaunay at 2016-02-26T17:12:59-05:00
fix let declaration merging
- - - - -
0119ea77 by Pierre Delaunay at 2016-02-26T17:38:56-05:00
lexp PCall handling
- - - - -
bb2cbbd5 by Pierre Delaunay at 2016-02-26T23:14:40-05:00
cleaning
- - - - -
62596a77 by Pierre Delaunay at 2016-02-27T12:16:56-05:00
merging
- - - - -
29 changed files:
- .gitignore
- GNUmakefile
- + TODO.md
- + _tags
- + doc/Compiler Structure.md
- + samples/debug_test.typer
- samples/lexer_test.typer
- + samples/lexp_test.typer
- src/pervasive.typer → samples/pervasive.typer
- − samples/pexp_test.typer
- − samples/token_test.typer
- + src/debruijn.ml
- src/fmt.ml
- tests/primary_debug.ml → src/grammar.ml
- src/lexp.ml
- + src/lparse.ml
- src/pexp.ml
- src/prelexer.ml
- src/sexp.ml
- src/util.ml
- + tests/debruijn_test.ml
- tests/debug.ml
- − tests/dummy1_test.ml
- − tests/dummy2_test.ml
- − tests/dummy_test.ml
- + tests/full_debug.ml
- − tests/lexer_debug.ml
- − tests/prelexer_debug.ml
- tests/utest_main.ml
Changes:
=====================================
.gitignore
=====================================
--- a/.gitignore
+++ b/.gitignore
@@ -12,6 +12,7 @@ typer
*.aux
manual.??
*.info
-_build/
+*_build/
*~
#*#
+test__.ml
=====================================
GNUmakefile
=====================================
--- a/GNUmakefile
+++ b/GNUmakefile
@@ -1,26 +1,28 @@
RM=rm -f
TEST_FILES := $(wildcard ./tests/*_test.ml)
+# This is for windows: Make windows version is old
+ifeq ($(OS),Windows_NT)
+SHELL=C:/Windows/System32/cmd.exe
+endif
all: typer debug tests
typer:
- ocamlbuild src/main.byte
+ ocamlbuild src/main.byte -cflag -rectypes
mv _build/src/main.byte _build/typer # move and rename executable
debug:
- ocamlbuild tests/prelexer_debug.byte -I src # debug print
- mv _build/tests/prelexer_debug.byte _build/prelexer_debug
- ocamlbuild tests/lexer_debug.byte -I src # debug print
- mv _build/tests/lexer_debug.byte _build/lexer_debug
+ ocamlbuild tests/full_debug.native -I src -cflag -rectypes
+ mv _build/tests/full_debug.native _build/full_debug
tests:
# Build tests
- $(foreach test, $(TEST_FILES), ocamlbuild $(subst ./,,$(subst .ml,.byte,$(test))) -I src;)
+ $(foreach test, $(TEST_FILES), ocamlbuild $(subst ./,,$(subst .ml,.native,$(test))) -I src -cflag -rectypes;)
# Run tests
- ocamlbuild tests/utest_main.byte
- ./_build/tests/utest_main.byte
+ ocamlbuild tests/utest_main.native
+ ./_build/tests/utest_main.native
# Make language doc
doc-tex:
=====================================
TODO.md
=====================================
--- /dev/null
+++ b/TODO.md
@@ -0,0 +1,31 @@
+TODO
+====
+
+PROJECT:
+ * pretty arg parsing utils
+
+FILE: full_debug.ml
+ * better arg parsing
+ * Allow users to choose what to print (Pretoks/Sexp/SexpNode/Pexp/Lexp/etc..)
+ * --all
+ * --pretoks
+ * --sexp
+ * --node
+ * --pexp
+ * --lexp
+
+ Other Option
+ --repl
+
+
+case (a,b)
+ | (Foo, Foo) => 3.14
+ | (Bar, Bar) => 3.15
+;;
+
+
+
+# Issues
+
+* The duplicate ';' create Sexp::Epsilon() which makes pexp_parse fail
+* pexp_parse fail to parse inductive
=====================================
_tags
=====================================
--- /dev/null
+++ b/_tags
=====================================
doc/Compiler Structure.md
=====================================
--- /dev/null
+++ b/doc/Compiler Structure.md
@@ -0,0 +1,56 @@
+Stream.of_string
+
+Typer Compiler Structure
+========================
+
+Read tests/full_debug.ml for ocaml usage
+
+
+* in_channel -> PreLexer: PreToken
+
+ Skips Blocks and identifies Strings
+
+ Blocks : {this is a block}
+ String : "this is a string"
+ PreToken: a pretoken is everything else
+
+ Function:
+ prelex_file file
+
+ TODO:
+ prelex_str "my code"
+
+* PreToken -> Lexer: Sexp
+
+ Process PreToken. Cut them in smaller pieces according to [stt : token_env]
+ For example:
+
+ Code: "a => 3;"
+
+ Pretoken: ['a', '=>', '3;']
+
+ Lexer ['a', '=>', '3;'] => ['a', '=>', '3', ';']
+
+ Here ';' is in stt which makes the '3;' pretoken to explode in two.
+
+ Function:
+ lex stt pretoken
+
+* Sexp -> sexp_parse: Sexp
+
+ Group Sexp into Nodes according to the specified grammar.
+ Create the program tree.
+
+ Code: "a => 3;"
+
+ Pretoken: ['a', '=>', '3;']
+
+ Lexer ['a', '=>', '3;'] => ['a', '=>', '3', ';'] (Sexp)
+
+ sexp_parse ['a', '=>', '3', ';']
+ => Node('_=>_', ['a', '3'])
+
+ Function:
+ sexp_parse sexp
+
+* Sexp -> Lexp
\ No newline at end of file
=====================================
samples/debug_test.typer
=====================================
--- /dev/null
+++ b/samples/debug_test.typer
@@ -0,0 +1,41 @@
+%
+% Pexp Debugging: Everything must work
+% This is not meant to be correct Typer input
+%
+
+{a => "This is a block"}; % Pimm: Block
+"This is a String"; % Pimm: String
+12; % Pimm: Integer
+12.12; % Pimm: Float
+
+% Pvar
+ab;
+
+% let_in
+let a = b in
+ c = b
+;
+
+% PCall
+(function arg1 arg2 arg3);
+
+% Parrow
+a -> 1;
+a => 2;
+a ≡> 1;
+
+% Lambda
+a = lambda (x, y) -> x + y;
+b = lambda (x, y) => x * y;
+c = lambda (x, y) ≡> x / y;
+
+% case
+case (a, b)
+ | (1, 2) => 1
+ | (_, _) => 3
+;
+
+% inductive
+% Nat : Type
+Type = inductive_ (Type_Label) (zero) (succ Type);
+inductive_ (Type_Label) (zero) (succ Type);
\ No newline at end of file
=====================================
samples/lexer_test.typer
=====================================
--- a/samples/lexer_test.typer
+++ b/samples/lexer_test.typer
@@ -4,36 +4,30 @@
%% ----------------
%% String
-a = "The answer is 42";
+a => "The answer is 42";
%% Integer
-b = 11;
+b => 11;
%% Float
-c = 3.14;
+c => 3.14;
%% Something
-C = 3.14.14;
-
+C => 3.14.14;
%% Case
+%% ----------------
case (a,b)
- | (Foo,Foo) => 3.14
- | (Bar,Bar) => 3.15
-;;
+ | (Foo, Foo) => 3.14
+ | (Bar, Bar) => 3.15
+;
%% Stuff
%% ----------------
-%% Epsilon
-
%% Block
-
-
-%% Node
-%% -> Composed expression
-
-%% Symbol
-%% --> Everything else
+{
+ a => "This is a Block";
+}
\ No newline at end of file
=====================================
samples/lexp_test.typer
=====================================
--- /dev/null
+++ b/samples/lexp_test.typer
@@ -0,0 +1,62 @@
+ab;
+
+% Type is read as a Pvar ?????
+add = lambda (a : Type) -> lambda (b : Type) -> (add a b);
+
+% How typer is supposed to read this
+p:int -> int;
+
+% this is a call to _=_
+odd n = case n | 0 => false | S n' => even (n');
+
+%
+% Here we test that two declaration with different
+% name are EXACLTY equivalent in the eyes
+% of the compiler
+%
+% Declaration order STILL MATTERS
+%
+
+% let
+let a:Nat; d:Nat; c:Nat; b:Nat;
+ a = b;
+ d = a;
+ c = d;
+ b = c;
+ in a + b + c + d
+;
+
+% let: Different naming
+let e:Nat; f:Nat; g:Nat; h:Nat;
+ e = h;
+ f = e;
+ g = f;
+ h = g;
+ in e + h + g + f
+;
+
+% let: Different Ordering
+let b:Nat; c:Nat; d:Nat; a:Nat;
+ c = d;
+ d = a;
+ b = c;
+ a = b;
+ in a + b + c + d
+;
+
+%
+% Recursivity detection
+%
+
+let odd: (int -> int);
+ even: (int -> int);
+ odd n = case n | 0 => false | S n' => even (n');
+ even n = case n | 0 => true | S n' => odd (n');
+ in a + b;
+
+
+% Do I consider functions as variable ?? Yes
+
+
+
+
=====================================
src/pervasive.typer → samples/pervasive.typer
=====================================
--- a/src/pervasive.typer
+++ b/samples/pervasive.typer
=====================================
samples/pexp_test.typer deleted
=====================================
--- a/samples/pexp_test.typer
+++ /dev/null
@@ -1,50 +0,0 @@
-%%
-%% Proto lambda-expressions, half-way between Sexp and Lexp.
-%%
-
-%% ppat
-%% -----------------
-
-%% Ppatany
-
-%% Ppatvar
-
-%% Ppatcons
-
-
-%% pexp
-%% -----------------
-
-%% Pimm
-%%
-
-%% Pvar
-%%
-
-%% Phastype
-%%
-
-%% Pmetavar
-%%
-
-%% Plet
-%%
-
-%% Parrow
-%%
-
-%% Plambda
-%%
-
-%% Pcall
-%%
-
-%% Pinductive
-%%
-
-%% Pcons
-%%
-
-%% Pcase
-%%
-
=====================================
samples/token_test.typer deleted
=====================================
--- a/samples/token_test.typer
+++ /dev/null
@@ -1,28 +0,0 @@
-%% This file check if typer recognize correctly tokens
-
-%% builtin types
-%% ----------------
-
-%% String
-a = "The answer is 42";
-
-%% Integer
-b = 11;
-
-%% Float
-c = 3.14;
-
-
-%% Stuff
-%% ----------------
-
-%% Epsilon
-
-%% Block
-
-
-%% Node
-%% -> Composed expression
-
-%% Symbol
-%% --> Everything else
=====================================
src/debruijn.ml
=====================================
--- /dev/null
+++ b/src/debruijn.ml
@@ -0,0 +1,196 @@
+(*
+ * Typer Compiler
+ *
+ * ---------------------------------------------------------------------------
+ *
+ * Copyright (C) 2011-2016 Free Software Foundation, Inc.
+ *
+ * Author: Pierre Delaunay <pierre.delaunay(a)hec.ca>
+ * Keywords: languages, lisp, dependent types.
+ *
+ * This file is part of Typer.
+ *
+ * Typer is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ * Typer is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * ---------------------------------------------------------------------------
+ *
+ * Description:
+ * Specifies recursive data structure for DeBruijn indexing
+ * methods starting with '_' are considered private and should not
+ * elsewhere in the project
+ *
+ * Methods:
+ * make_context : make an empty context
+ * add_scope ctx : add new scope to the current context
+ * find_var name ctx: return the index of the variable 'name'
+ * add_variable name loc ctx : add a variable to the current context
+ *
+ * TODO:
+ * ADD meyers list <index -> (type, name?)>
+ *
+ * ---------------------------------------------------------------------------*)
+
+open Util
+
+let debruijn_error = msg_error "DEBRUIJN"
+let debruijn_warning = msg_warning "DEBRUIJN"
+
+(* Type definitions
+ * ---------------------------------- *)
+
+(* This exist because I don't want that file to depend on anything *)
+module StringMap
+ = Map.Make (struct type t = string let compare = String.compare end)
+;;
+
+(* Map matching variable name and its distance in the current scope *)
+type scope = (int) StringMap.t (* Map<String, int>*)
+
+(* Offset is the number to take us out of the inner scope
+ * Scope is the Mapping between Variable's names and its current index loc
+ * Offset + Scope *)
+type context_impl = int * scope
+
+(* The recursive type that does everything
+ * inner Scope * Outer Scope *)
+type lexp_context = context_impl * lexp_context option
+
+
+(* internal definitions: DO NOT USE
+ * ---------------------------------- *)
+
+let _make_scope = StringMap.empty;;
+let _make_context_impl = (0, _make_scope);;
+
+let _get_inner_ctx (ctx: lexp_context) =
+ match ctx with
+ | (ct, _) -> ct
+;;
+
+let _get_inner_scope (ctx: lexp_context): scope =
+ let ictx = _get_inner_ctx ctx in
+ match ictx with
+ | (_, scope) -> scope
+;;
+
+(* get current offset *)
+let _get_offset (ctx: lexp_context): int =
+ let inner = _get_inner_ctx ctx in
+ match inner with
+ | offset, _ -> offset
+;;
+
+(* increase the offset *)
+let _inc_offset (ctx: lexp_context): lexp_context =
+ (* Because using ref is hell, we make a copy *)
+ match ctx with
+ | ((offset, scope), None) -> ((offset + 1, scope), None)
+ | ((offset, scope), Some outter) -> ((offset + 1, scope), Some outter)
+;;
+
+(* Increase the indexes of all inner variables *)
+let _inc_index (ctx: lexp_context): lexp_context =
+ let ((offset, scope), otr) = ctx in
+ let scope = StringMap.map (fun value -> value + 1) scope in
+ ((offset, scope), otr)
+;;
+
+(* Public methods: DO USE
+ * ---------------------------------- *)
+
+(* return its current DeBruijn index
+ * return -1 if the variable does not exist
+ * return closest variable *)
+let rec find_var (name: string) (ctx: lexp_context) =
+ (* Search *)
+ let local_index = find_local name ctx in
+ if local_index >= 0 then
+ local_index
+ else
+ begin
+ let outter_index = _find_outer name ctx in
+ if outter_index >= 0 then
+ outter_index + (_get_offset ctx)
+ else
+ -1
+ end
+
+and find_local (name: string) (ctx: lexp_context): int =
+ try
+ let inner = _get_inner_scope ctx in
+ StringMap.find name inner
+ with
+ Not_found -> -1
+
+(* You should not use this function 'find_var' is the way
+ * the reason is _find_outer does not send back a correct index *)
+and _find_outer (name: string) (ctx: lexp_context): int =
+ match ctx with
+ | (_, Some ct) -> (find_var name ct)
+ | _ -> -1
+;;
+
+(* Alias *)
+let get_var_index name ctx = find_var name ctx;;
+
+let add_variable name loc ctx =
+ (* I think this should be illegal *)
+ let local_index = find_local name ctx in
+ if local_index >= 0 then (* This is the index not the number of element *)
+ debruijn_warning loc ("Variable Redefinition: " ^ name);
+
+ let outer_index = _find_outer name ctx in
+ if outer_index >= 0 then
+ debruijn_warning loc ("Variable Shadowing: " ^ name);
+
+ (* Increase distance *)
+ let scope = StringMap.map (fun value -> value + 1) (_get_inner_scope ctx) in
+ (* Add new Value *)
+ let new_scope = StringMap.add name 0 scope in
+ (* build new context *)
+ match ctx with
+ | ((offset, _), None)
+ -> ((offset + 1, new_scope), None)
+ | ((offset, _), Some outter)
+ -> ((offset + 1, new_scope), Some outter)
+;;
+
+(* Make a Global context *)
+let make_context = (_make_context_impl, None);;
+
+(* Make a new Scope inside the outer context 'ctx' *)
+let add_scope ctx = (_make_context_impl, Some ctx);;
+
+(* Print Functions for testing *)
+let print_scope (scp: scope) (offset: int): unit =
+ StringMap.iter
+ (fun key value
+ -> print_string (key ^ "\t");
+ print_int (value + offset);
+ print_string "\n")
+ scp
+;;
+
+let print_lexp_context (ctx: lexp_context): unit =
+ print_string " Context Print\n";
+
+ let rec impl (ctx2: lexp_context) (offset: int) =
+ let inner = _get_inner_scope ctx2 in
+ match ctx2 with
+ | (_, Some ct)
+ -> impl ct ((_get_offset ctx2) + offset);
+ (print_scope inner offset);
+ | _ -> (print_scope inner offset) in
+ (impl ctx 0)
+;;
\ No newline at end of file
=====================================
src/fmt.ml
=====================================
--- a/src/fmt.ml
+++ b/src/fmt.ml
@@ -1,20 +1,34 @@
(*
- * Kiwi Compiler
- *
- * Pierre Delaunay
+ * Typer Compiler
*
- * ---------------------------------------------------------------------------
+ * ---------------------------------------------------------------------------
*
+ * Copyright (C) 2011-2016 Free Software Foundation, Inc.
*
- *)
-
-
-(******************************************************************************
- * Print helper
+ * Author: Pierre Delaunay <pierre.delaunay(a)hec.ca>
+ * Keywords: languages, lisp, dependent types.
+ *
+ * This file is part of Typer.
+ *
+ * Typer is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ * Typer is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
*
- * Declare new print function which align printed values.
+ * You should have received a copy of the GNU General Public License along
+ * with this program. If not, see <http://www.gnu.org/licenses/>.
*
- *****************************************************************************)
+ * ---------------------------------------------------------------------------
+ *
+ * Description:
+ * Declare new print function which align printed values.
+ *
+ * ---------------------------------------------------------------------------*)
(* Compute the number of character needed to print an integer*)
let str_size_int value =
@@ -47,3 +61,30 @@ let lalign_print_string str nb =
print_string str;
make_line " " (nb - String.length str);
;;
+
+(* print n char 'c' *)
+let rec prerr_make_line c n =
+ prerr_string c;
+ if n >= 1 then (make_line c (n - 1));
+;;
+
+(* print an integer right-aligned *)
+let ralign_prerr_int value nb =
+ prerr_make_line " " (nb - (str_size_int value));
+ prerr_int value;
+;;
+
+let lalign_prerr_int value nb =
+ prerr_int value;
+ prerr_make_line " " (nb - (str_size_int value));
+;;
+
+let ralign_prerr_string str nb =
+ prerr_make_line " " (nb - String.length str);
+ prerr_string str;
+;;
+
+let lalign_prerr_string str nb =
+ prerr_string str;
+ prerr_make_line " " (nb - String.length str);
+;;
=====================================
tests/primary_debug.ml → src/grammar.ml
=====================================
--- a/tests/primary_debug.ml
+++ b/src/grammar.ml
@@ -5,7 +5,7 @@
*
* Copyright (C) 2011-2016 Free Software Foundation, Inc.
*
- * Author: Pierre Delaunay <pierre.delaunay(a)hec.ca>
+ * Author: Stefan Monnier <monnier(a)iro.umontreal.ca>
* Keywords: languages, lisp, dependent types.
*
* This file is part of Typer.
@@ -26,108 +26,62 @@
* ---------------------------------------------------------------------------
*
* Description:
- * print out read pexp (primary expression)
+ * Define the default Typer Grammar
*
* --------------------------------------------------------------------------- *)
-
-let rec debug_pexp_print pexp =
- match pexp with
- | Pimm(exp)
- ->
- | Pvar(p)
- ->
- | Phastype(l, exp2, exp1)
- ->
-;;
+(* FIXME: it should be possible to make something like "." bind tighter than
+ function application. *)
+(* FIXME: what about sections, as in "if_then e1 else_"? *)
-let debug_pexp_print_all pexp =
- List.iter (fun pt ->
- print_string " ";
- debug_pexp_print pt;
- print_string "\n";
- )
- pexp
-;;
-(* Language config *)
+module SMap
+ = Map.Make (struct type t = string let compare = String.compare end)
+
+type grammar = (int option * int option) SMap.t
let default_stt =
- let stt = Array.create 256 false
+ let stt = Array.make 256 false
in stt.(Char.code ';') <- true;
stt.(Char.code ',') <- true;
stt.(Char.code '(') <- true;
stt.(Char.code ')') <- true;
stt
-;;
-
-let default_grammar : grammar
- = List.fold_left (fun g (n, ll, rl) -> SMap.add n (ll, rl) g)
- SMap.empty
- [("^", Some 171, Some 159);
- ("/", Some 148, Some 160);
- ("-", Some 92, Some 110);
- ("+", Some 93, Some 111);
- ("!=", Some 94, Some 75);
- (">=", Some 95, Some 76);
- ("<=", Some 96, Some 77);
- (">", Some 97, Some 78);
- ("<", Some 98, Some 79);
- ("&&", Some 64, Some 81);
- ("||", Some 39, Some 51);
- (",", Some 26, Some 26);
- ("then", Some 1, Some 0);
- ("=", Some 99, Some 80);
- ("type", None, Some 27);
- (";", Some 15, Some 15);
- ("*", Some 137, Some 137);
- (":", Some 173, Some 115);
- ("]", Some 3, None);
- ("->", Some 126, Some 114);
- ("=>", Some 126, Some 113);
- ("≡>", Some 126, Some 112);
- ("in", Some 2, Some 53);
- ("else", Some 0, Some 52);
- ("|", Some 40, Some 40);
- (")", Some 4, None);
- ("[", None, Some 3);
- ("case", None, Some 28);
- ("lambda", None, Some 126);
- ("letrec", None, Some 2);
- ("let", None, Some 2);
- ("if", None, Some 1);
- ("(", None, Some 4);
- ]
-;;
-
-let main filename () =
-
- (* Todo read file from prog args *)
- (* get pretokens*)
- let pretoks = prelex_file filename in
-
- (* get sexp/tokens *)
- let toks = lex default_stt pretoks in
-
- (* get pexp *)
- let pxp = sexp_parse_all grm toks limit in
-
- (* print pxp *)
- debug_pexp_print_all pxp
-;;
-
-(* Command Line *)
-open Core.Std
-
-let command =
- Command.basic
- ~summary:"Print Compiler Debug Info"
- ~readme:(fun () -> "More detailed information")
- Command.Spec.(empty +> anon ("filename" %: string))
- main
-
-let () =
- Command.run ~version:"1.0" ~build_info:"RWO" command
-
-
-
+
+let default_grammar : grammar =
+ List.fold_left (fun g (n, ll, rl) -> SMap.add n (ll, rl) g)
+ SMap.empty
+ [("^", Some 171, Some 159);
+ ("/", Some 148, Some 160);
+ ("-", Some 92, Some 110);
+ ("+", Some 93, Some 111);
+ ("!=", Some 94, Some 75);
+ (">=", Some 95, Some 76);
+ ("<=", Some 96, Some 77);
+ (">", Some 97, Some 78);
+ ("<", Some 98, Some 79);
+ ("&&", Some 64, Some 81);
+ ("||", Some 39, Some 51);
+ (",", Some 26, Some 26);
+ ("then", Some 1, Some 0);
+ ("=", Some 99, Some 80);
+ ("type", None, Some 27);
+ (";", Some 15, Some 15);
+ ("*", Some 137, Some 137);
+ (":", Some 173, Some 115);
+ ("]", Some 3, None);
+ ("->", Some 126, Some 114);
+ ("=>", Some 126, Some 113);
+ ("=>", Some 126, Some 112);
+ ("in", Some 2, Some 53);
+ ("else", Some 0, Some 52);
+ ("|", Some 40, Some 40);
+ (")", Some 4, None);
+ ("[", None, Some 3);
+ ("case", None, Some 28);
+ ("lambda", None, Some 126);
+ ("letrec", None, Some 2);
+ ("let", None, Some 2);
+ ("if", None, Some 1);
+ ("(", None, Some 4);
+ ]
\ No newline at end of file
=====================================
src/lexp.ml
=====================================
--- a/src/lexp.ml
+++ b/src/lexp.ml
@@ -25,6 +25,7 @@ open Lexer
open Sexp
open Pexp
open Myers
+open Grammar
(* open Unify *)
(*************** DeBruijn indices for variables *********************)
@@ -52,6 +53,7 @@ type builtin =
| EqType
| LevelType
+
type ltype = lexp
and lexp =
| Imm of sexp (* Used for strings, ... *)
@@ -75,6 +77,7 @@ type ltype = lexp
* ltype (* The base inductive type over which we switch. *)
* (location * (arg_kind * vdef) option list * lexp) SMap.t
* lexp option (* Default. *)
+ | UnknownType of location (* This is easy to handle *)
(* | Susp of subst * lexp
* (\* For logical metavars, there's no substitution. *\)
* | Metavar of (location * string) * metakind * metavar ref
@@ -188,7 +191,8 @@ let builtins =
* includes "younger" bindings.
*)
-type env_elem = (db_offset, vdef, lexp option, ltype)
+
+type env_elem = (db_offset * vdef * lexp option * ltype)
type env_type = env_elem myers
let env_lookup_type (env : env_type) (v : vref) =
let ((_, rname), dbi) = v in
@@ -510,6 +514,7 @@ let conv_erase = true (* If true, conv ignores erased terms. *)
* decls1 decls2
* | (_, _) -> false *)
+(*
(* In non-recursion calls, `s' is always empty. *)
let lexp_conv_p env = lexp_conv_p env VMap.empty
@@ -576,11 +581,93 @@ and lexp_unparse e : pexp =
(* (internal_error "Can't print a Susp") *)
let lexp_print e = sexp_print (pexp_unparse (lexp_unparse e))
-
+<<<<<<< HEAD
+
+(* let rec lexp_type (env: (lexp option * lexp) VMap.t) e : lexp =
+ * let rec follow e =
+ * match e with
+ * | Var (_,v) -> vmap_getval v
+ * | Metavar (_,_,r) -> (match !r with MetaSet e -> follow e | _ -> e)
+ * | _ -> e
+ * and vmap_getval (v : var) =
+ * match VMap.find v env with (Some e, _) -> follow e
+ * | _ -> Var (dummy_location, v) in
+ * match e with
+ * | Sort (l, Stype e) -> Sort (l, Stype (SortLevel (SLsucc e)))
+ * | Sort (l, StypeOmega)
+ * -> msg_error l "TypeΩ doesn't have a type"; mk_meta_dummy env l
+ * | Sort (l, StypeLevel)
+ * -> msg_error l "TypeLevel doesn't have a type"; mk_meta_dummy env l
+ * | SortLevel _ -> Sort (lexp_location e, StypeLevel)
+ * | Imm (Integer _) -> type_int
+ * | Imm (Float _) -> type_float
+ * | Builtin (_,_,t) -> t
+ * (\* | Imm (String _) -> Var (dummy_location, var_string) *\)
+ * | Imm s -> let l = sexp_location s in
+ * msg_error l "Unrecognized sexp in lexp"; mk_meta_dummy env l
+ * | Var (_,name) -> snd (VMap.find name env)
+ * | Let (l, decls, body) ->
+ * lexp_type (List.fold_left (fun env ((_,v),e,t) ->
+ * VMap.add v (Some (Let (l, decls, e)), t) env)
+ * env decls)
+ * body
+ * | Arrow _ -> type0 (\* FIXME! *\)
+ * | Lambda (ak, ((l,v) as var),t,e) ->
+ * Arrow (ak, Some var, t, dummy_location,
+ * lexp_type (VMap.add v (None, t) env) e)
+ * | Call (f, args) ->
+ * let ft = lexp_type env f in
+ * let rec one_arg t (_,arg) =
+ * match lexp_whnf VMap.empty t with
+ * | Arrow (_, None, t1, _, t2) -> t2
+ * | Arrow (_, Some (_,v), t1, _, t2) ->
+ * Susp (VMap.add v arg VMap.empty, t2)
+ * | _ -> msg_error (lexp_location arg) "Too many arguments"; t
+ * in List.fold_left one_arg ft args
+ * | Inductive (_,t,_) -> t
+ * | Cons (e,(l,name)) ->
+ * (match lexp_whnf VMap.empty e with
+ * | Inductive (_,_,branches) ->
+ * (try SMap.find name branches
+ * with Not_found -> msg_error l ("No such constructor name `"^name^"'");
+ * mk_meta_dummy env l)
+ * | _ -> msg_error l "The constructor refers to a non-inductive type";
+ * mk_meta_dummy env l)
+ * | Case (_,_,_,_,Some default) -> lexp_type env default
+ * (\* | Case (_,_,(_,i, args, branch) :: _,_) ->
+ * * let ct = lexp_type env (vmap_getval cv) in
+ * * let rec one_arg (t,env) argo =
+ * * match t with
+ * * | Arrow (_, None, t1, _, t2) ->
+ * * (t2, VMap.add (snd argo) (None, t1) env)
+ * * | Arrow (_, Some (l,v), t1, _, t2) ->
+ * * (Susp (VMap.add v (mk_meta_dummy l) VMap.empty, t2),
+ * * VMap.add (snd argo) (None, t1) env)
+ * * | Susp (s, Arrow (ak,v,t1,l,t2)) ->
+ * * one_arg (Arrow (ak, v, Susp (s, t1), l, Susp (s, t2)), env) argo
+ * * | _ -> msg_error (fst argo) "Too many arguments";
+ * * (t, VMap.add (snd argo)
+ * * (None, mk_meta_dummy (fst argo))
+ * * env)
+ * * in let (_,env') = List.fold_left one_arg (ct,env) args
+ * * in lexp_type env' branch *\)
+ * | Case (l,_,_,_,None) -> mk_meta_dummy env l (\* Dead code? *\)
+ * | Susp (s, e) -> lexp_type env (lexp_whnf s e)
+ * | Metavar ((l,_),_,r)
+ * -> match !r with MetaSet e -> lexp_type env e
+ * | MetaUnset (_, Some t, _) -> t
+ * | _ -> msg_error l "Uninstantiated metavar of unknown type";
+ * mk_meta_dummy env l *)
+
+(*
+let rec lexp_parse (p : pexp) (env : (vdef * lexp option * ltype) myers) = *)
+*)
+
+(* FIXME
type senv_type = (db_revindex SMap.t * db_index)
let senv_lookup senv s : db_index =
let (m, i) = senv in
- i - SMap.find s senv
+ i - SMap.find s senv *)
(* Parsing a Pexp into an Lexp is really "elaboration", i.e. it needs to
* infer the types and perform macro-expansion. For won't really
@@ -598,7 +685,10 @@ let senv_lookup senv s : db_index =
* - use lexp_p_infer for destructors, and use lexp_p_check for constructors.
* - use lexp_p_check whenever you can.
*)
-let rec lexp_p_infer (env : env_type) (p : pexp) : lexp * ltype = ?
+
+let rec lexp_p_infer (env : env_type) (p : pexp) : lexp * ltype =
+ (UnknownType(dummy_location), UnknownType(dummy_location))
+
and lexp_p_check (env : env_type) (p : pexp) (t : ltype) : lexp =
match p with
| _
=====================================
src/lparse.ml
=====================================
--- /dev/null
+++ b/src/lparse.ml
@@ -0,0 +1,297 @@
+(*
+ * Typer Compiler
+ *
+ * ---------------------------------------------------------------------------
+ *
+ * Copyright (C) 2011-2016 Free Software Foundation, Inc.
+ *
+ * Author: Pierre Delaunay <pierre.delaunay(a)hec.ca>
+ * Keywords: languages, lisp, dependent types.
+ *
+ * This file is part of Typer.
+ *
+ * Typer is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ * Typer is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * ---------------------------------------------------------------------------
+ *
+ * Description:
+ * parse pexp expression into lexp
+ *
+ * --------------------------------------------------------------------------- *)
+
+open Util
+open Sexp
+open Pexp
+open Lexp
+open Grammar
+open Debruijn
+open Fmt
+
+(* Shortcut => Create a Var *)
+let make_var name index loc =
+ Var(((loc, name), index))
+;;
+
+let not_implemented_error () =
+ internal_error "not implemented"
+;;
+
+let lexp_error = msg_error "LEXP"
+let lexp_warning = msg_warning "LEXP"
+
+(* Vdef is exactly similar to Pvar but need to modify our ctx *)
+let pvar_to_vdef p =
+ p
+;;
+(* PEXP is not giving SEXP types this is why types are always unknown *)
+
+(*
+ * The main job of lexp (currently) is to determine variable name (index)
+ * and to regroup type specification with their variable
+ *)
+
+let rec lexp_parse (p: pexp) (ctx: lexp_context): (lexp * lexp_context) =
+ (* So I don't have to extract it *)
+ let tloc = pexp_location p in
+ match p with
+ (* Block/String/Integer/Float *)
+ | Pimm value -> Imm(value), ctx
+
+ (* Symbol i.e identifier /!\ A lot of Pvar are not variables /!\ *)
+ | Pvar (loc, name) ->
+ let idx = get_var_index name ctx in
+ (* This should be an error but we accept it for debugging *)
+ if idx < 0 then
+ lexp_warning tloc ("Variable: '" ^ name ^ "' does not exist");
+ (make_var name (idx + 1) loc), ctx;
+
+ (* Let, Variable declaration + local scope *)
+ | Plet(loc, decls, body) -> (* /!\ HERE *)
+ let decl, nctx = lexp_parse_let decls (add_scope ctx) in
+ let bdy, nctx = lexp_parse body nctx in
+ (* print_lexp_context nctx; *)
+ (* Send back old context as we exit the inner scope *)
+ Let(tloc, decl, bdy), ctx
+
+ (* ->/=> *)
+ | Parrow (kind, Some var, tp, loc, expr) ->
+ let nvar = pvar_to_vdef var in (* /!\ HERE *)
+ let ltyp, ctx = lexp_parse tp ctx in
+ let lxp, ctx = lexp_parse expr ctx in
+ Arrow(kind, Some nvar, ltyp, tloc, lxp), ctx
+
+ | Parrow (kind, None, tp, loc, expr) ->
+ let ltyp, ctx = lexp_parse tp ctx in
+ let lxp, ctx = lexp_parse expr ctx in
+ Arrow(kind, None, ltyp, tloc, lxp), ctx
+
+ (* *)
+ | Plambda (kind, var, Some ptype, body) ->
+ let nvar = pvar_to_vdef var in (* /!\ HERE *)
+ let ltyp, ctx = lexp_parse ptype ctx in
+ let lbody, ctx = lexp_parse body ctx in
+ Lambda(kind, nvar, ltyp, lbody), ctx
+
+ | Plambda (kind, var, None, body) ->
+ let nvar = pvar_to_vdef var in (* /!\ HERE *)(* /!\ Missing Type *)
+ let lbody, ctx = lexp_parse body ctx in
+ Lambda(kind, nvar, UnknownType(tloc), lbody), ctx
+
+ (* Function Call *)
+ | Pcall (fname, _args) ->
+ let fname, ctx = lexp_parse fname ctx in
+ let pargs = pexp_parse_all _args in
+ let largs, fctx = lexp_parse_all pargs ctx in
+
+ (* Make everything explicit for now *)
+ let new_args = List.map (fun g -> (Aexplicit, g)) largs in
+
+ Call(fname, new_args), ctx
+
+ (* Pcons *)
+ (* Pcase *)
+ (* Pinductive *) (* Pinductive Pexp implementation is not ready *)
+
+ | _
+ -> UnknownType(tloc), ctx
+
+
+and lexp_parse_let decls ctx =
+
+ (* Merge Type info and declaration together *)
+ (* We use a list because order matters and Maps reorder elements *)
+ let rec is_equal target (p:(vdef * pexp option * pexp option)): bool =
+ let ((_, name), _, _) = p in
+ if name == target then true else false in
+
+ let rec loop (decls: (pvar * pexp * bool) list) merged:
+ (vdef * pexp option * pexp option) list =
+
+ (* we cant evaluate here because variable are not in the environment *)
+ match decls with
+ | [] -> List.rev merged
+ | hd::tl ->
+ match hd with
+ (* Type Info: Var:Type *)
+ | ((loc, name), type_info, true) -> begin
+ try
+ (* If found its means the instruction was declared
+ * before the type info. Should we allow this? *)
+ let (vd, inst, _) = List.find (is_equal name) merged in
+ let new_decl = (vd, inst, Some type_info) in
+ (loop tl (new_decl::merged))
+ with Not_found ->
+ let new_decl = (loc, name), None, Some type_info in
+ (loop tl (new_decl::merged)) end
+
+ (* Instruction: Var = expr *)
+ | ((loc, name), inst, false) -> begin
+ try
+ let (vd, _, ptyp) = List.find (is_equal name) merged in
+ let new_decl = (vd, Some inst, ptyp) in
+ (loop tl (new_decl::merged))
+ with Not_found ->
+ let new_decl = ((loc, name), Some inst, None) in
+ (loop tl (new_decl::merged)) end in
+
+ let decls = loop decls [] in
+
+ (* Add Each Variable to the environment *)
+ let rec add_var_env decls ctx =
+ match decls with
+ | [] -> ctx
+ | hd::tl -> begin
+ match hd with
+ (* Unused variable: No Instruction *)
+ (* Warning will be printed later *)
+ | ((loc, name), None, _) -> add_var_env tl ctx
+ | ((loc, name), _, _) ->
+ let ctx = add_variable name loc ctx in
+ add_var_env tl ctx end in
+
+ let nctx = add_var_env decls ctx in
+
+ (* lexp_parse instruction and types *)
+ let rec parse_decls decls ctx acc =
+ match decls with
+ | [] -> (List.rev acc), ctx
+ | hd::tl -> begin
+ match hd with
+ | ((loc, name), Some pinst, Some ptype) ->
+ let linst, nctx = lexp_parse pinst ctx in
+ let ltyp, nctx = lexp_parse ptype nctx in
+ let nacc = ((loc, name), linst, ltyp)::acc in
+ (parse_decls tl nctx nacc)
+ | ((loc, name), Some pinst, None) ->
+ let linst, nctx = lexp_parse pinst ctx in
+ (* This is where UnknownType are introduced *)
+ (* need Inference HERE *)
+ let nacc = ((loc, name), linst, UnknownType(loc))::acc in
+ (parse_decls tl nctx nacc)
+ (* Skip the variable *)
+ | ((loc, name), None, _) ->
+ lexp_warning loc "Unused Variable";
+ (parse_decls tl ctx acc)
+ end in
+
+ parse_decls decls nctx []
+
+and lexp_parse_all (p: pexp list) (ctx: lexp_context):
+ (lexp list * lexp_context) =
+ let rec loop (plst: pexp list) ctx (acc: lexp list) =
+ match plst with
+ | [] -> ((List.rev acc), ctx)
+ | _ -> let lxp, new_ctx = lexp_parse (List.hd plst) ctx in
+ (loop (List.tl plst) new_ctx (lxp::acc)) in
+ (loop p ctx [])
+;;
+
+(* Print back in CET (Close Enough Typer) easier to read *)
+ (* pretty ? * indent level * print_type? *)
+type print_context = (bool * int * bool)
+
+let rec lexp_print_adv opt exp =
+ let slexp_print = lexp_print_adv opt in (* short_lexp_print *)
+ let (pty, indent, prtp) = opt in
+ match exp with
+ | Imm(value) -> sexp_print value
+ | Var ((loc, name), idx) ->
+ print_string name;
+ if idx > 0 then begin
+ print_string "("; print_int idx; print_string ")"; end
+
+ | Let (_, decls, body) ->
+ print_string "let"; lexp_print_decls (pty, indent + 1, prtp) decls;
+ if pty then make_line " " (indent * 4 + 4);
+ print_string " in "; lexp_print_adv (pty, indent + 2, prtp) body
+
+ | Arrow(kind, Some (_, name), tp, loc, expr) ->
+ slexp_print tp; print_string ": "; print_string name;
+ print_string " -> "; slexp_print expr;
+
+ | Arrow(kind, None, tp, loc, expr) ->
+ slexp_print tp; print_string " -> "; slexp_print expr;
+
+ | Lambda(kind, (loc, name), ltype, lbody) ->
+ print_string "lambda ("; print_string (name ^ ": ");
+ slexp_print ltype; print_string ") -> "; slexp_print lbody;
+
+ | Call(fname, args) -> begin (* /!\ Partial Print *)
+ (* get function name *)
+ let str = match fname with
+ | Var((_, name), _) -> name
+ | _ -> "unkwn" in
+
+ let print_arg arg = match arg with | (kind, lxp) ->
+ lexp_print_adv (pty, 0, prtp) lxp in
+
+ let print_binop op lhs rhs =
+ print_arg lhs; print_string op; print_arg rhs in
+
+ match (str, args) with
+ (* Special Operator *)
+ | ("_=_", [lhs; rhs]) -> print_binop " = " lhs rhs
+ | ("_+_", [lhs; rhs]) -> print_binop " + " lhs rhs
+ | ("_-_", [lhs; rhs]) -> print_binop " - " lhs rhs
+ | ("_/_", [lhs; rhs]) -> print_binop " / " lhs rhs
+ | ("_*_", [lhs; rhs]) -> print_binop " * " lhs rhs
+ (* not an operator *)
+ | _ ->
+ print_string ("(" ^ str);
+ List.iter (fun arg -> print_string " "; print_arg arg) args;
+ print_string ")" end
+
+ (* debug catch all *)
+ | UnknownType (loc) -> print_string "unkwn";
+ | _ -> print_string "expr"
+
+and lexp_print_decls opt decls =
+ let (pty, indent, prtp) = opt in
+ let print_type nm tp =
+ print_string (" " ^ nm ^ ": "); lexp_print_adv opt tp;
+ print_string ";"; in
+
+ List.iteri (fun idx g -> match g with
+ | ((loc, name), expr, ltyp) ->
+ if pty && idx > 0 then make_line " " (indent * 4);
+ if prtp then print_type name ltyp; print_string " ";
+ print_string (name ^ " = ");
+ lexp_print_adv opt expr; print_string ";";
+ if pty then print_string "\n")
+ decls
+;;
+
+
+let lexp_print = lexp_print_adv (false, 0, true)
+
=====================================
src/pexp.ml
=====================================
--- a/src/pexp.ml
+++ b/src/pexp.ml
@@ -23,9 +23,13 @@ this program. If not, see <http://www.gnu.org/licenses/>. *)
open Util
open Sexp
+let pexp_error = msg_error "PEXP"
+
(*************** The Pexp Parser *********************)
type arg_kind = Aexplicit | Aimplicit | Aerasable (* eraseable ⇒ implicit. *)
+
+(* This is Dangerously misleading since pvar is NOT pexp but Pvar is *)
type pvar = symbol
(* type sort = Type | Ext *)
(* type tag = string *)
@@ -94,7 +98,7 @@ let rec pexp_parse (s : sexp) : pexp =
| Node (Symbol (start, "let_in_"), [decls; body])
-> Plet (start, pexp_p_decls decls, pexp_parse body)
| Node (Symbol (start, ("let_in_" | "let" | "let_")), _)
- -> msg_error start "Unrecognized let expression"; Pmetavar (start, "_")
+ -> pexp_error start "Unrecognized let expression"; Pmetavar (start, "_")
(* arrow *)
| Node (Symbol (start, (("_->_" | "_=>_" | "_≡>_") as arw)), [t1; t2])
-> let kind = (match arw with
@@ -104,7 +108,7 @@ let rec pexp_parse (s : sexp) : pexp =
-> Parrow (kind, Some v, pexp_parse t1, start, pexp_parse t2)
| _ -> Parrow (kind, None, pexp_parse t1, start, pexp_parse t2))
| Node (Symbol (start, ("_->_" | "_=>_" | "_≡>_")), _)
- -> msg_error start "Unrecognized arrow expression"; Pmetavar (start, "_")
+ -> pexp_error start "Unrecognized arrow expression"; Pmetavar (start, "_")
(* lambda *)
| Node (Symbol (start,(("lambda_->_" | "lambda_=>_" | "lambda_≡>_") as arw)),
[arg; body])
@@ -117,37 +121,38 @@ let rec pexp_parse (s : sexp) : pexp =
| Symbol v -> (v, None)
| Node (Symbol (_, "_:_"), [Symbol v; t])
-> (v, Some (pexp_parse t))
- | _ -> msg_error start "Unrecognized lambda argument";
+ | _ -> pexp_error start "Unrecognized lambda argument";
((dummy_location, "unrecognized_arg"), None)
in Plambda (kind, v, t, pbody))
(sexp_p_list arg ["_:_"])
(pexp_parse body)
| Node (Symbol (start, "lambda_"), _)
- -> msg_error start "Unrecognized lambda expression"; Pmetavar (start, "_")
+ -> pexp_error start "Unrecognized lambda expression"; Pmetavar (start, "_")
(* inductive type *)
| Node (Symbol (start, "inductive_"), t :: cases)
-> let (name, args) = match t with
- | Node (Symbol s, args) -> (s, args)
- | Symbol s -> (s, [])
- | _ -> msg_error start "Unrecognized inductive type name";
+ | Node (Symbol s, args) -> (s, args) (* This a constructor *)
+ | Symbol s -> (s, []) (* This is a Label *)
+ | _ -> pexp_error start "Unrecognized inductive type name";
((dummy_location, ""), []) in
let pcases =
List.fold_right
(fun case pcases
-> match case with
- | Node (Symbol s, cases)
+ (* read Constructor name + args => Type ((Symbol * args) list) *)
+ | Node (Symbol s, cases)
-> (s, List.map pexp_p_ind_arg cases)::pcases
- | _ -> msg_error (sexp_location case)
+ | _ -> pexp_error (sexp_location case)
"Unrecognized constructor declaration"; pcases)
cases [] in
Pinductive (name, List.map pexp_p_formal_arg args, pcases)
| Node (Symbol (start, "inductive_"), _)
- -> msg_error start "Unrecognized inductive type"; Pmetavar (start, "_")
+ -> pexp_error start "Unrecognized inductive type"; Pmetavar (start, "_")
(* constructor *)
| Node (Symbol (start, "inductive-cons"), [Symbol tname; Symbol tag])
-> Pcons (tname, tag)
| Node (Symbol (start, "cons_"), _)
- -> msg_error start "Unrecognized constructor call"; Pmetavar (start, "_")
+ -> pexp_error start "Unrecognized constructor call"; Pmetavar (start, "_")
(* cases analysis *)
| Node (Symbol (start, "case_"),
[Node (Symbol (_, "_|_"), e :: cases)])
@@ -155,12 +160,12 @@ let rec pexp_parse (s : sexp) : pexp =
| Node (Symbol (_, "_=>_"), [pat; code])
-> (pexp_p_pat pat, pexp_parse code)
| _ -> let l = (sexp_location branch) in
- msg_error l "Unrecognized simple case branch";
+ pexp_error l "Unrecognized simple case branch";
(Ppatany l, Pmetavar (l, "_"))
in Pcase (start, pexp_parse e, List.map parse_case cases)
| Node (Symbol (start, "case_"), [e]) -> Pcase (start, pexp_parse e, [])
| Node (Symbol (start, "case_"), _)
- -> msg_error start "Unrecognized case expression"; Pmetavar (start, "_")
+ -> pexp_error start "Unrecognized case expression"; Pmetavar (start, "_")
(* | Node (Symbol (_, "(_)"), [e]) -> pexp_parse e *)
| Node (f, []) -> pexp_parse f
| Node (f, args) -> Pcall (pexp_parse f, args)
@@ -184,9 +189,8 @@ and pexp_p_formal_arg arg : (arg_kind * pvar * pexp option) =
| Node (Symbol (_, ":"), [Symbol s; e])
-> (Aexplicit, s, Some (pexp_parse e))
| Symbol s -> (Aexplicit, s, None)
- | _ -> (msg_error (sexp_location arg)
- "Unrecognized formal arg";
- (Aexplicit, (sexp_location arg, "{arg}"), None))
+ | _ -> (pexp_error (sexp_location arg) "Unrecognized formal arg");
+ (Aexplicit, (sexp_location arg, "{arg}"), None)
and pexp_u_formal_arg (arg : arg_kind * pvar * pexp option) =
match arg with
@@ -235,7 +239,7 @@ and pexp_p_pat_arg (s : sexp) = match s with
| Node (Symbol (_, "_:≡_"), [Symbol f; Symbol s])
-> (Some (Aerasable, f), Ppatvar s)
| _ -> let loc = sexp_location s in
- msg_error loc "Unknown pattern arg";
+ pexp_error loc "Unknown pattern arg";
(None, Ppatany loc)
and pexp_u_pat_arg (arg : (arg_kind * symbol) option * ppat) : sexp =
@@ -254,7 +258,7 @@ and pexp_p_pat (s : sexp) : ppat = match s with
| Node (Symbol c, args)
-> Ppatcons (c, List.map pexp_p_pat_arg args)
| _ -> let l = sexp_location s in
- msg_error l "Unknown pattern"; Ppatany l
+ pexp_error l "Unknown pattern"; Ppatany l
and pexp_u_pat (p : ppat) : sexp = match p with
| Ppatany l -> Symbol (l, "_")
@@ -268,16 +272,16 @@ and pexp_p_decls e =
-> List.concat (List.map pexp_p_decls decls)
| Node (Symbol (_, "_:_"), [Symbol s; t]) -> [(s, pexp_parse t, true)]
| Node (Symbol (_, "_=_"), [Symbol s; t]) -> [(s, pexp_parse t, false)]
- (* | Node (Symbol (_, "_=_"), [Node (Symbol s, args); t]) ->
- * let rec mkfun args =
- * match args with
- * | [] -> pexp_parse t
- * | (Symbol s :: args) -> Plambda (s, None, mkfun args)
- * | (arg :: args) -> msg_error (sexp_location arg)
- * "Unknown argument format";
- * mkfun args
- * in [(s, mkfun args, false)] *)
- | _ -> msg_error (sexp_location e) ("Unknown declaration"); []
+ | Node (Symbol (_, "_=_"), [Node (Symbol s, args); t]) ->
+ let rec mkfun args =
+ match args with
+ | [] -> pexp_parse t (* Plambda of arg_kind * pvar * pexp option * pexp *)
+ | (Symbol s :: args) -> Plambda(Aexplicit, s, None, mkfun args)
+ | (arg :: args) -> pexp_error (sexp_location arg)
+ "Unknown argument format";
+ mkfun args
+ in [(s, mkfun args, false)]
+ | _ -> pexp_error (sexp_location e) ("Unknown declaration"); []
and pexp_unparse (e : pexp) : sexp =
match e with
@@ -309,7 +313,8 @@ and pexp_unparse (e : pexp) : sexp =
[Symbol v; pexp_unparse t]));
pexp_unparse body])
| Pcall (f, args) -> Node (pexp_unparse f, args)
- | Pinductive (_, t, branches) ->
+ (* Pinductive *)
+ | Pinductive (s, t, branches) ->
Node (Symbol (dummy_location, "inductive_"),
sexp_u_list (List.map pexp_u_formal_arg t)
:: List.map (fun ((l,name) as s, types)
@@ -340,4 +345,7 @@ and pexp_u_decls ds =
let pexp_print e = sexp_print (pexp_unparse e)
-
+(* Parse All Pexp as a list *)
+let pexp_parse_all (nodes: sexp list) =
+ List.map pexp_parse nodes
+;;
=====================================
src/prelexer.ml
=====================================
--- a/src/prelexer.ml
+++ b/src/prelexer.ml
@@ -22,6 +22,8 @@ this program. If not, see <http://www.gnu.org/licenses/>. *)
open Util
+let prelexer_error = msg_error "PRELEXER"
+
type pretoken =
| Pretoken of location * string
| Prestring of location * string
@@ -66,7 +68,7 @@ let rec prelex (file : string) (fin : in_channel) ln ctx acc
| '"' -> (* A string. *)
let rec prestring bp cp chars =
if bp >= limit then
- (msg_error {file=file; line=ln; column=cpos}
+ (prelexer_error {file=file; line=ln; column=cpos}
"Unterminated string";
nextline ctx
(Prestring ({file=file; line=ln; column=cpos}, "")
@@ -80,7 +82,7 @@ let rec prelex (file : string) (fin : in_channel) ln ctx acc
:: acc)
| '\\' ->
(if bpos + 1 >= limit then
- (msg_error {file=file; line=ln; column=cpos}
+ (prelexer_error {file=file; line=ln; column=cpos}
"Unterminated string";
nextline ctx
(Prestring ({file=file; line=ln; column=cpos},
@@ -92,7 +94,7 @@ let rec prelex (file : string) (fin : in_channel) ln ctx acc
| 'n' -> prestring (bp+2) (cp+2) ('\n' :: chars)
| 'r' -> prestring (bp+2) (cp+2) ('\r' :: chars)
| ('u' | 'U') ->
- msg_error {file=file; line=ln; column=cp}
+ prelexer_error {file=file; line=ln; column=cp}
"Unimplemented unicode escape";
prestring (bp+2) (cp+2) chars
| char -> prestring (bp+2) (cp+2) (char :: chars))
@@ -107,7 +109,7 @@ let rec prelex (file : string) (fin : in_channel) ln ctx acc
List.rev acc,
{file=file; line=ln; column=(cpos + 1)})
:: sacc)
- | _ -> (msg_error {file=file; line=ln; column=cpos}
+ | _ -> (prelexer_error {file=file; line=ln; column=cpos}
"Unmatched closing brace";
prelex' ctx (bpos+1) (cpos+1) acc))
| char -> (* A pretoken. *)
@@ -130,13 +132,16 @@ let rec prelex (file : string) (fin : in_channel) ln ctx acc
match ctx with
| [] -> List.rev acc
| ((ln, cpos, _, _) :: ctx) ->
- (msg_error {file=file; line=ln; column=cpos}
+ (prelexer_error {file=file; line=ln; column=cpos}
"Unmatched opening brace"; List.rev acc)
let prelex_file file =
let fin = open_in file
in prelex file fin 1 [] [] (* Traditionally, line numbers start at 1 :-( *)
+
+let prelex_string str =
+ prelex "string" str 1 [] []
let rec pretokens_print pretokens =
List.iter (fun pt ->
=====================================
src/sexp.ml
=====================================
--- a/src/sexp.ml
+++ b/src/sexp.ml
@@ -31,6 +31,9 @@ this program. If not, see <http://www.gnu.org/licenses/>. *)
open Util
open Prelexer
+open Grammar
+
+let sexp_error = msg_error "SEXP"
type integer = (* Num.num *) int
type symbol = location * string
@@ -86,13 +89,6 @@ let rec sexp_location s =
(*************** The Sexp Parser *********************)
-(* FIXME: it should be possible to make something like "." bind tighter than
- function application. *)
-(* FIXME: what about sections, as in "if_then e1 else_"? *)
-
-module SMap
- = Map.Make (struct type t = string let compare = String.compare end)
-type grammar = (int option * int option) SMap.t
(* If true, infix symbols like "_;_" will be turned into ";_" or "_;"
* if they had no right or left argument.
@@ -160,7 +156,7 @@ let rec sexp_parse (g : grammar) (rest : sexp list)
* It might simply be a postfix symbol that binds very tightly.
* We currently signal an error because it's more common for
* it to be a closer with missing opener. *)
- -> msg_error l ("Lonely postfix/closer \""^name^"\"");
+ -> sexp_error l ("Lonely postfix/closer \""^name^"\"");
sexp_parse rest' level op largs
[mk_node [(l,name);(l,"")] [] rargs true]
| (Some ll, Some rl) when ll > level
@@ -223,4 +219,15 @@ let sexp_u_list (ss : sexp list) : sexp =
| [] -> Epsilon
| [s] -> s
| (s :: ss) -> Node (s, ss)
-
+
+(* Parse all the Sexp *)
+let sexp_parse_all_to_list grm tokens limit =
+ let rec sexp_parse_impl grm tokens limit acc =
+ match tokens with
+ (* We are done parsing *)
+ | [] -> List.rev acc (* What does list rev do ? *)
+ (* Keep going *)
+ | _ -> let (sxp, rest) = sexp_parse_all grm tokens limit in
+ sexp_parse_impl grm rest limit (sxp :: acc) in
+ sexp_parse_impl grm tokens limit []
+;;
=====================================
src/util.ml
=====================================
--- a/src/util.ml
+++ b/src/util.ml
@@ -27,20 +27,41 @@ let dummy_location = {file=""; line=0; column=0}
type bottom = | B_o_t_t_o_m_ of bottom
-let msg_message kind location msg =
- prerr_string location.file;
- prerr_char ':';
- prerr_int location.line;
- prerr_char ':';
- prerr_int location.column;
- prerr_string (":"^kind^": ");
- prerr_string msg;
- prerr_newline ()
-
-let msg_error = msg_message "Error"
-let msg_info = msg_message "Info"
+(* print debug info *)
+let print_loc (loc: location) =
+ (*print_string loc.file; *) (* Printing the file is too much*)
+ print_string "ln ";
+ Fmt.ralign_print_int loc.line 3;
+ print_string ", cl ";
+ Fmt.ralign_print_int loc.column 3;
+;;
+
+(* print debug info *)
+let prerr_loc (loc: location) =
+ (*print_string loc.file; *) (* Printing the file is too much*)
+ prerr_string "ln ";
+ Fmt.ralign_prerr_int loc.line 3;
+ prerr_string ", cl ";
+ Fmt.ralign_prerr_int loc.column 3;
+;;
+
+(* File is not printed because currently we parse only one file... *)
+(* Section is the name of the compilation step [for debugging] *)
+(* 'prerr' output is ugly *)
+let msg_message kind section (loc: location) msg =
+ print_string (" " ^ kind);
+ print_string " ["; print_loc loc; print_string "] ";
+ print_string (section ^ " ");
+ print_string msg;
+ print_newline ()
+
+let msg_error = msg_message "[!] Error "
+let msg_info = msg_message "[?] Info "
+let msg_warning = msg_message "/!\\ Warning "
let string_implode chars = String.concat "" (List.map (String.make 1) chars)
exception Internal_error of string
let internal_error s = raise (Internal_error s)
+
+
=====================================
tests/debruijn_test.ml
=====================================
--- /dev/null
+++ b/tests/debruijn_test.ml
@@ -0,0 +1,32 @@
+(* TODO make some real test *)
+open Debruijn
+open Util
+
+let main () =
+ (* Tests *)
+ (* Create a new scope: global scope *)
+ let loc = dummy_location in
+ let g0 = make_context in
+ let g1 = add_variable "a" loc g0 in
+ let g2 = add_variable "a" loc g1 in
+ let g3 = add_variable "b" loc g2 in
+ let g4 = add_variable "c" loc g3 in
+ let g5 = add_variable "d" loc g4 in
+
+ (* we enter a let or whatever *)
+ let l0 = add_scope g5 in
+ let l1 = add_variable "a" loc l0 in
+ let l2 = add_variable "e" loc l1 in
+
+ (* Testing is done *)
+ print_string "Inner Context\n";
+ print_lexp_context l2;
+
+ (* We exit the scope *)
+ print_string "Outer Context\n";
+ print_lexp_context g5
+;;
+
+
+main ()
+;;
\ No newline at end of file
=====================================
tests/debug.ml
=====================================
--- a/tests/debug.ml
+++ b/tests/debug.ml
@@ -27,113 +27,149 @@
*
* Description:
* Provide helper functions to print out
- * extracted token
- * extracted expression
+ * extracted Pretoken
+ * extracted Sexp
*
* --------------------------------------------------------------------------- *)
(* removes some warnings *)
open Util
-
-(* print debug info *)
-let print_loc (loc : Util.location) =
- print_string loc.file;
- print_string ": ln ";
- Fmt.ralign_print_int loc.line 3;
- print_string ", cl ";
- Fmt.ralign_print_int loc.column 3;
-;;
-
+open Prelexer
+open Lexer
+open Sexp
+open Pexp
+open Lexp
+open Lparse
-(*open Token
-open Token
-
-(* Print token with debug info *)
-let print_token tok =
- (* Shortcut *)
- let lalign str = Fmt.lalign_print_string str 20 in
-
- (* When we need to print only the name *)
- let quick_print name loc =
- lalign name;
- print_string "["; print_loc loc; print_string "] ";
- print_string "\n" in
-
- let long_print name loc elem =
- lalign name;
- print_string "["; print_loc loc; print_string "] ";
- print_string "'";
- print_string elem;
- print_string "'\n" in
+(* Print aPretokens *)
+let rec debug_pretokens_print pretoken =
+ print_string " ";
+ let print_info msg loc =
+ print_string msg;
+ print_string "["; print_loc loc; print_string "]\t" in
- let print_kwd name loc ch =
- lalign name;
- print_string "["; print_loc loc; print_string "] ";
- print_char ch;
- print_string "\n" in
-
- let print_float name loc ch =
- lalign name;
- print_string "["; print_loc loc; print_string "] ";
- print_float ch;
- print_string "\n" in
-
- let print_integer name loc ch =
- lalign name;
- print_string "["; print_loc loc; print_string "] ";
- print_int ch;
- print_string "\n" in
-
- (* Print tokens *)
- match tok with
- | Token.Arw(loc, str) -> long_print "Arw" loc str;
- | Token.Assign(loc, str) -> long_print "Assign" loc str;
- | Token.Colon(loc, str) -> long_print "Colon" loc str;
- | Token.Lambda(loc) -> quick_print "Lambda" loc;
- | Token.Case(loc) -> quick_print "Case" loc;
- | Token.Inductive(loc) -> quick_print "Inductive" loc;
- | Token.Let(loc) -> quick_print "Let" loc;
- | Token.In(loc) -> quick_print "In" loc;
- | Token.Ident(loc, str) -> long_print "Identifier" loc str;
- | Token.Kwd(loc, ch) -> print_kwd "Kwd" loc ch;
- | Token.Float(loc, value) -> print_float "Float" loc value;
- | Token.Integer(loc, value) -> print_integer "Integer" loc value;
- | Token.String(loc, str) -> long_print "String" loc str;
+ match pretoken with
+ | Preblock(loc, pts,_)
+ -> print_info "Preblock: " loc;
+ print_string "{"; pretokens_print pts; print_string " }"
+
+ | Pretoken(loc, str)
+ -> print_info "Pretoken: " loc;
+ print_string ("'" ^ str ^ "'");
+
+ | Prestring(loc, str)
+ -> print_info "Prestring: " loc;
+ print_string ("\"" ^ str ^ "\"");
;;
-
-(* Lexer print
- *--------------------------------------------------*)
-
-(* Print the list of token *)
-let debug_lex file_name =
- let file_stream = open_in file_name in
-
- (* Create a stream of tokens *)
- let lex_stream = Lexer.lex file_name (Stream.of_channel file_stream) in
-
- (* Print each tokens *)
- Stream.iter (fun tok -> print_token tok) lex_stream;
+(* Print a List of Pretokens *)
+let rec debug_pretokens_print_all pretokens =
+ List.iter (fun pt -> debug_pretokens_print pt; print_string "\n") pretokens
+;;
+
+(* Sexp Print *)
+let rec debug_sexp_print sexp =
+ let print_info msg loc =
+ print_string msg;
+ print_string "["; print_loc loc; print_string "]\t" in
+ match sexp with
+ | Epsilon
+ -> print_string "Epsilon " (* "ε" *)
+
+ | Block(loc, pts, _)
+ -> print_info "Block: " loc;
+ print_string "{"; pretokens_print pts; print_string " }"
+
+ | Symbol(loc, name)
+ -> print_info "Symbol: " loc; print_string name
+
+ | String(loc, str)
+ -> print_info "String: " loc;
+ print_string "\""; print_string str; print_string "\""
+
+ | Integer(loc, n)
+ -> print_info "Integer: " loc; print_int n
+
+ | Float(loc, x)
+ -> print_info "Float: " loc; print_float x
+
+ | Node(f, args)
+ -> print_info "Node: " (sexp_location f);
+ sexp_print f; print_string " \t ";
+ List.iter (fun sexp -> sexp_print sexp; print_string " @ ")
+ args;
+ print_string " "
+;;
+
+(* Print a list of sexp *)
+let debug_sexp_print_all tokens =
+ List.iter (fun pt ->
+ print_string " ";
+ debug_sexp_print pt;
+ print_string "\n";)
+ tokens
;;
-(* Parser print
- *--------------------------------------------------(**)
-let debug_parser file_name =
- let file_stream = open_in file_name in
+(* Print a Pexp with debug info *)
+let debug_pexp_print pexp =
+ print_string " ";
+ let l = pexp_location pexp in
+ let print_info msg loc pex =
+ print_string msg; print_string "[";
+ print_loc loc;
+ print_string "]\t";
+ pexp_print pexp in
+ match pexp with
+ | Pimm _ -> print_info "Pimm " l pexp
+ | Pvar (_,_) -> print_info "Pvar " l pexp
+ | Phastype (_,_,_) -> print_info "Phastype " l pexp
+ | Pmetavar (_, _) -> print_info "Pmetavar " l pexp
+ | Plet (_, _, _) -> print_info "Plet " l pexp
+ | Parrow (_, _, _, _, _) -> print_info "Parrow " l pexp
+ | Plambda (_,_, _, _) -> print_info "Plambda " l pexp
+ | Pcall (_, _) -> print_info "Pcall " l pexp
+ | Pinductive (_, _, _) -> print_info "Pinductive " l pexp
+ | Pcons (_,_) -> print_info "Pcons " l pexp
+ | Pcase (_, _, _) -> print_info "Pcase " l pexp
+ | _ -> print_info "Not Impl " l pexp
+;;
- (* Create a stream of tokens *)
- let lex_stream = Lexer.lex file_name (Stream.of_channel file_stream) in
-
- (* Parse token's stream *)
- Toplevel.main_loop lex_stream
-;; **)
+(* Print a list of pexp *)
+let debug_pexp_print_all pexps =
+ List.iter
+ (fun px ->
+ debug_pexp_print px;
+ print_string "\n")
+ pexps
+;;
+(* Print lexp with debug info *)
+let debug_lexp_print lxp =
+ print_string " ";
+ let print_info msg loc expr=
+ print_string msg; print_string "[";
+ print_loc loc;
+ print_string "]\t";
+ lexp_print lxp in
+ match lxp with
+ | Var((loc, _), _) -> print_info "Var " loc lxp
+ | Imm(s) -> print_info "Imm " dummy_location lxp
+ | Let(loc, _, _) -> print_info "Let " loc lxp
+ | Arrow(_, _, _, loc, _) -> print_info "Arrow " loc lxp
+ | Lambda(_, (loc, _), _, _) -> print_info "Lambda " loc lxp
+ | Call(_, _) -> print_info "Call " dummy_location lxp
+ | UnknownType(loc) -> print_info "UnknownType " loc lxp
+ | _ -> print_string "Nothing";
+;;
-let main () =
- debug_lex "./typer_test/lexer_test.typer"; (**)
-
- (*debug_parser "kiwi_code/lexer_test.kwi";**)
+(* Print a list of lexp *)
+let debug_lexp_print_all lexps =
+ List.iter
+ (fun px ->
+ debug_lexp_print px;
+ print_string "\n")
+ lexps
;;
-main ();*)
+
=====================================
tests/dummy1_test.ml deleted
=====================================
--- a/tests/dummy1_test.ml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-open Util
-open Prelexer
-open Debug
-
-let main () =
-
- let file_name = (Sys.argv.(1) ^ "/samples/lexer_test.typer") in
- prelex_file file_name
-;;
-
-main ()
-;;
\ No newline at end of file
=====================================
tests/dummy2_test.ml deleted
=====================================
--- a/tests/dummy2_test.ml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-open Util
-open Prelexer
-open Debug
-
-let main () =
-
- let file_name = (Sys.argv.(1) ^ "/samples/lexer_test.typer") in
- prelex_file file_name
-;;
-
-main ()
-;;
\ No newline at end of file
=====================================
tests/dummy_test.ml deleted
=====================================
--- a/tests/dummy_test.ml
+++ /dev/null
@@ -1,16 +0,0 @@
-
-open Util
-open Prelexer
-open Debug
-
-let main () =
-
- print_endline Sys.argv.(0);
- print_endline Sys.argv.(1);
-
- let file_name = (Sys.argv.(1) ^ "/samples/lexer_test.typer") in
- prelex_file file_name
-;;
-
-main ()
-;;
\ No newline at end of file
=====================================
tests/full_debug.ml
=====================================
--- /dev/null
+++ b/tests/full_debug.ml
@@ -0,0 +1,97 @@
+(*
+ * Typer Compiler
+ *
+ * ---------------------------------------------------------------------------
+ *
+ * Copyright (C) 2011-2016 Free Software Foundation, Inc.
+ *
+ * Author: Pierre Delaunay <pierre.delaunay(a)hec.ca>
+ * Keywords: languages, lisp, dependent types.
+ *
+ * This file is part of Typer.
+ *
+ * Typer is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ * Typer is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * ---------------------------------------------------------------------------
+ *
+ * Description:
+ * print out each compilation' steps
+ *
+ * --------------------------------------------------------------------------- *)
+
+open Debug
+open Prelexer
+open Lexer
+open Sexp
+open Grammar
+open Pexp
+open Debruijn
+open Lparse
+
+
+let main () =
+
+ let arg_n = Array.length Sys.argv in
+ let usage =
+ " Usage: \n " ^ Sys.argv.(0) ^ " <file_name> [options] \n\n" in
+
+ let print_title msg =
+ print_string "\n\t====\n";
+ print_string ("\t " ^ msg ^ "\n");
+ print_string "\t=======================\n" in
+
+ (* Print Usage *)
+ if arg_n == 1 then
+ begin
+ print_string usage;
+ print_string " Options:\n";
+ end
+ else
+ begin
+ let filename = Sys.argv.(1) in
+
+ (* Read additional Args if any *)
+
+ (* get pretokens*)
+ let pretoks = prelex_file filename in
+
+ (* get sexp/tokens *)
+ let toks = lex default_stt pretoks in
+
+ (* get node sexp *)
+ let nodes = sexp_parse_all_to_list default_grammar toks (Some ";") in
+
+ (* get pexp *)
+ let pexps = pexp_parse_all nodes in
+
+ (* get lexp *)
+ let ctx = make_context in
+ let lexps, new_ctx = lexp_parse_all pexps ctx in
+
+ (* Printing *)(*
+ print_title "PreTokens"; debug_pretokens_print_all pretoks;
+ print_title "Base Sexp"; debug_sexp_print_all toks; *)
+ print_title "Node Sexp"; debug_sexp_print_all nodes;
+ print_title "Pexp"; debug_pexp_print_all pexps;
+ print_title "Lexp"; debug_lexp_print_all lexps;
+
+ (* Eval Each Expression *)
+
+
+ end
+;;
+
+main ()
+;;
+
=====================================
tests/lexer_debug.ml deleted
=====================================
--- a/tests/lexer_debug.ml
+++ /dev/null
@@ -1,131 +0,0 @@
-(*
- * Typer Compiler
- *
- * ---------------------------------------------------------------------------
- *
- * Copyright (C) 2011-2016 Free Software Foundation, Inc.
- *
- * Author: Pierre Delaunay <pierre.delaunay(a)hec.ca>
- * Keywords: languages, lisp, dependent types.
- *
- * This file is part of Typer.
- *
- * Typer is free software; you can redistribute it and/or modify it under the
- * terms of the GNU General Public License as published by the Free Software
- * Foundation, either version 3 of the License, or (at your option) any
- * later version.
- *
- * Typer is distributed in the hope that it will be useful, but WITHOUT ANY
- * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
- * FOR A PARTICULAR PURPOSE. See the GNU General Public License for
- * more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program. If not, see <http://www.gnu.org/licenses/>.
- *
- * ---------------------------------------------------------------------------
- *
- * Description:
- * print out read Sexp (Syntactic expression)
- * i.e lexer's tokens
- *
- * --------------------------------------------------------------------------- *)
-
-open Util
-open Prelexer
-open Sexp
-open Lexer
-
-let default_stt =
- let stt = Array.create 256 false
- in stt.(Char.code ';') <- true;
- stt.(Char.code ',') <- true;
- stt.(Char.code '(') <- true;
- stt.(Char.code ')') <- true;
- stt
-
-
-let rec debug_sexp_print sexp =
- let print_loc = Debug.print_loc in
- match sexp with
- | Epsilon
- -> print_string "Epsilon()\n" (* "ε" *)
-
- | Block(loc, pts, _)
- -> print_string "Block: \t{";
- print_string "["; print_loc loc; print_string "]\t";
- pretokens_print pts;
- print_string " }"
-
- | Symbol(loc, name)
- -> print_string "Symbol: \t";
- print_string "["; print_loc loc; print_string "]\t";
- print_string name
-
- | String(loc, str)
- -> print_string "String: \t";
- print_string "["; print_loc loc; print_string "]\t";
- print_string "\""; print_string str; print_string "\""
-
- | Integer(loc, n)
- -> print_string "Integer: \t";
- print_string "["; print_loc loc; print_string "]\t";
- print_int n
-
- | Float(loc, x)
- -> print_string "Float: \t";
- print_string "["; print_loc loc; print_string "]\t";
- print_float x
-
- | Node(f, args)
- -> print_string "Node: \t";
- print_string "(";sexp_print f;
- List.iter (fun sexp -> print_string " "; sexp_print sexp)
- args;
- print_string ")"
-;;
-
-let debug_sexp_print_all tokens =
- List.iter (fun pt ->
- print_string " ";
- debug_sexp_print pt;
- print_string "\n";
- )
- tokens
-;;
-
-let main () =
- (*
- * print tokens/sexp of the file given as first arg
- *
- ********************************************************)
-
- let file = Sys.argv.(1) in
- print_string file;
- print_string "\n";
-
- (* Todo read file from prog args *)
- (* get pretokens*)
- let pretoks = prelex_file file in
-
- (* get tokens *)
- let toks = lex default_stt pretoks in
-
- (* print tokens *)
- debug_sexp_print_all toks
-;;
-
-main ();;
-
-(* Command Line * )
-let command =
- Command.basic
- ~summary:"Print Compiler Debug Info"
- ~readme:(fun () -> "More detailed information")
- Command.Spec.(empty +> anon ("filename" %: string))
- main
-
-let () =
- Command.run ~version:"1.0" ~build_info:"RWO" command * *)
-
-(*(main Sys.argv.(1));;*)
=====================================
tests/prelexer_debug.ml deleted
=====================================
--- a/tests/prelexer_debug.ml
+++ /dev/null
@@ -1,73 +0,0 @@
-(*
- * Typer Compiler
- *
- * ---------------------------------------------------------------------------
- *
- * Copyright (C) 2011-2016 Free Software Foundation, Inc.
- *
- * Author: Pierre Delaunay <pierre.delaunay(a)hec.ca>
- * Keywords: languages, lisp, dependent types.
- *
- * This file is part of Typer.
- *
- * Typer is free software; you can redistribute it and/or modify it under the
- * terms of the GNU General Public License as published by the Free Software
- * Foundation, either version 3 of the License, or (at your option) any
- * later version.
- *
- * Typer is distributed in the hope that it will be useful, but WITHOUT ANY
- * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
- * FOR A PARTICULAR PURPOSE. See the GNU General Public License for
- * more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program. If not, see <http://www.gnu.org/licenses/>.
- *
- * ---------------------------------------------------------------------------
- *
- * Description:
- * print out read pretoken
- *
- * --------------------------------------------------------------------------- *)
-
-open Util
-open Prelexer
-open Debug
-
-(* TODO: add a Prestring and a Preblock example into the test.typer file *)
-let rec debug_pretokens_print pretokens =
- List.iter (fun pt ->
- print_string " ";
- match pt with
- | Preblock(loc, pts,_)
- -> print_string "Preblock:\t";
- print_string "["; print_loc loc; print_string "]\t";
- print_string "{";
- pretokens_print pts;
- print_string " }"
-
- | Pretoken(loc, str)
- -> print_string "Pretoken:\t";
- print_string "["; print_loc loc; print_string "]\t";
- print_string str;
- print_string "\n"
-
- | Prestring(loc, str)
- -> print_string "Prestring:\t";
- print_string "["; print_loc loc; print_string "]\t";
- print_string "\"";
- print_string str;
- print_string "\"\n";
- )
- pretokens
-
-let main () =
- let file = Sys.argv.(1) in
- print_string file;
- print_string "\n";
-
- let arr = prelex_file file in
- debug_pretokens_print arr
-;;
-
-main ();
=====================================
tests/utest_main.ml
=====================================
--- a/tests/utest_main.ml
+++ b/tests/utest_main.ml
@@ -32,7 +32,7 @@
let cut_name str =
- String.sub str 0 (String.length str - 10)
+ String.sub str 0 (String.length str - 12)
;;
(* search *_test.byte executable en run them
@@ -60,7 +60,9 @@ let main () =
for i = 0 to files_n - 1 do
(* Check if file is a test => if it is run it *)
- (if Filename.check_suffix files.(i) "_test.byte" then begin
+ (if (Filename.check_suffix files.(i) "_test.byte") ||
+ (Filename.check_suffix files.(i) "_test.native") then
+ begin
tests_n := !tests_n + 1;
View it on GitLab: https://gitlab.com/monnier/typer/compare/57a4f589c0c4dda04796fea8053dda038b…
3
4
> Je me souviens plus pourquoi que l'on voulait utiliser une liste de Meyers ?
Pour que l'accès aux variables dans l'environnement soit O(log N) au
lieu de O(N).
> Il me semblait que l'on avait dit que
> let a = b, c = d in
> devient
> let a = b in
> let c = d in
> Nous n'avons donc pas besoin que Lexp.Let(location * (vdef * lexp * ltype)
> list * lexp)
> et nous pouvons utiliser location Lexp.Let(location * (vdef * lexp * ltype)
> * lexp) à la place.
Non, parce qu'il y a aussi le cas
let odd : int -> int;
even : int -> int;
odd n = case n | 0 => false | S n' => even (n');
even n = case n | 0 => true | S n' => odd (n');
in <exp>
qui ne peut pas se décomposer.
> Je vais créer un type temporaire Lexp.UnknownType(loc) pour remplacer les
> types qui ne sont pas encore inféré
OK. Sinon tu peux aussi simplement utiliser type_int.
> Est-ce bien un exemple correcte d'un let dans typer ?
> let a::Nat, a = b in
Presque. L'annotation de type utilise ":" plutôt que "::" et le
séparateur entre déclarations est ";" plutôt que ",".
Stefan
4
4