Files

41 lines
1.3 KiB
OCaml

open System.IO
open Ast
open List
(* Create a parser object, wired to the lexer. The cast *)
(* here is only needed because F# does not understand all *)
(* C# conversions, even simple upcasts. *)
let langParser = new LangParse()
(* Now invoke the parser on an input stream. The parser *)
(* function returns the base type SYMBOL, but we know the exact *)
(* type will always be Prog. The ".v" access fetches the attribute *)
(* that stores the real value carried by the 'Prog' symbol. *)
let stream = new StreamReader(Sys.argv.(1))
let myProg =
let res = langParser.Parse(stream) in
if nonnull res then (cast res : Prog).v
else (prerr_endline "Exiting: syntax error"; exit 1)
(* Now look at the resulting AST, e.g. count the number of top-level *)
(* statements, and then the overall number of nodes. *)
let _ = System.Console.WriteLine(List.length (match myProg with Prog l -> l))
let rec progNodes (Prog stmts) = stmtsNodes stmts
and stmtsNodes l =
match l with
[] -> 0
| h::t -> stmtNodes h + stmtsNodes t
and stmtNodes s =
match s with
| Assign (a,b) -> 1
| While (a,b) -> 1 + stmtNodes b
| Seq stmts -> stmtsNodes stmts
| IfThen (g,t) -> 1 + stmtNodes t
| IfThenElse (g,t,e) -> 1 + stmtNodes t + stmtNodes e
let _ = System.Console.WriteLine("Num nodes = "^string_of_int (progNodes myProg))