| 1 |
(* match.sml |
| 2 |
* |
| 3 |
* COPYRIGHT (c) 2005 |
| 4 |
* John Reppy (http://www.cs.uchicago.edu/~jhr) |
| 5 |
* Aaron Turon ([email protected]) |
| 6 |
* All rights reserved. |
| 7 |
* |
| 8 |
* A simple match "backend" that runs the produced state machine directly |
| 9 |
* on stdin. Treats end of line as end of input. Note that a match only |
| 10 |
* occurs if the machine is in an accepting state after consuming the |
| 11 |
* complete input; in particular, the input is meant to represent a single |
| 12 |
* token, and the machine does not restart until the end of input. |
| 13 |
* |
| 14 |
**************************************************************** |
| 15 |
* NOTE! NOT UNICODE COMPATIBLE |
| 16 |
**************************************************************** |
| 17 |
*) |
| 18 |
|
| 19 |
structure Match : OUTPUT = |
| 20 |
struct |
| 21 |
|
| 22 |
structure SIS = RegExp.SymSet |
| 23 |
structure LO = LexOutputSpec |
| 24 |
|
| 25 |
fun match (LO.State{id, label, final, next, ...}, []) = final |
| 26 |
| match (LO.State{id, label, final, next, ...}, sym::r) = let |
| 27 |
fun goto [] = [] |
| 28 |
| goto ((syms, s)::r') = |
| 29 |
if SIS.member (syms, sym) |
| 30 |
then match(s, r) |
| 31 |
else goto r' |
| 32 |
in |
| 33 |
goto (!next) |
| 34 |
end |
| 35 |
|
| 36 |
fun matchLoop states = (case TextIO.inputLine (TextIO.stdIn) |
| 37 |
of NONE => () |
| 38 |
| SOME "\n" => () |
| 39 |
| SOME s => let |
| 40 |
val chars = List.rev (List.tl (List.rev (String.explode s))) |
| 41 |
val syms = List.map (Word.fromInt o Char.ord) chars |
| 42 |
val q0 as LO.State {label, ...} = List.hd states |
| 43 |
val _ = case match (q0, syms) |
| 44 |
of [] => print "-- No match --\n" |
| 45 |
| i::_ => |
| 46 |
(print "-- Match: "; |
| 47 |
print (RegExp.toString (Vector.sub (label, i))); |
| 48 |
print " --\n") |
| 49 |
in |
| 50 |
(* continue I/O loop *) |
| 51 |
matchLoop states |
| 52 |
end |
| 53 |
(* end case *)) |
| 54 |
|
| 55 |
fun output (LO.Spec {dfa, ...}, _) = |
| 56 |
matchLoop(dfa) |
| 57 |
|
| 58 |
end |