| 1 |
(* |
| 2 |
* A pattern matching compiler. |
| 3 |
* This is based on Pettersson's paper |
| 4 |
* ``A Term Pattern-Match Compiler Inspired by Finite Automata Theory'' |
| 5 |
* |
| 6 |
*) |
| 7 |
local |
| 8 |
val sanityCheck = true |
| 9 |
val debug = false |
| 10 |
in |
| 11 |
|
| 12 |
functor MatchCompiler |
| 13 |
(structure Var : (* a variable *) |
| 14 |
sig type var |
| 15 |
val compare : var * var -> order |
| 16 |
val toString : var -> string |
| 17 |
end |
| 18 |
|
| 19 |
structure Con : (* datatype constructors *) |
| 20 |
sig |
| 21 |
type con |
| 22 |
val compare : con * con -> order |
| 23 |
val toString : con -> string |
| 24 |
val variants : con -> {known:con list, others:bool} |
| 25 |
val arity : con -> int |
| 26 |
end |
| 27 |
|
| 28 |
structure Literal : (* literals *) |
| 29 |
sig |
| 30 |
type literal |
| 31 |
val compare : literal * literal -> order |
| 32 |
val toString : literal -> string |
| 33 |
val variants : literal -> {known:literal list, others:bool} option |
| 34 |
end |
| 35 |
|
| 36 |
structure Action : |
| 37 |
sig type action (* an action *) |
| 38 |
val toString : action -> string |
| 39 |
val freeVars : action -> Var.var list |
| 40 |
end |
| 41 |
|
| 42 |
structure Guard : (* a guard expression *) |
| 43 |
sig type guard |
| 44 |
val toString : guard -> string |
| 45 |
val compare : guard * guard -> order |
| 46 |
val logicalAnd : guard * guard -> guard |
| 47 |
end |
| 48 |
|
| 49 |
structure Exp : |
| 50 |
sig type exp |
| 51 |
val toString : exp -> string |
| 52 |
end |
| 53 |
) : MATCH_COMPILER = |
| 54 |
struct |
| 55 |
|
| 56 |
structure PP = PP |
| 57 |
|
| 58 |
val i2s = Int.toString |
| 59 |
|
| 60 |
fun listify (l,s,r) list = |
| 61 |
l^List.foldr (fn (x,"") => x | (x,y) => x^s^y) "" list^r |
| 62 |
|
| 63 |
(* ListPair.all has the wrong semantics! *) |
| 64 |
fun forall f ([], []) = true |
| 65 |
| forall f (x::xs, y::ys) = f(x,y) andalso forall f (xs, ys) |
| 66 |
| forall f _ = false |
| 67 |
|
| 68 |
datatype index = INT of int | LABEL of Var.var |
| 69 |
|
| 70 |
datatype path = PATH of index list |
| 71 |
|
| 72 |
structure Index = |
| 73 |
struct |
| 74 |
fun compare(INT i, INT j) = Int.compare(i,j) |
| 75 |
| compare(LABEL i, LABEL j) = Var.compare(i,j) |
| 76 |
| compare(INT _, LABEL _) = LESS |
| 77 |
| compare(LABEL _,INT _) = GREATER |
| 78 |
fun equal(x,y) = compare(x,y) = EQUAL |
| 79 |
fun toString(INT i) = i2s i |
| 80 |
| toString(LABEL l) = Var.toString l |
| 81 |
end |
| 82 |
|
| 83 |
structure Path = |
| 84 |
struct |
| 85 |
fun compare(PATH p1, PATH p2) = |
| 86 |
let fun loop([], []) = EQUAL |
| 87 |
| loop([], _) = LESS |
| 88 |
| loop(_, []) = GREATER |
| 89 |
| loop(x::xs, y::ys) = |
| 90 |
(case Index.compare(x,y) of |
| 91 |
EQUAL => loop(xs,ys) |
| 92 |
| ord => ord |
| 93 |
) |
| 94 |
in loop(p1, p2) |
| 95 |
end |
| 96 |
fun equal(p1,p2) = compare(p1,p2) = EQUAL |
| 97 |
fun append(PATH p1, PATH p2) = PATH(p1@p2) |
| 98 |
fun dot(PATH p, i) = PATH(p @ [i]) |
| 99 |
fun toString(PATH p) = |
| 100 |
"["^List.foldr (fn (i,"") => Index.toString i |
| 101 |
| (i,s) => Index.toString i^"."^s) "" p^"]" |
| 102 |
fun toIdent(PATH p) = |
| 103 |
"v_"^List.foldr (fn (i,"") => Index.toString i |
| 104 |
| (i,s) => Index.toString i^"_"^s) "" p |
| 105 |
structure Map = RedBlackMapFn(type ord_key = path val compare = compare) |
| 106 |
end |
| 107 |
|
| 108 |
datatype name = VAR of Var.var | PVAR of path |
| 109 |
|
| 110 |
structure Name = |
| 111 |
struct |
| 112 |
fun toString(VAR v) = Var.toString v |
| 113 |
| toString(PVAR p) = Path.toString p |
| 114 |
fun compare(VAR x,VAR y) = Var.compare(x,y) |
| 115 |
| compare(PVAR x,PVAR y) = Path.compare(x,y) |
| 116 |
| compare(VAR _, PVAR _) = LESS |
| 117 |
| compare(PVAR _, VAR _) = GREATER |
| 118 |
fun equal(x,y) = compare(x,y) = EQUAL |
| 119 |
structure Set = RedBlackSetFn(type ord_key = name val compare = compare) |
| 120 |
fun setToString s = |
| 121 |
"{"^List.foldr (fn (v,"") =>toString v |
| 122 |
| (v,s) => toString v^"."^s) "" (Set.listItems s)^"}" |
| 123 |
end |
| 124 |
|
| 125 |
structure VarSet = RedBlackSetFn |
| 126 |
(type ord_key = Var.var val compare = Var.compare) |
| 127 |
structure Subst = RedBlackMapFn(type ord_key = Var.var val compare = Var.compare) |
| 128 |
type subst = name Subst.map |
| 129 |
fun mergeSubst(s1,s2) = Subst.foldri(fn (k,v,s) => Subst.insert(s,k,v)) s1 s2 |
| 130 |
|
| 131 |
(* Internal rep of pattern after every variable has been renamed *) |
| 132 |
datatype pat = |
| 133 |
WILDpat (* wild card *) |
| 134 |
| APPpat of decon * pat list (* constructor *) |
| 135 |
| TUPLEpat of pat list (* tupling *) |
| 136 |
| RECORDpat of (Var.var * pat) list (* record *) |
| 137 |
| ORpat of (subst * pat) list (* disjunction *) |
| 138 |
| ANDpat of (subst * pat) list (* conjunction *) |
| 139 |
| NOTpat of subst * pat (* negation *) |
| 140 |
| WHEREpat of pat * subst * Guard.guard (* guard *) |
| 141 |
| NESTEDpat of pat * subst * path * (int * Exp.exp) * pat |
| 142 |
| CONTpat of Var.var * pat |
| 143 |
|
| 144 |
and decon = CON of Con.con |
| 145 |
| LIT of Literal.literal |
| 146 |
|
| 147 |
exception MatchCompiler of string |
| 148 |
|
| 149 |
fun error msg = raise MatchCompiler msg |
| 150 |
fun bug msg = error("bug: "^msg) |
| 151 |
|
| 152 |
structure Con = Con |
| 153 |
structure Action = Action |
| 154 |
structure Literal = Literal |
| 155 |
structure Guard = Guard |
| 156 |
structure Exp = Exp |
| 157 |
structure Var = Var |
| 158 |
|
| 159 |
structure Decon = |
| 160 |
struct |
| 161 |
fun kind(CON _) = 0 |
| 162 |
| kind(LIT _) = 1 |
| 163 |
fun compare(CON x,CON y) = Con.compare(x,y) |
| 164 |
| compare(LIT x,LIT y) = Literal.compare(x,y) |
| 165 |
| compare(x,y) = Int.compare(kind x,kind y) |
| 166 |
|
| 167 |
fun toString(CON c) = Con.toString c |
| 168 |
| toString(LIT l) = Literal.toString l |
| 169 |
|
| 170 |
fun equal(x,y) = compare(x,y) = EQUAL |
| 171 |
structure Map = RedBlackMapFn(type ord_key = decon val compare = compare) |
| 172 |
structure Set = RedBlackSetFn(type ord_key = decon val compare = compare) |
| 173 |
end |
| 174 |
|
| 175 |
structure Pat = |
| 176 |
struct |
| 177 |
fun sortByLabel l = |
| 178 |
ListMergeSort.sort |
| 179 |
(fn ((x,_),(y,_)) => Var.compare(x,y) = GREATER) l |
| 180 |
|
| 181 |
fun toString(WILDpat) = "_" |
| 182 |
| toString(APPpat(c,[])) = Decon.toString c |
| 183 |
| toString(APPpat(c,xs)) = Decon.toString c^ |
| 184 |
listify("(",",",")") (map toString xs) |
| 185 |
| toString(TUPLEpat pats) = listify("(",",",")") (map toString pats) |
| 186 |
| toString(RECORDpat lps) = listify("{",",","}") |
| 187 |
(map (fn (l,p) => |
| 188 |
Var.toString l^"="^toString p) lps) |
| 189 |
| toString(ORpat ps) = listify("("," | ",")") (map toString' ps) |
| 190 |
| toString(ANDpat ps) = listify("("," and ",")") (map toString' ps) |
| 191 |
| toString(NOTpat p) = "not "^toString' p |
| 192 |
| toString(WHEREpat(p,_,g)) = toString p^" where "^Guard.toString g |
| 193 |
| toString(NESTEDpat(p,_,_,(_,e),p')) = |
| 194 |
toString p^" where "^Exp.toString e^" in "^toString p' |
| 195 |
| toString(CONTpat(v,p)) = toString p ^" exception "^ Var.toString v |
| 196 |
and toString'(subst,p) = toString p |
| 197 |
|
| 198 |
end |
| 199 |
|
| 200 |
type rule_no = int |
| 201 |
|
| 202 |
datatype dfa = |
| 203 |
DFA of |
| 204 |
{ stamp : int, (* unique dfa stamp *) |
| 205 |
freeVars : Name.Set.set ref, (* free variables *) |
| 206 |
refCount : int ref, (* reference count *) |
| 207 |
generated: bool ref, (* has code been generated? *) |
| 208 |
height : int ref, (* dag height *) |
| 209 |
test : test (* type of tests *) |
| 210 |
} |
| 211 |
|
| 212 |
and test = |
| 213 |
CASE of path * (decon * path list * dfa) list * |
| 214 |
dfa option (* multiway *) |
| 215 |
| WHERE of Guard.guard * dfa * dfa (* if test *) |
| 216 |
| OK of rule_no * Action.action (* final dfa *) |
| 217 |
| BIND of subst * dfa (* apply subst *) |
| 218 |
| LET of path * (int * Exp.exp) * dfa (* let *) |
| 219 |
| SELECT of path * (path * index) list * dfa (* projections *) |
| 220 |
| CONT of Var.var * dfa (* bind continuation *) |
| 221 |
| FAIL (* error dfa *) |
| 222 |
|
| 223 |
and compiled_dfa = |
| 224 |
ROOT of {dfa : dfa, |
| 225 |
used : Name.Set.set, |
| 226 |
exhaustive : bool, |
| 227 |
redundant : IntListSet.set |
| 228 |
} |
| 229 |
|
| 230 |
and matrix = |
| 231 |
MATRIX of |
| 232 |
{ rows : row list, |
| 233 |
paths : path list (* path (per column) *) |
| 234 |
} |
| 235 |
|
| 236 |
|
| 237 |
withtype row = |
| 238 |
{pats : pat list, |
| 239 |
guard : (subst * Guard.guard) option, |
| 240 |
nested : (subst * path * (int * Exp.exp) * pat) list, |
| 241 |
dfa : dfa |
| 242 |
} |
| 243 |
and compiled_rule = |
| 244 |
rule_no * pat list * Guard.guard option * subst * Action.action |
| 245 |
|
| 246 |
and compiled_pat = pat * subst |
| 247 |
|
| 248 |
(* Utilities for dfas *) |
| 249 |
structure DFA = |
| 250 |
struct |
| 251 |
val itow = Word.fromInt |
| 252 |
|
| 253 |
fun h(DFA{stamp, ...}) = itow stamp |
| 254 |
fun hash(DFA{stamp, test, ...}) = |
| 255 |
(case test of |
| 256 |
FAIL => 0w0 |
| 257 |
| OK _ => 0w123 + itow stamp |
| 258 |
| CASE(path, cases, default) => 0w1234 + |
| 259 |
foldr (fn ((_,_,x),y) => h x + y) |
| 260 |
(case default of SOME x => h x | NONE => 0w0) cases |
| 261 |
| SELECT(_, _, dfa) => 0w2313 + hash dfa |
| 262 |
| CONT(_, dfa) => 0w1234 + hash dfa |
| 263 |
| WHERE(g, yes, no) => 0w2343 + h yes + h no |
| 264 |
| BIND(_, dfa) => 0w23234 + h dfa |
| 265 |
| LET(_, (i, _), dfa) => itow i + h dfa + 0w843 |
| 266 |
) |
| 267 |
|
| 268 |
(* pointer equality *) |
| 269 |
fun eq(DFA{stamp=s1, ...}, DFA{stamp=s2, ...}) = s1=s2 |
| 270 |
fun eqOpt(NONE, NONE) = true |
| 271 |
| eqOpt(SOME x, SOME y) = eq(x,y) |
| 272 |
| eqOpt _ = false |
| 273 |
|
| 274 |
(* one-level equality *) |
| 275 |
fun equal(DFA{test=t1, stamp=s1,...}, |
| 276 |
DFA{test=t2, stamp=s2,...}) = |
| 277 |
(case (t1, t2) of |
| 278 |
(FAIL, FAIL) => true |
| 279 |
| (OK _, OK _) => s1 = s2 |
| 280 |
| (SELECT(p1, b1, x), SELECT(p2, b2, y)) => |
| 281 |
Path.equal(p1,p2) andalso eq(x,y) andalso |
| 282 |
forall(fn ((px,ix),(py,iy)) => |
| 283 |
Path.equal(px,py) andalso Index.equal(ix,iy)) |
| 284 |
(b1,b2) |
| 285 |
| (CONT(k1, x), CONT(k2, y)) => |
| 286 |
Var.compare(k1,k2) = EQUAL andalso eq(x,y) |
| 287 |
| (CASE(p1,c1,o1), CASE(p2,c2,o2)) => |
| 288 |
Path.equal(p1,p2) andalso |
| 289 |
forall |
| 290 |
(fn ((u,_,x),(v,_,y)) => |
| 291 |
Decon.equal(u,v) andalso eq(x,y)) |
| 292 |
(c1,c2) andalso |
| 293 |
eqOpt(o1,o2) |
| 294 |
| (WHERE(g1, y1, n1), |
| 295 |
WHERE(g2, y2, n2)) => |
| 296 |
Guard.compare(g1,g2) = EQUAL |
| 297 |
andalso eq(y1,y2) andalso eq(n1,n2) |
| 298 |
| (BIND(s1, x), BIND(s2, y)) => |
| 299 |
eq(x,y) andalso |
| 300 |
forall (fn ((p,x),(q,y)) => |
| 301 |
Var.compare(p,q) = EQUAL andalso |
| 302 |
Name.equal(x,y)) |
| 303 |
(Subst.listItemsi s1, Subst.listItemsi s2) |
| 304 |
| (LET(p1, (i1, _), x), LET(p2, (i2, _), y)) => |
| 305 |
Path.equal(p1,p2) andalso i1=i2 andalso eq(x,y) |
| 306 |
| _ => false |
| 307 |
) |
| 308 |
|
| 309 |
structure HashTable = |
| 310 |
HashTableFn(type hash_key = dfa |
| 311 |
val sameKey = equal |
| 312 |
val hashVal = hash |
| 313 |
) |
| 314 |
|
| 315 |
fun toString(ROOT{dfa, ...}) = |
| 316 |
let exception NotVisited |
| 317 |
val visited = IntHashTable.mkTable(32, NotVisited) |
| 318 |
fun mark stamp = IntHashTable.insert visited (stamp, true) |
| 319 |
fun isVisited stamp = |
| 320 |
Option.getOpt(IntHashTable.find visited stamp, false) |
| 321 |
open PP |
| 322 |
infix ++ |
| 323 |
fun prArgs [] = nop |
| 324 |
| prArgs ps = seq(!!"(",!!",",!!")") (map (! o Path.toString) ps) |
| 325 |
fun walk(DFA{stamp, test=FAIL, ...}) = ! "fail" |
| 326 |
| walk(DFA{stamp, test, refCount=ref n, ...}) = |
| 327 |
if isVisited stamp then !"goto" ++ int stamp |
| 328 |
else (mark stamp; |
| 329 |
!!"<" ++ int stamp ++ !!">" ++ |
| 330 |
(if n > 1 then !! "*" else nop) ++ |
| 331 |
(case test of |
| 332 |
OK(_,a) => !"Ok" ++ !(Action.toString a) |
| 333 |
| FAIL => !"Fail" |
| 334 |
| SELECT(root,bindings,body) => |
| 335 |
line(!"Let") ++ |
| 336 |
block(seq (nop,nl,nop) |
| 337 |
(map (fn (p,i) => |
| 338 |
tab ++ |
| 339 |
!(Path.toString p) ++ !"=" ++ |
| 340 |
!(Path.toString root) ++ !"." ++ |
| 341 |
!(Index.toString i) |
| 342 |
) bindings) |
| 343 |
) ++ |
| 344 |
line(!"in") ++ |
| 345 |
block(walk body) |
| 346 |
| CONT(k,x) => line(!"Cont" ++ !(Var.toString k) ++ walk x) |
| 347 |
| CASE(p,cases,default) => |
| 348 |
line(!"Case" ++ !!(Path.toString p)) ++ |
| 349 |
block( |
| 350 |
seq (nop,nl,nop) |
| 351 |
((map (fn (decon,args,dfa) => |
| 352 |
tab ++ !(Decon.toString decon) ++ prArgs args |
| 353 |
++ !"=>" ++ sp ++ walk dfa) |
| 354 |
cases) @ |
| 355 |
(case default of |
| 356 |
NONE => [] |
| 357 |
| SOME dfa => [!"_" ++ !"=>" ++ sp ++ walk dfa] |
| 358 |
) |
| 359 |
) |
| 360 |
) |
| 361 |
| WHERE(g,y,n) => |
| 362 |
line(!"If" ++ !(Guard.toString g)) ++ |
| 363 |
block(tab ++ ! "then" ++ walk y ++ nl ++ |
| 364 |
tab ++ ! "else" ++ walk n) |
| 365 |
| BIND(subst, x) => |
| 366 |
line(Subst.foldri (fn (v,n,pp) => |
| 367 |
tab ++ !(Var.toString v) ++ !!"<-" ++ |
| 368 |
!(Name.toString n) ++ pp) |
| 369 |
nop subst) ++ |
| 370 |
walk x |
| 371 |
| LET(path,( _, e), x) => |
| 372 |
line(! "Let" ++ !(Path.toString path) ++ !"=" ++ |
| 373 |
!(Exp.toString e)) ++ |
| 374 |
block(walk x) |
| 375 |
) |
| 376 |
) |
| 377 |
in PP.text(walk dfa ++ nl) |
| 378 |
end |
| 379 |
end |
| 380 |
|
| 381 |
(* Utilities for the pattern matrix *) |
| 382 |
structure Matrix = |
| 383 |
struct |
| 384 |
fun row(MATRIX{rows, ...}, i) = List.nth(rows,i) |
| 385 |
fun col(MATRIX{rows, ...}, i) = |
| 386 |
List.map (fn {pats, ...} => List.nth(pats, i)) rows |
| 387 |
fun pathOf(MATRIX{paths, ...}, i) = List.nth(paths, i) |
| 388 |
fun columnCount(m) = List.length(#pats(row(m,0))) |
| 389 |
fun isEmpty(MATRIX{rows=[], ...}) = true |
| 390 |
| isEmpty _ = false |
| 391 |
|
| 392 |
fun removeFirstRow(MATRIX{rows=_::rows, paths}) = |
| 393 |
MATRIX{rows=rows, paths=paths} |
| 394 |
| removeFirstRow _ = error "removeFirstRow" |
| 395 |
|
| 396 |
fun check(MATRIX{rows, paths, ...}) = |
| 397 |
let val arity = length paths |
| 398 |
in app (fn {pats, ...} => |
| 399 |
if length pats <> arity then bug "bad matrix" else ()) |
| 400 |
rows |
| 401 |
end |
| 402 |
|
| 403 |
fun toString(MATRIX{rows, paths, ...}) = |
| 404 |
listify("","\n","\n") |
| 405 |
(map (fn {pats, ...} => |
| 406 |
listify("[","\t","]") (map Pat.toString pats)) rows) |
| 407 |
|
| 408 |
(* |
| 409 |
* Given a matrix, find the best column for matching. |
| 410 |
* |
| 411 |
* I'm using the heuristic that John (Reppy) uses: |
| 412 |
* the first column i where pat_i0 is not a wild card, and |
| 413 |
* with the maximum number of distinct constructors in the |
| 414 |
* the column. |
| 415 |
* |
| 416 |
* If the first row is all wild card, then return NONE. |
| 417 |
*) |
| 418 |
fun findBestMatchColumn(m as MATRIX{rows, ...}) = |
| 419 |
let val _ = if sanityCheck then check m else () |
| 420 |
val _ = if debug then |
| 421 |
(print(toString m)) |
| 422 |
else () |
| 423 |
val nCol = columnCount m |
| 424 |
|
| 425 |
fun score i = (* score of doing pattern matching on column i *) |
| 426 |
let val pats_i = col(m, i) |
| 427 |
val pats_i0 = hd pats_i |
| 428 |
in case pats_i0 of |
| 429 |
WILDpat => 0 |
| 430 |
| _ => |
| 431 |
let val (cons, score) = |
| 432 |
(* count distinct constructors; skip refutable cards |
| 433 |
* Give records, tuples and or pats, high scores so that |
| 434 |
* they are immediately expanded |
| 435 |
*) |
| 436 |
List.foldr (fn (WILDpat, (S, n)) => (S, n) |
| 437 |
| (APPpat(c, _), (S, n)) => |
| 438 |
(Decon.Set.add(S, c), n) |
| 439 |
| (_, (S, n)) => (S, 10000)) |
| 440 |
(Decon.Set.empty, 0) pats_i |
| 441 |
in score + Decon.Set.numItems cons end |
| 442 |
end |
| 443 |
|
| 444 |
(* Find column with the highest score *) |
| 445 |
fun findBest(i, bestSoFar) = |
| 446 |
if i >= nCol then bestSoFar else |
| 447 |
let val score_i = score i |
| 448 |
val best = |
| 449 |
if case bestSoFar of |
| 450 |
NONE => true |
| 451 |
| SOME(_, best_score) => score_i > best_score |
| 452 |
then SOME(i, score_i) |
| 453 |
else bestSoFar |
| 454 |
in findBest(i+1, best) |
| 455 |
end |
| 456 |
|
| 457 |
in case findBest(0, NONE) of |
| 458 |
SOME(i, 0) => NONE (* a score of zero means all wildcards *) |
| 459 |
| SOME(i, _) => SOME i |
| 460 |
| NONE => NONE |
| 461 |
end |
| 462 |
|
| 463 |
end (* Matrix *) |
| 464 |
|
| 465 |
val toString = DFA.toString |
| 466 |
|
| 467 |
(* |
| 468 |
* Rename user pattern into internal pattern. |
| 469 |
* The path business is hidden from the client. |
| 470 |
*) |
| 471 |
fun rename doIt {number=rule_no, pats, guard, action, cont} = |
| 472 |
let val empty = Subst.empty |
| 473 |
|
| 474 |
fun bind(subst, v, p) = |
| 475 |
case Subst.find(subst, v) of |
| 476 |
SOME _ => error("duplicated pattern variable "^Var.toString v) |
| 477 |
| NONE => Subst.insert(subst, v, PVAR p) |
| 478 |
|
| 479 |
fun process(path, subst:subst, pat) : compiled_pat = |
| 480 |
let fun idPat id = (WILDpat, bind(subst, id, path)) |
| 481 |
fun asPat(id, p) = |
| 482 |
let val (p, subst) = process(path, subst, p) |
| 483 |
in (p, bind(subst, id, path)) |
| 484 |
end |
| 485 |
fun wildPat() = (WILDpat, subst) |
| 486 |
fun litPat(lit) = (APPpat(LIT lit, []), subst) |
| 487 |
|
| 488 |
fun processPats(pats) = |
| 489 |
let fun loop([], _, ps', subst) = (rev ps', subst) |
| 490 |
| loop(p::ps, i, ps', subst) = |
| 491 |
let val path' = Path.dot(path, INT i) |
| 492 |
val (p, subst) = process(path', subst, p) |
| 493 |
in loop(ps, i+1, p::ps', subst) |
| 494 |
end |
| 495 |
in loop(pats, 0, [], subst) end |
| 496 |
|
| 497 |
fun processLPats(lpats) = |
| 498 |
let fun loop([], ps', subst) = (rev ps', subst) |
| 499 |
| loop((l,p)::ps, ps', subst) = |
| 500 |
let val path' = Path.dot(path, LABEL l) |
| 501 |
val (p, subst) = process(path', subst, p) |
| 502 |
in loop(ps, (l,p)::ps', subst) |
| 503 |
end |
| 504 |
in loop(lpats, [], subst) end |
| 505 |
|
| 506 |
fun consPat(c,args) : compiled_pat = |
| 507 |
let val (pats, subst) = processPats(args) |
| 508 |
in (* arity check *) |
| 509 |
if Con.arity c <> length args |
| 510 |
then error("arity mismatch "^Con.toString c) |
| 511 |
else (); |
| 512 |
(APPpat(CON c, pats), subst) |
| 513 |
end |
| 514 |
|
| 515 |
fun tuplePat(pats) : compiled_pat = |
| 516 |
let val (pats, subst) = processPats(pats) |
| 517 |
in (TUPLEpat pats, subst) end |
| 518 |
|
| 519 |
fun recordPat(lpats) : compiled_pat = |
| 520 |
let val (lpats, subst) = processLPats(lpats) |
| 521 |
in (RECORDpat lpats, subst) end |
| 522 |
|
| 523 |
fun noDupl(subst, subst') = |
| 524 |
let val duplicated = |
| 525 |
VarSet.listItems( |
| 526 |
VarSet.intersection |
| 527 |
(VarSet.addList(VarSet.empty, Subst.listKeys subst'), |
| 528 |
VarSet.addList(VarSet.empty, Subst.listKeys subst))) |
| 529 |
in case duplicated of |
| 530 |
[] => () |
| 531 |
| _ => error("duplicated pattern variables: "^ |
| 532 |
listify("",",","") (map Var.toString duplicated)) |
| 533 |
end |
| 534 |
|
| 535 |
(* Or patterns are tricky because the same variable name |
| 536 |
* may be bound to different components. We handle this by renaming |
| 537 |
* all variables to some canonical set of paths, |
| 538 |
* then rename all variables to these paths. |
| 539 |
*) |
| 540 |
fun logicalPat (name, name2, f) [] = error("empty "^name^" pattern") |
| 541 |
| logicalPat (name, name2, f) pats = |
| 542 |
let val results = map (fn p => process(path, empty, p)) pats |
| 543 |
val ps = map #1 results |
| 544 |
val orSubsts = map #2 results |
| 545 |
fun sameVars([], s') = true |
| 546 |
| sameVars(s::ss, s') = |
| 547 |
forall (fn (x,y) => Var.compare(x,y) = EQUAL) |
| 548 |
(Subst.listKeys s, s') andalso |
| 549 |
sameVars(ss, s') |
| 550 |
(* make sure all patterns use the same set of |
| 551 |
* variable names |
| 552 |
*) |
| 553 |
val orNames = Subst.listKeys(hd orSubsts) |
| 554 |
val _ = if sameVars(tl orSubsts, orNames) then () |
| 555 |
else error("not all "^name2^ |
| 556 |
" have the same variable bindings") |
| 557 |
val _ = noDupl(subst, hd orSubsts) |
| 558 |
(* build the new substitution to include all names in the |
| 559 |
* or patterns. |
| 560 |
*) |
| 561 |
|
| 562 |
val subst = Subst.foldri |
| 563 |
(fn (v, _, subst) => Subst.insert(subst,v,VAR v) |
| 564 |
) subst (hd orSubsts) |
| 565 |
in (f(ListPair.zip(orSubsts,ps)), subst) |
| 566 |
end |
| 567 |
|
| 568 |
fun orPat pats = logicalPat ("or", "disjuncts", ORpat) pats |
| 569 |
fun andPat pats = logicalPat ("and", "conjuncts", ANDpat) pats |
| 570 |
|
| 571 |
fun notPat pat = |
| 572 |
let val (pat,subst') = process(path, empty, pat) |
| 573 |
val _ = noDupl(subst,subst') |
| 574 |
in (NOTpat(subst',pat), subst) |
| 575 |
end |
| 576 |
|
| 577 |
fun wherePat(pat, e) = |
| 578 |
let val (pat, subst') = process(path, empty, pat) |
| 579 |
val _ = noDupl(subst,subst') |
| 580 |
in (WHEREpat(pat, subst', e), subst) |
| 581 |
end |
| 582 |
|
| 583 |
fun nestedPat(pat1, e, pat2) = |
| 584 |
let val path' = Path.dot(path, INT ~1) |
| 585 |
val (pat1, subst1) = process(path, subst, pat1) |
| 586 |
val (pat2, subst2) = process(path',subst1, pat2) |
| 587 |
in (NESTEDpat(pat1, subst1, path', e, pat2), subst2) |
| 588 |
end |
| 589 |
|
| 590 |
in doIt {idPat=idPat, |
| 591 |
asPat=asPat, |
| 592 |
wildPat=wildPat, |
| 593 |
consPat=consPat, |
| 594 |
tuplePat=tuplePat, |
| 595 |
recordPat=recordPat, |
| 596 |
litPat=litPat, |
| 597 |
orPat=orPat, |
| 598 |
andPat=andPat, |
| 599 |
notPat=notPat, |
| 600 |
wherePat=wherePat, |
| 601 |
nestedPat=nestedPat |
| 602 |
} pat |
| 603 |
end |
| 604 |
|
| 605 |
fun processAllPats(i, [], subst, ps') = (rev ps', subst) |
| 606 |
| processAllPats(i, p::ps, subst, ps') = |
| 607 |
let val (p, subst) = process(PATH[INT i], subst, p) |
| 608 |
in processAllPats(i+1, ps, subst, p::ps') end |
| 609 |
|
| 610 |
val (pats, subst) = processAllPats(0, pats, empty, []) |
| 611 |
in (rule_no, pats, guard, subst, action) |
| 612 |
end |
| 613 |
|
| 614 |
structure DFAMap = |
| 615 |
RedBlackMapFn(type ord_key = dfa |
| 616 |
fun st(DFA{stamp, ...}) = stamp |
| 617 |
fun compare(x,y) = Int.compare(st x, st y) |
| 618 |
) |
| 619 |
|
| 620 |
(* |
| 621 |
* Give the arguments to case, factor out the common case and make it |
| 622 |
* the default. |
| 623 |
*) |
| 624 |
fun factorCase(p, cases, d as SOME _) = (p, cases, d) |
| 625 |
| factorCase(p, cases, NONE) = |
| 626 |
let fun count(m,dfa) = getOpt(DFAMap.find(m,dfa),0) |
| 627 |
fun inc((_,_,dfa),m) = DFAMap.insert(m, dfa, 1 + count(m, dfa)) |
| 628 |
val m = foldr inc DFAMap.empty cases |
| 629 |
val best = DFAMap.foldri |
| 630 |
(fn (dfa,c,NONE) => SOME(dfa,c) |
| 631 |
| (dfa,c,best as SOME(_,c')) => |
| 632 |
if c > c' then SOME(dfa,c) else best) |
| 633 |
NONE m |
| 634 |
fun neq(DFA{stamp=x, ...},DFA{stamp=y,...}) = x<>y |
| 635 |
in case best of |
| 636 |
NONE => (p, cases, NONE) |
| 637 |
| SOME(_,1) => (p, cases, NONE) |
| 638 |
| SOME(defaultCase,n) => |
| 639 |
let val others = List.filter(fn (_,_,x) => neq(x,defaultCase)) |
| 640 |
cases |
| 641 |
in (p, others, SOME defaultCase) |
| 642 |
end |
| 643 |
end |
| 644 |
|
| 645 |
(* |
| 646 |
* The main pattern matching compiler. |
| 647 |
* The dfa states are constructed with hash consing at the same time |
| 648 |
* so no separate DFA minimization step is needed. |
| 649 |
*) |
| 650 |
fun compile{compiled_rules, compress} = |
| 651 |
let exception NoSuchState |
| 652 |
|
| 653 |
datatype expandType = SWITCH of (decon * path list * matrix) list |
| 654 |
* matrix option |
| 655 |
| PROJECT of path * (path * index) list * matrix |
| 656 |
|
| 657 |
fun simp x = if compress then factorCase x else x |
| 658 |
|
| 659 |
(* Table for hash consing *) |
| 660 |
val dfaTable = DFA.HashTable.mkTable(32,NoSuchState) : |
| 661 |
dfa DFA.HashTable.hash_table |
| 662 |
val lookupState = DFA.HashTable.lookup dfaTable |
| 663 |
val insertState = DFA.HashTable.insert dfaTable |
| 664 |
|
| 665 |
val stampCounter = ref 0 |
| 666 |
|
| 667 |
fun mkState(test) = |
| 668 |
let val stamp = !stampCounter |
| 669 |
in stampCounter := stamp + 1; |
| 670 |
DFA{stamp=stamp, freeVars=ref Name.Set.empty, |
| 671 |
height=ref 0, refCount=ref 0, generated=ref false, test=test} |
| 672 |
end |
| 673 |
|
| 674 |
fun newState test = |
| 675 |
let val s = mkState(test) |
| 676 |
in lookupState s handle NoSuchState => (insertState(s, s); s) |
| 677 |
end |
| 678 |
|
| 679 |
(* State constructors *) |
| 680 |
val fail = newState(FAIL) |
| 681 |
fun Ok x = newState(OK x) |
| 682 |
fun Case(_, [], SOME x) = x |
| 683 |
| Case(_, [], NONE) = fail |
| 684 |
| Case(p, cases as (_,_,c)::cs, default) = |
| 685 |
if List.all(fn (_,_,c') => DFA.eq(c,c')) cs andalso |
| 686 |
(case default of |
| 687 |
SOME x => DFA.eq(c,x) |
| 688 |
| NONE => true |
| 689 |
) |
| 690 |
then c |
| 691 |
else newState(CASE(simp(p, cases, default))) |
| 692 |
fun Select(x) = newState(SELECT(x)) |
| 693 |
fun Cont(x) = newState(CONT(x)) |
| 694 |
fun Where(g, yes, no) = |
| 695 |
if DFA.eq(yes,no) then yes else newState(WHERE(g, yes, no)) |
| 696 |
fun Bind(subst, x) = |
| 697 |
if Subst.numItems subst = 0 then x else newState(BIND(subst, x)) |
| 698 |
fun Let x = newState(LET x) |
| 699 |
|
| 700 |
(* |
| 701 |
* Expand column i, |
| 702 |
* Return a new list of matrixes indexed by the deconstructors. |
| 703 |
*) |
| 704 |
fun expandColumn(m as MATRIX{rows, paths, ...}, i) = |
| 705 |
let val ithCol = Matrix.col(m, i) |
| 706 |
val path_i = Matrix.pathOf(m, i) |
| 707 |
val _ = if debug then |
| 708 |
(print("Expanding column "^i2s i^"\n")) |
| 709 |
else () |
| 710 |
|
| 711 |
fun split_i ps = |
| 712 |
let fun loop(j, p::ps, ps') = |
| 713 |
if i = j then (rev ps', p, ps) |
| 714 |
else loop(j+1, ps, p::ps') |
| 715 |
| loop _ = bug "split_i" |
| 716 |
in loop(0, ps, []) end |
| 717 |
|
| 718 |
(* If the ith column cfind out what to expand *) |
| 719 |
fun expand(WILDpat::ps, this) = expand(ps, this) |
| 720 |
| expand((p as ORpat _)::ps, this) = SOME p |
| 721 |
| expand((p as ANDpat _)::ps, this) = SOME p |
| 722 |
| expand((p as NOTpat _)::ps, this) = SOME p |
| 723 |
| expand((p as WHEREpat _)::ps, this) = SOME p |
| 724 |
| expand((p as NESTEDpat _)::ps, this) = SOME p |
| 725 |
| expand((p as CONTpat _)::ps, this) = SOME p |
| 726 |
| expand((p as TUPLEpat _)::ps, this) = expand(ps, SOME p) |
| 727 |
| expand((p as RECORDpat _)::ps, this) = expand(ps, SOME p) |
| 728 |
| expand((p as APPpat _)::ps, this) = expand(ps, SOME p) |
| 729 |
| expand([], this) = this |
| 730 |
|
| 731 |
(* Split the paths *) |
| 732 |
val (prevPaths, _, nextPaths) = split_i paths |
| 733 |
|
| 734 |
in case expand(ithCol, NONE) of |
| 735 |
SOME(NOTpat _) => (* expand not patterns *) |
| 736 |
let fun expand([], _) = bug "expand NOT" |
| 737 |
| expand((row as {pats, guard, nested, dfa})::rows,rows') = |
| 738 |
let val (prev, pat_i, next) = split_i(pats) |
| 739 |
in case pat_i of |
| 740 |
NOTpat(subst,p) => |
| 741 |
let val rows' = rev rows' |
| 742 |
val yes = {pats=prev@[WILDpat]@next, |
| 743 |
nested=nested, |
| 744 |
guard=guard, dfa=dfa} |
| 745 |
val m2 = MATRIX{rows=rows, paths=paths} |
| 746 |
val no = {pats=prev@[p]@next, guard=NONE, |
| 747 |
nested=[], |
| 748 |
dfa=Bind(subst,match m2)} |
| 749 |
val m1 = MATRIX{rows=rows'@[no,yes]@rows, |
| 750 |
paths=paths} |
| 751 |
in expandColumn(m1, i) end |
| 752 |
| _ => expand(rows, row::rows') |
| 753 |
end |
| 754 |
in expand(rows, []) |
| 755 |
end |
| 756 |
| SOME(ORpat _ | WHEREpat _ | NESTEDpat _) => |
| 757 |
(* if we have or/where patterns then expand all rows |
| 758 |
* with these patterns |
| 759 |
*) |
| 760 |
let fun expand(row as {pats, dfa, nested, guard}) = |
| 761 |
let val (prev, pat_i, next) = split_i(pats) |
| 762 |
in case pat_i of |
| 763 |
ORpat ps => |
| 764 |
map (fn (subst,p) => |
| 765 |
{pats=prev@[p]@next, nested=nested, |
| 766 |
dfa=Bind(subst,dfa), guard=guard}) |
| 767 |
ps |
| 768 |
| WHEREpat(p,subst',g) => |
| 769 |
[{pats=prev@[p]@next, dfa=dfa, nested=nested, |
| 770 |
guard=case guard of |
| 771 |
NONE => SOME(subst',g) |
| 772 |
| SOME(subst,g') => |
| 773 |
SOME(mergeSubst(subst,subst'), |
| 774 |
Guard.logicalAnd(g,g')) |
| 775 |
}] |
| 776 |
| NESTEDpat(pat, subst, path, exp, pat') => |
| 777 |
[{pats=prev@[pat]@next, dfa=dfa, |
| 778 |
nested=(subst,path,exp,pat')::nested, |
| 779 |
guard=guard}] |
| 780 |
| _ => [row] |
| 781 |
end |
| 782 |
val newMatrix = |
| 783 |
MATRIX{rows = List.concat (map expand rows), |
| 784 |
paths = paths |
| 785 |
} |
| 786 |
in expandColumn(newMatrix, i) |
| 787 |
end |
| 788 |
| SOME(TUPLEpat pats) => (* expand a tuple along all the columns *) |
| 789 |
let val arity = length pats |
| 790 |
val wilds = map (fn _ => WILDpat) pats |
| 791 |
fun processRow{pats, nested, dfa, guard} = |
| 792 |
let val (prev, pat_i, next) = split_i(pats) |
| 793 |
in case pat_i of |
| 794 |
TUPLEpat ps' => |
| 795 |
let val n = length ps' |
| 796 |
in if n <> arity then error("tuple arity mismatch") |
| 797 |
else (); |
| 798 |
{pats=prev @ ps' @ next, nested=nested, |
| 799 |
dfa=dfa, guard=guard} |
| 800 |
end |
| 801 |
| WILDpat => |
| 802 |
{pats=prev @ wilds @ next, nested=nested, |
| 803 |
dfa=dfa,guard=guard} |
| 804 |
| pat => error("mixing tuple and: "^Pat.toString pat) |
| 805 |
end |
| 806 |
val rows = map processRow rows |
| 807 |
val path_i' = List.tabulate |
| 808 |
(arity, fn i => Path.dot(path_i, INT i)) |
| 809 |
val paths = prevPaths @ path_i' @ nextPaths |
| 810 |
val bindings = List.tabulate (arity, fn i => |
| 811 |
(Path.dot(path_i, INT i), INT i)) |
| 812 |
in PROJECT(path_i,bindings, |
| 813 |
MATRIX{rows=rows, paths=paths} |
| 814 |
) |
| 815 |
end |
| 816 |
| SOME(RECORDpat _) => (* expand a tuple along all the columns *) |
| 817 |
let (* All the labels that are in this column *) |
| 818 |
val labels = |
| 819 |
VarSet.listItems |
| 820 |
(List.foldr |
| 821 |
(fn (RECORDpat lps, L) => |
| 822 |
List.foldr (fn ((l,p), L) => VarSet.add(L,l)) L lps |
| 823 |
| (_, L) => L) |
| 824 |
VarSet.empty ithCol) |
| 825 |
|
| 826 |
val _ = if debug then |
| 827 |
print("Labels="^listify("",",","") |
| 828 |
(map Var.toString labels)^"\n") |
| 829 |
else () |
| 830 |
|
| 831 |
fun lp2s(l,p) = Var.toString l^"="^Pat.toString p |
| 832 |
fun lps2s lps = listify("","\t","") (map lp2s lps) |
| 833 |
fun ps2s ps = listify("","\t","") (map Pat.toString ps) |
| 834 |
|
| 835 |
val wilds = map (fn _ => WILDpat) labels |
| 836 |
|
| 837 |
fun processRow{pats, nested, dfa, guard} = |
| 838 |
let val (prev, pat_i, next) = split_i(pats) |
| 839 |
in case pat_i of |
| 840 |
RECORDpat lps => |
| 841 |
(* Put lps in canonical order *) |
| 842 |
let val lps = Pat.sortByLabel lps |
| 843 |
val _ = if debug then |
| 844 |
print("lpats="^lps2s lps^"\n") |
| 845 |
else () |
| 846 |
|
| 847 |
fun collect([], [], ps') = rev ps' |
| 848 |
| collect(x::xs, [], ps') = |
| 849 |
collect(xs, [], WILDpat::ps') |
| 850 |
| collect(x::xs, this as (l,p)::lps, ps') = |
| 851 |
(case Var.compare(x,l) of |
| 852 |
EQUAL => collect(xs, lps, p::ps') |
| 853 |
| LESS => collect(xs, this, WILDpat::ps') |
| 854 |
| GREATER => error "labels out of order" |
| 855 |
) |
| 856 |
| collect _ = bug "processRow" |
| 857 |
val ps = collect(labels, lps, []) |
| 858 |
val _ = if debug then |
| 859 |
print("new pats="^ps2s ps^"\n") |
| 860 |
else () |
| 861 |
in {pats=prev @ ps @ next, nested=nested, |
| 862 |
dfa=dfa, guard=guard} |
| 863 |
end |
| 864 |
| WILDpat => |
| 865 |
{pats=prev @ wilds @ next,nested=nested, |
| 866 |
dfa=dfa,guard=guard} |
| 867 |
| pat => error("mixing record and: "^Pat.toString pat) |
| 868 |
end |
| 869 |
|
| 870 |
val rows = map processRow rows |
| 871 |
|
| 872 |
val path_i' = map (fn l => Path.dot(path_i, LABEL l)) labels |
| 873 |
val paths = prevPaths @ path_i' @ nextPaths |
| 874 |
|
| 875 |
val bindings = map (fn l => |
| 876 |
(Path.dot(path_i, LABEL l), LABEL l)) |
| 877 |
labels |
| 878 |
in PROJECT(path_i,bindings, |
| 879 |
MATRIX{rows=rows, paths=paths} |
| 880 |
) |
| 881 |
end |
| 882 |
| SOME(APPpat(decon,_)) => |
| 883 |
(* Find out how many variants are there in this case *) |
| 884 |
let fun getVariants() = |
| 885 |
Decon.Set.listItems |
| 886 |
(List.foldr |
| 887 |
(fn (APPpat(x,_),S) => Decon.Set.add(S,x) |
| 888 |
| (_,S) => S) Decon.Set.empty ithCol) |
| 889 |
|
| 890 |
val (allVariants, hasDefault) = |
| 891 |
case decon of |
| 892 |
CON c => |
| 893 |
let val {known, others} = Con.variants c |
| 894 |
in (case known of [] => getVariants() |
| 895 |
| _ => map CON known, others) |
| 896 |
end |
| 897 |
| LIT l => |
| 898 |
case Literal.variants l of |
| 899 |
SOME{known, others} => (map LIT known, others) |
| 900 |
| NONE => (getVariants(), true) |
| 901 |
|
| 902 |
(* function from con -> matrix; initially no rows |
| 903 |
*) |
| 904 |
fun insert(tbl, key, x) = Decon.Map.insert(tbl, key, x) |
| 905 |
fun lookup(tbl, key) = |
| 906 |
case Decon.Map.find(tbl, key) of |
| 907 |
SOME x => x |
| 908 |
| NONE => bug("can't find constructor "^Decon.toString key) |
| 909 |
val empty = Decon.Map.empty |
| 910 |
|
| 911 |
fun create([], tbl) = tbl |
| 912 |
| create((con as CON c)::cons, tbl) = |
| 913 |
let val n = Con.arity c |
| 914 |
val paths = List.tabulate |
| 915 |
(n, fn i => Path.dot(path_i, INT i)) |
| 916 |
in create(cons, insert(tbl, con, {args=paths, rows=[]})) |
| 917 |
end |
| 918 |
| create((con as LIT l)::cons, tbl) = |
| 919 |
create(cons, insert(tbl, con, {args=[], rows=[]})) |
| 920 |
|
| 921 |
val tbl = create(allVariants, empty) |
| 922 |
|
| 923 |
fun insertRow(tbl, decon, row) = |
| 924 |
let val {args, rows} = lookup(tbl, decon) |
| 925 |
in insert(tbl, decon, {args=args, rows=rows@[row]}) |
| 926 |
end |
| 927 |
|
| 928 |
fun foreachRow([], tbl) = tbl |
| 929 |
| foreachRow({pats, dfa, nested, guard}::rows, tbl) = |
| 930 |
let val (prev, pat_i, next) = split_i pats |
| 931 |
|
| 932 |
fun addRow(tbl, decon, pats) = |
| 933 |
insertRow(tbl, decon, |
| 934 |
{pats=pats, nested=nested, |
| 935 |
dfa=dfa, guard=guard}) |
| 936 |
|
| 937 |
fun addWildToEveryRow(tbl) = |
| 938 |
foldr (fn (c, tbl) => |
| 939 |
let val {args, rows} = lookup(tbl, c) |
| 940 |
val wilds = map (fn _ => WILDpat) args |
| 941 |
val pats = prev @ wilds @ next |
| 942 |
in addRow(tbl, c, pats) |
| 943 |
end) tbl allVariants |
| 944 |
|
| 945 |
val tbl = |
| 946 |
case pat_i of |
| 947 |
WILDpat => addWildToEveryRow tbl |
| 948 |
| APPpat(decon, args) => |
| 949 |
let val pats = prev @ args @ next |
| 950 |
in addRow(tbl, decon, pats) |
| 951 |
end |
| 952 |
| _ => error |
| 953 |
"expecting constructor but found tuple/record" |
| 954 |
in foreachRow(rows, tbl) |
| 955 |
end |
| 956 |
|
| 957 |
val tbl = foreachRow(rows, tbl) |
| 958 |
|
| 959 |
fun collectCases(decon, {args, rows}, rules) = |
| 960 |
let val matrix = |
| 961 |
MATRIX{rows=rows, paths=prevPaths @args@nextPaths} |
| 962 |
in (decon, args, matrix)::rules |
| 963 |
end |
| 964 |
|
| 965 |
val cases = Decon.Map.foldri collectCases [] tbl |
| 966 |
|
| 967 |
(* If we have a default then the default matrix |
| 968 |
* contains the original matrix with rows whose |
| 969 |
* column i is the wild card. |
| 970 |
*) |
| 971 |
val default = |
| 972 |
if hasDefault then |
| 973 |
SOME( |
| 974 |
MATRIX{rows=List.filter |
| 975 |
(fn {pats, ...} => |
| 976 |
case List.nth(pats, i) of |
| 977 |
WILDpat => true |
| 978 |
| _ => false) rows, |
| 979 |
paths=paths} |
| 980 |
) |
| 981 |
else NONE |
| 982 |
|
| 983 |
in SWITCH(Decon.Map.foldri collectCases [] tbl, default) |
| 984 |
end |
| 985 |
| SOME p => bug ("expandColumn: "^Pat.toString p) |
| 986 |
| NONE => bug "expandColumn" |
| 987 |
end (* expandColumn *) |
| 988 |
|
| 989 |
(* |
| 990 |
* Generate the DFA |
| 991 |
*) |
| 992 |
and match matrix = |
| 993 |
if Matrix.isEmpty matrix then fail |
| 994 |
else |
| 995 |
case Matrix.findBestMatchColumn matrix of |
| 996 |
NONE => (* first row is all wild cards *) |
| 997 |
(case Matrix.row(matrix, 0) of |
| 998 |
{guard=SOME(subst, g), nested=[], dfa, ...} => |
| 999 |
(* generate guard *) |
| 1000 |
Bind(subst, |
| 1001 |
Where(g, dfa, |
| 1002 |
match(Matrix.removeFirstRow matrix))) |
| 1003 |
| {guard=NONE, dfa, nested=[], ...} => dfa |
| 1004 |
| {guard, pats, nested=n::ns, dfa, ...} => |
| 1005 |
(* handle nested pats *) |
| 1006 |
let val (subst, path, exp, pat) = n |
| 1007 |
val MATRIX{rows, paths} = matrix |
| 1008 |
val row0 = {guard=guard, pats=pat::pats, |
| 1009 |
nested=ns, dfa=dfa} |
| 1010 |
val rows' = tl rows |
| 1011 |
val rows' = map (fn {pats, nested, dfa, guard} => |
| 1012 |
{pats=WILDpat::pats, nested=nested, dfa=dfa, |
| 1013 |
guard=guard}) rows' |
| 1014 |
val m = MATRIX{rows=row0::rows', paths=path::paths} |
| 1015 |
in Bind(subst, Let(path, exp, match m)) |
| 1016 |
end |
| 1017 |
) |
| 1018 |
| SOME i => |
| 1019 |
(* mixture rule; split at column i *) |
| 1020 |
(case expandColumn(matrix, i) of |
| 1021 |
(* splitting a constructor *) |
| 1022 |
SWITCH(cases, default) => |
| 1023 |
let val cases = map (fn (c,p,m) => (c,p,match m)) cases |
| 1024 |
in Case(Matrix.pathOf(matrix, i), cases, |
| 1025 |
Option.map match default) |
| 1026 |
end |
| 1027 |
(* splitting a tuple or record; |
| 1028 |
* recompute new bindings. |
| 1029 |
*) |
| 1030 |
| PROJECT(p,bindings,m) => Select(p, bindings, match m) |
| 1031 |
) |
| 1032 |
|
| 1033 |
fun makeMatrix rules = |
| 1034 |
let val (_, pats0, _, _, _) = hd rules |
| 1035 |
val arity = length pats0 |
| 1036 |
fun makeRow(r, pats, NONE, subst, action) = |
| 1037 |
{pats=pats, guard=NONE, nested=[], |
| 1038 |
dfa=Bind(subst, Ok(r, action))} |
| 1039 |
| makeRow(r, pats, SOME g, subst, action) = |
| 1040 |
{pats=pats, guard=SOME(subst,g), nested=[], |
| 1041 |
dfa=Ok(r, action)} |
| 1042 |
|
| 1043 |
in MATRIX{rows = map makeRow rules, |
| 1044 |
paths = List.tabulate(arity, fn i => PATH[INT i]) |
| 1045 |
} |
| 1046 |
end |
| 1047 |
|
| 1048 |
val dfa = match(makeMatrix compiled_rules) |
| 1049 |
|
| 1050 |
val rule_nos = map #1 compiled_rules |
| 1051 |
|
| 1052 |
(* |
| 1053 |
* 1. Update the reference counts. |
| 1054 |
* 2. Compute the set of free path variables at each state. |
| 1055 |
* 3. Compute the set of path variables that are actually used. |
| 1056 |
* 4. Compute the height of each node. |
| 1057 |
*) |
| 1058 |
exception NotVisited |
| 1059 |
val visited = IntHashTable.mkTable (32, NotVisited) |
| 1060 |
fun mark s = IntHashTable.insert visited (s,true) |
| 1061 |
fun isVisited s = getOpt(IntHashTable.find visited s, false) |
| 1062 |
|
| 1063 |
fun set(fv, s) = (fv := s; s) |
| 1064 |
fun setH(height, h) = (height := h; h) |
| 1065 |
val union = Name.Set.union |
| 1066 |
val diff = Name.Set.difference |
| 1067 |
val add = Name.Set.add |
| 1068 |
val empty = Name.Set.empty |
| 1069 |
|
| 1070 |
fun diffPaths(fvs, ps) = |
| 1071 |
diff(fvs, Name.Set.addList(Name.Set.empty, map PVAR ps)) |
| 1072 |
|
| 1073 |
val used = ref Name.Set.empty |
| 1074 |
fun occurs s = used := Name.Set.union(!used,s) |
| 1075 |
val redundant = ref(IntListSet.addList(IntListSet.empty, rule_nos)) |
| 1076 |
fun ruleUsed r = redundant := IntListSet.delete(!redundant, r) |
| 1077 |
fun vars subst = Name.Set.addList(empty,Subst.listItems subst) |
| 1078 |
|
| 1079 |
fun visit(DFA{stamp, refCount, test, freeVars, height, ...},PVs) = |
| 1080 |
(refCount := !refCount + 1; |
| 1081 |
if isVisited stamp then (!freeVars, !height) |
| 1082 |
else (mark stamp; |
| 1083 |
case test of |
| 1084 |
FAIL => (empty, 0) |
| 1085 |
| BIND(subst, dfa) => |
| 1086 |
let val patvars = Name.Set.addList(empty, |
| 1087 |
map VAR (Subst.listKeys subst)) |
| 1088 |
val (s, h) = visit(dfa, union(PVs, patvars)) |
| 1089 |
val variables = vars subst |
| 1090 |
val s' = union(s, variables) |
| 1091 |
val s' = diff(s', patvars) |
| 1092 |
in occurs s'; |
| 1093 |
(set(freeVars, s'), setH(height, h + 1)) |
| 1094 |
end |
| 1095 |
| LET(p, _, dfa) => |
| 1096 |
let val (s, h) = visit(dfa, PVs) |
| 1097 |
in (set(freeVars, s), setH(height, h+1)) |
| 1098 |
end |
| 1099 |
| OK(rule_no, action) => |
| 1100 |
let val fvs = Name.Set.addList(empty, |
| 1101 |
map VAR(Action.freeVars action)) |
| 1102 |
(* val _ = |
| 1103 |
(print("Action = "^Action.toString action^"\n"); |
| 1104 |
print("PVs = "^Name.setToString PVs^"\n"); |
| 1105 |
print("FVs = "^Name.setToString fvs^"\n") |
| 1106 |
) *) |
| 1107 |
val fvs = Name.Set.intersection(PVs, fvs) |
| 1108 |
in ruleUsed rule_no; |
| 1109 |
(set(freeVars, fvs), 0) |
| 1110 |
end |
| 1111 |
| CASE(p, cases, opt) => |
| 1112 |
let val (fvs, h) = |
| 1113 |
List.foldr (fn ((_,ps,x),(s, h)) => |
| 1114 |
let val (fv,h') = visit(x, PVs) |
| 1115 |
val fv = diffPaths(fv, ps) |
| 1116 |
in (union(fv,s), Int.max(h,h')) |
| 1117 |
end) |
| 1118 |
(empty, 0) cases |
| 1119 |
val (fvs, h) = |
| 1120 |
case opt of NONE => (fvs, h) |
| 1121 |
| SOME x => |
| 1122 |
let val (fv, h') = visit(x, PVs) |
| 1123 |
in (union(fvs,fv), Int.max(h,h')) |
| 1124 |
end |
| 1125 |
val fvs = add(fvs, PVAR p) |
| 1126 |
in occurs fvs; |
| 1127 |
(set(freeVars, fvs), setH(height, h+1)) |
| 1128 |
end |
| 1129 |
| WHERE(_, y, n) => |
| 1130 |
let val (sy, hy) = visit(y, PVs) |
| 1131 |
val (sn, hn) = visit(n, PVs) |
| 1132 |
val s = union(sy, sn) |
| 1133 |
val h = Int.max(hy,hn) + 1 |
| 1134 |
in occurs s; |
| 1135 |
(set(freeVars, s), setH(height, h)) |
| 1136 |
end |
| 1137 |
| SELECT(p, bs, x) => |
| 1138 |
let val (s, h) = visit(x, PVs) |
| 1139 |
val s = add(s, PVAR p) |
| 1140 |
val bs = foldr (fn ((p,_),S) => add(S,PVAR p)) s bs |
| 1141 |
val fvs = diff(s, bs) |
| 1142 |
in occurs bs; |
| 1143 |
(set(freeVars, fvs), setH(height,h+1)) |
| 1144 |
end |
| 1145 |
| CONT(k, x) => |
| 1146 |
let val (s, h) = visit(x, PVs) |
| 1147 |
in (* always generate a state function *) |
| 1148 |
refCount := !refCount + 1; |
| 1149 |
(set(freeVars, s), setH(height,h+1)) |
| 1150 |
end |
| 1151 |
) |
| 1152 |
) |
| 1153 |
val _ = visit(dfa, empty); |
| 1154 |
val DFA{refCount=failCount, ...} = fail |
| 1155 |
in ROOT{used = !used, |
| 1156 |
dfa = dfa, |
| 1157 |
exhaustive= !failCount = 0, |
| 1158 |
redundant= !redundant |
| 1159 |
} |
| 1160 |
end |
| 1161 |
|
| 1162 |
fun exhaustive(ROOT{exhaustive, ...}) = exhaustive |
| 1163 |
fun redundant(ROOT{redundant, ...}) = redundant |
| 1164 |
|
| 1165 |
(* |
| 1166 |
* Generate final code for pattern matching. |
| 1167 |
*) |
| 1168 |
fun codeGen |
| 1169 |
{ genFail : unit -> 'exp, |
| 1170 |
genOk, |
| 1171 |
genPath, |
| 1172 |
genBind, |
| 1173 |
genCase, |
| 1174 |
genIf : Guard.guard * 'exp * 'exp -> 'exp, |
| 1175 |
genGoto, |
| 1176 |
genFun, |
| 1177 |
genLet : 'decl list * 'exp -> 'exp, |
| 1178 |
genProj : path * (path option * index) list -> 'decl, |
| 1179 |
genVar : path -> Var.var, |
| 1180 |
genVal : Var.var * 'exp -> 'decl, |
| 1181 |
genCont |
| 1182 |
} (root, dfa) = |
| 1183 |
let |
| 1184 |
val ROOT{dfa, used, ...} = dfa |
| 1185 |
|
| 1186 |
fun genPat p = if Name.Set.member(used, PVAR p) then SOME p else NONE |
| 1187 |
(* fun arg p = SOME p *) |
| 1188 |
|
| 1189 |
fun mkVars freeVarSet = |
| 1190 |
map (fn PVAR p => genVar p |
| 1191 |
| VAR v => v |
| 1192 |
) (Name.Set.listItems (!freeVarSet)) |
| 1193 |
|
| 1194 |
fun enque(dfa,(F,B)) = (F,dfa::B) |
| 1195 |
val emptyQueue = ([], []) |
| 1196 |
|
| 1197 |
(* Walk a state, if it is shared then just generate a goto to the |
| 1198 |
* state function; otherwise expand it |
| 1199 |
*) |
| 1200 |
fun walk(dfa as DFA{stamp, refCount, generated, freeVars, ...}, |
| 1201 |
workList) = |
| 1202 |
if !refCount > 1 then |
| 1203 |
(* just generate a goto *) |
| 1204 |
let val code = genGoto(stamp, mkVars freeVars) |
| 1205 |
in if !generated then (code, workList) |
| 1206 |
else (generated := true; (code, enque(dfa,workList))) |
| 1207 |
end |
| 1208 |
else |
| 1209 |
expandDfa(dfa, workList) |
| 1210 |
|
| 1211 |
(* generate a new function definition *) |
| 1212 |
and genNewFun(dfa as DFA{stamp, freeVars, height, ...}, workList) = |
| 1213 |
let val (body, workList) = expandDfa(dfa, workList) |
| 1214 |
in ((!height,genFun(stamp, mkVars freeVars, body)), workList) |
| 1215 |
end |
| 1216 |
|
| 1217 |
and expandYesNo(yes, no, workList) = |
| 1218 |
let val (yes, workList) = walk(yes, workList) |
| 1219 |
val (no, workList) = walk(no, workList) |
| 1220 |
in (yes, no, workList) |
| 1221 |
end |
| 1222 |
|
| 1223 |
(* expand the dfa always *) |
| 1224 |
and expandDfa(DFA{stamp, test, freeVars, ...}, workList) = |
| 1225 |
(case test of |
| 1226 |
(* action *) |
| 1227 |
OK(rule_no, action) => (genOk(action), workList) |
| 1228 |
(* failure *) |
| 1229 |
| FAIL => (genFail(), workList) |
| 1230 |
(* guard *) |
| 1231 |
| BIND(subst, dfa) => |
| 1232 |
let val (code, workList) = walk(dfa, workList) |
| 1233 |
val bindings = |
| 1234 |
Subst.foldri |
| 1235 |
(fn (v,PVAR p,b) => (v,genPath p)::b |
| 1236 |
| (v,VAR v',b) => b |
| 1237 |
) [] subst |
| 1238 |
in (genLet(genBind bindings, code), workList) |
| 1239 |
end |
| 1240 |
| LET(path, (_, e), dfa) => |
| 1241 |
let val (code, workList) = walk(dfa, workList) |
| 1242 |
in (genLet(genBind [(genVar path,e)], code), workList) |
| 1243 |
end |
| 1244 |
| WHERE(g, yes, no) => |
| 1245 |
let val (yes, no, workList) = expandYesNo(yes, no, workList) |
| 1246 |
in (genIf(g, yes, no), workList) |
| 1247 |
end |
| 1248 |
(* case *) |
| 1249 |
| CASE(path, cases, default) => |
| 1250 |
let val (cases, workList) = |
| 1251 |
List.foldr |
| 1252 |
(fn ((con, paths, dfa), (cases, workList)) => |
| 1253 |
let val (code, workList) = walk(dfa, workList) |
| 1254 |
in ((con, map genPat paths, code)::cases, workList) |
| 1255 |
end |
| 1256 |
) ([], workList) cases |
| 1257 |
|
| 1258 |
(* find the most common case and make it the default *) |
| 1259 |
|
| 1260 |
val (default, workList) = |
| 1261 |
case default of |
| 1262 |
NONE => (NONE, workList) |
| 1263 |
| SOME dfa => |
| 1264 |
let val (code, workList) = walk(dfa, workList) |
| 1265 |
in (SOME code, workList) end |
| 1266 |
|
| 1267 |
in (genCase(genVar path, cases, default), workList) |
| 1268 |
end |
| 1269 |
| SELECT(path, bindings, body) => |
| 1270 |
let val (body, workList) = walk(body, workList) |
| 1271 |
val bindings = map (fn (p,v) => (SOME p,v)) bindings |
| 1272 |
in (genLet([genProj(path, bindings)], body), workList) |
| 1273 |
end |
| 1274 |
| CONT(k, body) => |
| 1275 |
let val (body, workList) = walk(body, workList) |
| 1276 |
in (genLet([genCont(k, stamp, mkVars freeVars)],body),workList) |
| 1277 |
end |
| 1278 |
) |
| 1279 |
|
| 1280 |
(* Generate code for the dfa; accumulate all the auxiliary |
| 1281 |
* functions together and generate a let. |
| 1282 |
*) |
| 1283 |
fun genAll(root,dfa) = |
| 1284 |
let val (exp, workList) = walk(dfa, emptyQueue) |
| 1285 |
fun genAuxFunctions(([], []), funs) = funs |
| 1286 |
| genAuxFunctions(([], B), funs) = |
| 1287 |
genAuxFunctions((rev B,[]), funs) |
| 1288 |
| genAuxFunctions((dfa::F,B), funs) = |
| 1289 |
let val (newFun, workList) = genNewFun(dfa, (F, B)) |
| 1290 |
in genAuxFunctions(workList, newFun :: funs) |
| 1291 |
end |
| 1292 |
val rootDecl = genVal(genVar(PATH [INT 0]), root) |
| 1293 |
val funs = genAuxFunctions(workList, []) |
| 1294 |
(* order the functions by dependencies; sort by lowest height *) |
| 1295 |
val funs = ListMergeSort.sort |
| 1296 |
(fn ((h,_),(h',_)) => h > h') funs |
| 1297 |
val funs = map #2 funs |
| 1298 |
in genLet(rootDecl::funs, exp) |
| 1299 |
end |
| 1300 |
in genAll(root,dfa) |
| 1301 |
end |
| 1302 |
|
| 1303 |
end |
| 1304 |
|
| 1305 |
end (* local *) |