You'd like to test grammars that are being proposed as test cases for CS 132 projects. One way is to test it on actual CS 132 projects, but those projects aren't done yet and anyway you'd like a second opinion in case the student projects are incorrect. So you decide to write a simple parser generator. Given a grammar in the style of Homework 1, your program will generate a function that is a parser. When this parser is given a string whose prefix is a program to parse, it returns the corresponding unmatched suffix, or an error indication if no prefix of the string is a valid program.
The key notion of this assignment is that of a matcher. A matcher is a function that inspects a given string of terminals to find a match for a prefix that corresponds to a nonterminal symbol of a grammar, and then checks whether the match is acceptable by testing whether a given acceptor succeeds on the corresponding suffix. For example, a matcher for awkish_grammar below might inspect the string ["3";"+";"4";"-"] and find two possible prefixes that match, namely ["3";"+";"4"] and ["3"]. The matcher will first apply the acceptor to the first prefix ["3";"+";"4"], along with the corresponding suffix ["-"]. If this is accepted, the matcher will return whatever the acceptor returns. Otherwise, the matcher will apply the acceptor to the second prefix ["3"], along with the corresponding suffix ["+";"4";"-"], and will return whatever the acceptor returns. If a matcher finds no matching prefixes, it returns the special value None.
As you can see by mentally executing the example, matchers sometimes need to try multiple alternatives and to backtrack to a later alternative if an earlier one is a blind alley.
An acceptor is a function that accepts a suffix by returning some value wrapped inside the Some constructor. The acceptor rejects the suffix by returning None. For example, the acceptor (function | "+"::t -> Some ("+"::t) | _ -> None) accepts only suffixes beginning with "+". Such an acceptor would cause the example matcher to fail on the prefix ["3";"+";"4"] (since the corresponding suffix begins with "-", not "+") but it would succeed on the prefix ["3"].
By convention, an acceptor that is successful returns Some s, where s is a tail of the input suffix (because the acceptor may have parsed more of the input, and has therefore consumed some of the suffix). This allows the matcher's caller to retrieve an indication of where the matched prefix ends (since it ends just before the suffix starts). Although this behavior is crucial for the internal acceptors used by your code, it is not required for top-level acceptors supplied by test programs: a top-level acceptor needs only to return a Some x value to succeed.
Whenever there are several rules to try for a nonterminal, you should always try them left-to-right. For example, awkish_grammar below contains this:
| Expr -> [[N Term; N Binop; N Expr]; [N Term]]
and therefore, your matcher should attempt to use the rule "Expr → Term Binop Expr" before attempting to use the simpler rule "Expr → Term".
If you can build a matcher, it should be relatively easy to build a parser, which yields a parse tree that corresponds to its input fragment.
type ('nonterminal, 'terminal) parse_tree = | Node of 'nonterminal * ('nonterminal, 'terminal) parse_tree list | Leaf of 'terminalIf you traverse a parse tree in preorder left to right, the leaves you encounter contain the same terminal symbols as the parsed fragment, and each internal node of the parse tree corresponds to a rule in the grammar, traversed in a leftmost derivation order.
Unlike Homework 1, we are expecting some weaknesses here, so your assessment should talk about them. For example, we don't expect that your implementation will work with all possible grammars, but we would like to know which sort of grammars it will have trouble with.
As with Homework 1, your code may use the Pervasives and List modules, but it should use no other modules. Your code should be free of side effects. Simplicity is more important than efficiency, but your code should avoid using unnecessary time and space when it is easy to do so.
We will test your program on the SEASnet Linux servers as before, so make sure that /usr/local/cs/bin is at the start of your path, using the same technique as in Homework 1.
Submit three files:
let accept_all string = Some string let accept_empty_suffix = function | _::_ -> None | x -> Some x (* An example grammar for a small subset of Awk. This grammar is not the same as Homework 1; it is instead the same as the grammar under "Theoretical background" above. *) type awksub_nonterminals = | Expr | Term | Lvalue | Incrop | Binop | Num let awkish_grammar = (Expr, function | Expr -> [[N Term; N Binop; N Expr]; [N Term]] | Term -> [[N Num]; [N Lvalue]; [N Incrop; N Lvalue]; [N Lvalue; N Incrop]; [T"("; N Expr; T")"]] | Lvalue -> [[T"$"; N Expr]] | Incrop -> [[T"++"]; [T"--"]] | Binop -> [[T"+"]; [T"-"]] | Num -> [[T"0"]; [T"1"]; [T"2"]; [T"3"]; [T"4"]; [T"5"]; [T"6"]; [T"7"]; [T"8"]; [T"9"]]) let test0 = ((make_matcher awkish_grammar accept_all ["ouch"]) = None) let test1 = ((make_matcher awkish_grammar accept_all ["9"]) = Some [] let test2 = ((make_matcher awkish_grammar accept_all ["9"; "+"; "$"; "1"; "+"]) = Some ["+"] let test3 = ((make_matcher awkish_grammar accept_empty_suffix ["9"; "+"; "$"; "1"; "+"]) = None) (* This one might take a bit longer.... *) let test4 = ((make_matcher awkish_grammar accept_all ["("; "$"; "8"; ")"; "-"; "$"; "++"; "$"; "--"; "$"; "9"; "+"; "("; "$"; "++"; "$"; "2"; "+"; "("; "8"; ")"; "-"; "9"; ")"; "-"; "("; "$"; "$"; "$"; "$"; "$"; "++"; "$"; "$"; "5"; "++"; "++"; "--"; ")"; "-"; "++"; "$"; "$"; "("; "$"; "8"; "++"; ")"; "++"; "+"; "0"]) = Some []) let test5 = (parse_tree_leaves (Node ("+", [Leaf 3; Node ("*", [Leaf 4; Leaf 5])])) = [3; 4; 5]) let small_awk_frag = ["$"; "1"; "++"; "-"; "2"] let test6 = ((make_parser awkish_grammar small_awk_frag) = Some (Node (Expr, [Node (Term, [Node (Lvalue, [Leaf "$"; Node (Expr, [Node (Term, [Node (Num, [Leaf "1"])])])]); Node (Incrop, [Leaf "++"])]); Node (Binop, [Leaf "-"]); Node (Expr, [Node (Term, [Node (Num, [Leaf "2"])])])]))) let test7 = match make_parser awkish_grammar small_awk_frag with | Some tree -> parse_tree_leaves tree = small_awk_frag | _ -> false
If you put the sample test cases into a file hw2sample.ml, you should be able to use it with something ike the following to test your hw2.ml solution on the SEASnet implementation of OCaml. Similarly, the command #use "hw2test.ml";; should run your own test cases on your solution.
$ ocaml OCaml version 4.07.1 # #use "hw2.ml";; ... val parse_tree_leaves : ('a, 'b) parse_tree -> 'b list = <fun> ... val make_matcher : 'a * ('a -> ('a, 'b) symbol list list) -> ('b list -> 'c option) -> 'b list -> 'c option = <fun> ... val make_parser : 'a * ('a -> ('a, 'b) symbol list list) -> 'b list -> ('a, 'b) parse_tree option = <fun> ... # #use "hw2sample.ml";; val accept_all : 'a -> 'a option = <fun> val accept_empty_suffix : 'a list -> 'b list option = <fun> type awksub_nonterminals = ... val awkish_grammar : awksub_nonterminals * (awksub_nonterminals -> (awksub_nonterminals, string) symbol list list) = (Expr, <fun>) val test0 : bool = true val test1 : bool = true val test2 : bool = true val test3 : bool = true val test4 : bool = true val test5 : bool = true ... val test6 : bool = true val test7 : bool = true #
You can use a previous Homework 2 as a hint. It is a tough homework and is not the same problem but there are some common ideas. Look for the sample solution at the end.