Import Upstream version 20180207
[hcoop/debian/mlton.git] / mlyacc / examples / fol / parse.sml
1 (* Uses the generated lexer and parser to export parsing functions
2 *)
3
4 signature PARSE =
5 sig
6
7 structure Absyn : ABSYN
8
9 (* parse a program from a string *)
10
11 val prog_parse : string -> Absyn.absyn
12
13 (* parse a query from a string *)
14
15 val query_parse : string -> Absyn.absyn
16
17 (* parse a program in a file *)
18
19 val file_parse : string -> Absyn.absyn
20
21 (* parse a query from the standard input *)
22
23 val top_parse : unit -> Absyn.absyn
24
25 end (* signature PARSE *)
26
27
28 functor Parse (structure Absyn : ABSYN
29 structure Interface : INTERFACE
30 structure Parser : PARSER
31 sharing type Parser.arg = Interface.arg
32 sharing type Parser.pos = Interface.pos
33 sharing type Parser.result = Absyn.absyn
34 structure Tokens : Fol_TOKENS
35 sharing type Tokens.token = Parser.Token.token
36 sharing type Tokens.svalue = Parser.svalue
37 ) : PARSE =
38 struct
39
40 structure Absyn = Absyn
41
42 fun parse (dummyToken,lookahead,reader : int -> string) =
43 let val _ = Interface.init_line()
44 val empty = !Interface.line
45 val dummyEOF = Tokens.EOF(empty,empty)
46 val dummyTOKEN = dummyToken(empty,empty)
47 fun invoke lexer =
48 let val newLexer = Parser.Stream.cons(dummyTOKEN,lexer)
49 in Parser.parse(lookahead,newLexer,Interface.error,
50 Interface.nothing)
51 end
52 fun loop lexer =
53 let val (result,lexer) = invoke lexer
54 val (nextToken,lexer) = Parser.Stream.get lexer
55 in if Parser.sameToken(nextToken,dummyEOF) then result
56 else loop lexer
57 end
58 in loop (Parser.makeLexer reader)
59 end
60
61 fun string_reader s =
62 let val next = ref s
63 in fn _ => !next before next := ""
64 end
65
66 fun prog_parse s = parse (Tokens.PARSEPROG,15,string_reader s)
67
68 fun query_parse s = parse (Tokens.PARSEQUERY,15,string_reader s)
69
70 fun file_parse name =
71 let val dev = TextIO.openIn name
72 in (parse (Tokens.PARSEPROG,15,fn i => TextIO.inputN(dev,i)))
73 before TextIO.closeIn dev
74 end
75
76 fun top_parse () =
77 parse (Tokens.PARSEQUERY,0,(fn i =>
78 (case TextIO.inputLine TextIO.stdIn
79 of SOME s => s
80 | _ => "")))
81
82 end (* functor Parse *)