| 1 |
(* compute-follow1.sml |
| 2 |
* |
| 3 |
* COPYRIGHT (c) 2006 |
| 4 |
* John Reppy (http://www.cs.uchicago.edu/~jhr) |
| 5 |
* Aaron Turon (http://www.cs.uchicago.edu/~adrassi) |
| 6 |
* All rights reserved. |
| 7 |
*) |
| 8 |
|
| 9 |
structure ComputeFollow1 : sig |
| 10 |
|
| 11 |
datatype result = Result of { |
| 12 |
followOf : LLKSpec.nonterm -> Token.Set.set |
| 13 |
} |
| 14 |
|
| 15 |
val compute : LLKSpec.prod list |
| 16 |
* ComputeNullable.result |
| 17 |
* ComputeFirst1.result |
| 18 |
-> result |
| 19 |
|
| 20 |
end = struct |
| 21 |
|
| 22 |
structure TSet = Token.Set |
| 23 |
structure NMap = Nonterm.Map |
| 24 |
|
| 25 |
datatype result = Result of { |
| 26 |
followOf : LLKSpec.nonterm -> Token.Set.set |
| 27 |
} |
| 28 |
|
| 29 |
fun getNT (LLKSpec.TOK _) = NONE |
| 30 |
| getNT (LLKSpec.NONTERM nt) = SOME nt |
| 31 |
| getNT (LLKSpec.CLOS nt) = SOME nt |
| 32 |
| getNT (LLKSpec.POSCLOS nt) = SOME nt |
| 33 |
| getNT (LLKSpec.OPT nt) = SOME nt |
| 34 |
|
| 35 |
fun compute (rules, nres, fres) = let |
| 36 |
val ComputeNullable.Result |
| 37 |
{nullable, nullableItem, nullableItems} = nres |
| 38 |
val ComputeFirst1.Result |
| 39 |
{firstOf, firstOfItem, firstOfItems} = fres |
| 40 |
fun followOf nm nt = |
| 41 |
Option.getOpt (NMap.find (nm, nt), TSet.empty) |
| 42 |
fun doRule (LLKSpec.PROD{lhs, rhs, ...}, (nm, changed)) = let |
| 43 |
val lhsToks = followOf nm lhs |
| 44 |
fun iter (nm, changed, []) = (nm, changed) |
| 45 |
| iter (nm, changed, item::prec) = let |
| 46 |
val (nm', changed') = |
| 47 |
case getNT item |
| 48 |
of SOME nt => let |
| 49 |
val toks = followOf nm nt |
| 50 |
val toks' = TSet.union (lhsToks, toks) |
| 51 |
val changed' = changed |
| 52 |
orelse (TSet.numItems toks' > TSet.numItems toks) |
| 53 |
val nm' = NMap.insert (nm, nt, toks') |
| 54 |
in |
| 55 |
(nm', changed') |
| 56 |
end |
| 57 |
| NONE => (nm, changed) |
| 58 |
in |
| 59 |
if nullableItem item then |
| 60 |
iter (nm', changed', prec) |
| 61 |
else (nm', changed') |
| 62 |
end |
| 63 |
in |
| 64 |
iter (nm, false, List.rev rhs) |
| 65 |
end |
| 66 |
fun loopToFixedPt nm = let |
| 67 |
val (nm', changed) = List.foldl doRule (nm, false) rules |
| 68 |
in if changed then loopToFixedPt nm' else nm' |
| 69 |
end |
| 70 |
fun initRule (LLKSpec.PROD{lhs, rhs, ...}, nm) = let |
| 71 |
fun iter (nm, []) = nm |
| 72 |
| iter (nm, item::rest) = (case getNT item |
| 73 |
of SOME nt => let |
| 74 |
val toks = followOf nm nt |
| 75 |
val toks' = TSet.union (toks, firstOfItems rest) |
| 76 |
val nm' = NMap.insert (nm, nt, toks') |
| 77 |
in |
| 78 |
iter (nm', rest) |
| 79 |
end |
| 80 |
| NONE => iter (nm, rest) |
| 81 |
(* end case *)) |
| 82 |
in |
| 83 |
iter (nm, rhs) |
| 84 |
end |
| 85 |
val nm = loopToFixedPt (List.foldl initRule NMap.empty rules) |
| 86 |
in Result { |
| 87 |
followOf = followOf nm |
| 88 |
} |
| 89 |
end |
| 90 |
|
| 91 |
end |
| 92 |
|