Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (* File Expr/Parse.fs *)
- (* Lexing and parsing of simple expressions using fslex and fsyacc *)
- module Parse
- open System
- open System.IO
- open System.Text
- open Microsoft.FSharp.Text.Lexing
- open Absyn
- type sinstr =
- | SCstI of int (* push integer *)
- | SVar of int (* push variable from env *)
- | SAdd (* pop args, push sum *)
- | SSub (* pop args, push diff. *)
- | SMul (* pop args, push product *)
- | SPop (* pop value/unbind var *)
- | SSwap (* exchange top and next *)
- (* Plain parsing from a string, with poor error reporting *)
- let fromString (str : string) : expr =
- let lexbuf = Lexing.LexBuffer<char>.FromString(str)
- try
- ExprPar.Main ExprLex.Token lexbuf
- with
- | exn -> let pos = lexbuf.EndPos
- failwithf "%s near line %d, column %d\n"
- (exn.Message) (pos.Line+1) pos.Column
- (* Parsing from a text file *)
- let fromFile (filename : string) =
- use reader = new StreamReader(filename)
- let lexbuf = Lexing.LexBuffer<char>.FromTextReader reader
- try
- ExprPar.Main ExprLex.Token lexbuf
- with
- | exn -> let pos = lexbuf.EndPos
- failwithf "%s in file %s near line %d, column %d\n"
- (exn.Message) filename (pos.Line+1) pos.Column
- let compString s : list<sinstr> =
- let rec r e (a:list<sinstr>) (x:int) =
- match e with
- | CstI(i) -> SCstI(i)::a
- | Var(s) -> SVar(x)::a
- | Let(s,e1,e2) -> (r e1 a 0)@(r e2 a 0)@SSwap::SPop::a
- | Prim("+",e1,e2) -> (r e1 a x)@(r e2 a (x+1))@SAdd::a
- | Prim("-",e1,e2) -> (r e1 a x)@(r e2 a (x+1))@SSub::a
- | Prim("*",e1,e2) -> (r e1 a x)@(r e2 a (x+1))@SMul::a
- r (fromString s) [] 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement