| 1 |
(* compute-first1.sml |
| 2 |
* |
| 3 |
* COPYRIGHT (c) 2005 John Reppy (http://www.cs.uchicago.edu/~jhr) |
| 4 |
* All rights reserved. |
| 5 |
*) |
| 6 |
|
| 7 |
structure ComputeFirst1 : sig |
| 8 |
|
| 9 |
datatype result = Result of { |
| 10 |
firstOf : LLKSpec.nonterm -> Token.Set.set, |
| 11 |
firstOfItem : LLKSpec.item -> Token.Set.set, |
| 12 |
firstOfItems : LLKSpec.item list -> Token.Set.set |
| 13 |
} |
| 14 |
|
| 15 |
val compute : LLKSpec.prod list |
| 16 |
* ComputeNullable.result |
| 17 |
-> result |
| 18 |
|
| 19 |
end = struct |
| 20 |
|
| 21 |
structure TSet = Token.Set |
| 22 |
structure NMap = Nonterm.Map |
| 23 |
structure P = Predict |
| 24 |
|
| 25 |
datatype result = Result of { |
| 26 |
firstOf : LLKSpec.nonterm -> Token.Set.set, |
| 27 |
firstOfItem : LLKSpec.item -> Token.Set.set, |
| 28 |
firstOfItems : LLKSpec.item list -> Token.Set.set |
| 29 |
} |
| 30 |
|
| 31 |
fun compute (rules, nres) = let |
| 32 |
val ComputeNullable.Result |
| 33 |
{nullable, nullableItem, nullableItems} = nres |
| 34 |
fun firstOf nm nt = |
| 35 |
Option.getOpt (NMap.find (nm, nt), TSet.empty) |
| 36 |
fun firstOfItem nm item = (case item |
| 37 |
of (LLKSpec.TOK tok) => P.mkTok tok |
| 38 |
| (LLKSpec.NONTERM nt) => firstOf nm nt |
| 39 |
| (LLKSpec.CLOS nt) => firstOf nm nt |
| 40 |
| (LLKSpec.POSCLOS nt) => firstOf nm nt |
| 41 |
| (LLKSpec.OPT nt) => firstOf nm nt |
| 42 |
(* end case *)) |
| 43 |
and firstOfItems nm items = let |
| 44 |
fun iter (fs, []) = fs |
| 45 |
| iter (fs, item::rest) = let |
| 46 |
val fs' = TSet.union (fs, firstOfItem nm item) |
| 47 |
in if nullableItem item |
| 48 |
then iter (fs', rest) |
| 49 |
else fs' |
| 50 |
end |
| 51 |
in iter (TSet.empty, items) |
| 52 |
end |
| 53 |
fun doRule (LLKSpec.PROD{lhs, rhs, ...}, (nm, changed)) = let |
| 54 |
val toks = firstOf nm lhs |
| 55 |
val toks' = TSet.union (toks, firstOfItems nm rhs) |
| 56 |
val nm' = NMap.insert (nm, lhs, toks') |
| 57 |
in |
| 58 |
(nm', changed |
| 59 |
orelse (TSet.numItems toks' > TSet.numItems toks)) |
| 60 |
end |
| 61 |
fun loopToFixedPt nm = let |
| 62 |
val (nm', changed) = List.foldl doRule (nm, false) rules |
| 63 |
in if changed then loopToFixedPt nm' else nm' |
| 64 |
end |
| 65 |
val nm = loopToFixedPt NMap.empty |
| 66 |
in Result { |
| 67 |
firstOf = firstOf nm, |
| 68 |
firstOfItem = firstOfItem nm, |
| 69 |
firstOfItems = firstOfItems nm |
| 70 |
} |
| 71 |
end |
| 72 |
|
| 73 |
end |