| 1 |
(* |
| 2 |
* A really stupid but (hopefully) working precedence parser |
| 3 |
* |
| 4 |
* --Allen Leung ([email protected]) |
| 5 |
*) |
| 6 |
|
| 7 |
signature PRECEDENCE_PARSER = |
| 8 |
sig |
| 9 |
|
| 10 |
type precedence_stack |
| 11 |
|
| 12 |
datatype fixity = INFIX of int |
| 13 |
| INFIXR of int |
| 14 |
| NONFIX |
| 15 |
datatype 'a token = ID of string |
| 16 |
| EXP of 'a |
| 17 |
|
| 18 |
exception PrecedenceError |
| 19 |
|
| 20 |
val empty : precedence_stack |
| 21 |
val declare : precedence_stack * string * fixity -> precedence_stack |
| 22 |
val parse : { stack : precedence_stack, |
| 23 |
app : 'a * 'a -> 'a, |
| 24 |
tuple : 'a list -> 'a, |
| 25 |
id : string -> 'a, |
| 26 |
error : string -> unit, |
| 27 |
toString : 'a -> string, |
| 28 |
kind : string |
| 29 |
} -> 'a token list -> 'a |
| 30 |
end |
| 31 |
|
| 32 |
structure PrecedenceParser : PRECEDENCE_PARSER = |
| 33 |
struct |
| 34 |
|
| 35 |
|
| 36 |
datatype fixity = INFIX of int |
| 37 |
| INFIXR of int |
| 38 |
| NONFIX |
| 39 |
datatype 'a token = ID of string |
| 40 |
| EXP of 'a |
| 41 |
|
| 42 |
type precedence_stack = (string * fixity) list |
| 43 |
|
| 44 |
val empty = [] |
| 45 |
fun declare(stack,id,fixity) = (id,fixity)::stack |
| 46 |
|
| 47 |
exception PrecedenceError |
| 48 |
|
| 49 |
fun parse {stack,tuple,app,id,toString,error,kind} tokens = |
| 50 |
let fun fixity x = |
| 51 |
let fun f [] = NONFIX |
| 52 |
| f ((y,fix)::S) = if x = y then fix else f S |
| 53 |
in f stack end |
| 54 |
|
| 55 |
val toks = map (fn ID x => (id x,fixity x) |
| 56 |
| EXP e => (e,NONFIX)) tokens |
| 57 |
|
| 58 |
fun err(msg) = |
| 59 |
(error(msg^" in "^kind^": "^ |
| 60 |
List.foldr (fn ((x,_),"") => toString x |
| 61 |
| ((x,_),s) => toString x^" "^s) "" |
| 62 |
toks); |
| 63 |
raise PrecedenceError) |
| 64 |
fun err'(msg, x) = err(msg^" "^toString x) |
| 65 |
|
| 66 |
(* |
| 67 |
* Parse with precedence. |
| 68 |
*) |
| 69 |
fun scan(p, tokens) = |
| 70 |
case tokens of |
| 71 |
(f,NONFIX)::(x,NONFIX)::rest => |
| 72 |
scan(p, (app(f,x), NONFIX)::rest) (* application *) |
| 73 |
| [(x,NONFIX)] => (x, []) |
| 74 |
| (x,INFIX _)::_ => err'("dangling infix symbol", x) |
| 75 |
| (x,INFIXR _)::_ => err'("dangling infixr symbol", x) |
| 76 |
| (left,NONFIX)::(rest as (f,INFIX q)::rest') => |
| 77 |
if p >= q then |
| 78 |
(left, rest) |
| 79 |
else |
| 80 |
let val (right, rest) = scan(q,rest') |
| 81 |
in scan(p,(app(f,tuple[left,right]),NONFIX)::rest) |
| 82 |
end |
| 83 |
| (left,NONFIX)::(rest as (f,INFIXR q)::rest') => |
| 84 |
if p > q then |
| 85 |
(left, rest) |
| 86 |
else |
| 87 |
let val (right, rest) = scan(q,rest') |
| 88 |
in scan(p,(app(f,tuple[left,right]),NONFIX)::rest) |
| 89 |
end |
| 90 |
| _ => err("parse error") |
| 91 |
|
| 92 |
fun scanAll [(x,INFIX _)] = x |
| 93 |
| scanAll [(x,INFIXR _)] = x |
| 94 |
| scanAll tokens = #1(scan(~1,tokens)) |
| 95 |
|
| 96 |
in scanAll toks end |
| 97 |
|
| 98 |
end |