source: proto/RE/Haskell/CanonicalRE.hs @ 3599

Last change on this file since 3599 was 3599, checked in by cameron, 5 years ago

Haskell prototype interpreter and regular expression simulator

File size: 9.2 KB
Line 
1-- Module Canonical_RE is a canonical representation for regular
2-- expressions that uses a minimum number of alternative forms,
3-- for example, in comparison with module RE_Proto.
4-- Use of this canonical representation should simplify transformation and
5-- analysis algorithms. 
6-- Compare for example, RE_proto.minMatchLen with CanonicalRE.minMatchLen
7
8
9module CanonicalRE (RE(..), canonicalize, minMatchLen, removeNullablePrefix) where
10       
11import qualified RE_Proto as Proto
12import Data.Char
13import RunPablo
14
15data RepLimit = UpperBound Int | Unbounded deriving Show
16upper_bound_dec :: RepLimit -> RepLimit
17upper_bound_dec (UpperBound j) = UpperBound (j - 1)
18upper_bound_dec Unbounded = Unbounded
19
20data RE = CC String | Seq [RE] | Alt [RE] | Rep RE Int RepLimit |
21          Start | End  -- lookbehind/lookahead assertions for newline
22          deriving Show
23-- Rep r i j represents UpperBound repetition, with lower bound i and
24-- upper bound j.   We use the convention that any negative value of
25-- j represents Unbounded repetition.
26
27canonicalize :: Proto.RE -> RE
28canonicalize (Proto.CC s) = CC s
29canonicalize (Proto.CCnot s) =  CC (filter (\c -> not(elem c s)) (map chr ([0..9]++[11..127])))
30canonicalize (Proto.Lit s) = Seq (map (\c -> CC [c]) s)
31canonicalize Proto.Start = Start
32canonicalize Proto.End = End
33canonicalize Proto.Any = CC (map chr ([0..9]++[11..127]))
34canonicalize (Proto.Join rs) = Seq (map canonicalize rs)
35canonicalize (Proto.Alt rs) = Alt (map canonicalize rs)
36canonicalize (Proto.Opt r) = Rep (canonicalize r) 0 (UpperBound 1) 
37canonicalize (Proto.Kstar r) = Rep (canonicalize r) 0 Unbounded
38canonicalize (Proto.Kplus r) = Rep (canonicalize r) 1 Unbounded
39canonicalize (Proto.OrMore i r) = Rep (canonicalize r) i Unbounded
40canonicalize (Proto.Bounded i j r) = Rep (canonicalize r) i (UpperBound j)
41
42
43-- Write a minimal match length function that determines the minimum length
44-- string that can be matched by an RE, considering that Start and End match
45-- single \n characterProto.
46
47minMatchLen :: RE -> Int
48minMatchLen (CC s) = 1
49minMatchLen Start = 1
50minMatchLen End = 1
51minMatchLen (Seq []) = 0
52minMatchLen (Seq (r:rs)) = minMatchLen r + (minMatchLen (Seq rs))
53minMatchLen (Alt [r]) = minMatchLen r
54minMatchLen (Alt (r:rs)) = min (minMatchLen r) (minMatchLen (Alt rs))
55minMatchLen (Rep r i j) = i * (minMatchLen r)
56
57--- removeNullablePrefix takes a regular expression and returns
58--- the version of it that has been transformed to remove any nullable
59--- prefixeProto.  A prefix p is nullable if it can possibly match the empty
60--- string, i.e., minMatchLen(p) = 0.  For example, in the regexp
61--- [a-z]*-[0-9]+ the prefix [a-z]* is nullable.
62
63removeNullablePrefix :: RE -> RE
64removeNullablePrefix (CC s) = (CC s)
65removeNullablePrefix Start = Start
66removeNullablePrefix End = End
67removeNullablePrefix (Seq []) = Seq []
68removeNullablePrefix (Seq (r:rs))
69   | minMatchLen(r) == 0  = removeNullablePrefix(Seq rs)
70   | otherwise            = Seq ((removeNullablePrefix r):rs)
71removeNullablePrefix (Alt rs) = Alt (map removeNullablePrefix rs)
72removeNullablePrefix (Rep r 0 ub) = Seq []
73removeNullablePrefix (Rep r lb ub)
74   | minMatchLen(r) == 0  = Seq []
75   | otherwise            = Seq [removeNullablePrefix(r), Rep r (lb-1) (upper_bound_dec ub)]
76
77
78--
79-- The Symbol Environment keeps track of the symbols generated
80-- during compilation, so that new unique symbols can be
81-- generated (gensym) as needed.   All symbols are formed from
82-- a string prefix and a numeric suffix.
83--
84-- For example, if the symbols "marker0", "marker1", "condition0"
85-- have been generated and no others have, the environment is
86-- [("marker", 1), ("condition", 0)]
87--
88type Env = [(String, Int)]
89
90gensym :: (Env, String) -> (Env, String)
91gensym ([], s) = ([(s, 0)], s ++ show 0)
92gensym ((prefix1, count1):env, s) 
93  | prefix1 == s = ((s, count1+1):env, s ++ show(count1+1))
94  | otherwise    = ((prefix1, count1):newenv, newsym)
95  where (newenv, newsym) = gensym(env, s)
96
97
98--
99-- To keep track of the current context for code generation during
100-- compilation, we define a CodeGenState that represents the output
101-- at each compilation step.   This state consists of an environment
102-- defining the symbols used so far, the sequence of generated PabloS
103-- statements generated so far and the name of the variable that
104-- holds the match result for the overall expression so far.
105--
106type CodeGenState = (Env, [PabloS], String)
107
108--
109-- In compiling to regular expression form, we use a helper function
110-- that takes a regular expression and a code generation state, and
111-- returns the code generation state.   The main compile routine
112-- initializes the process by setting an initial marker stream
113-- of all ones.
114--
115--
116compile :: RE -> CodeGenState
117re2pablo_helper :: (RE, CodeGenState) -> CodeGenState
118
119
120compile(re) = re2pablo_helper(re, (env, [Assign(marker, All(1))], marker))
121  where 
122    (env, marker) = gensym([], "start_marker")
123
124-- To match a character class, use bitwise and of the marker and
125-- character class, then advance 1. 
126
127re2pablo_helper(CC(c), (env, stmts, last_marker)) = (newenv, stmts ++ [new_stmt], newsym)
128   where 
129     (newenv, newsym) = gensym(env, "marker")
130     new_stmt = Assign (newsym, Advance(And(Var(last_marker), CharClass(c))))
131
132-- To match "^" we must be at the start of line, i.e., one past
133-- a newline character or at the beginning of file.  We use the
134-- trick of advancing the negated newline stream to determine these
135-- positions.
136--
137re2pablo_helper(Start, (env, stmts, last_marker)) = (newenv, stmts ++ [new_stmt], newsym)
138   where 
139     (newenv, newsym) = gensym(env, "start_of_line_marker")
140     new_stmt = Assign (newsym, And(Var(last_marker), Not(Advance(Not(CharClass("\n"))))))
141
142-- To match "$" we must have reached end of line.
143--
144re2pablo_helper(End, (env, stmts, last_marker)) = (newenv, stmts ++ [new_stmt], newsym)
145   where 
146     (newenv, newsym) = gensym(env, "end_of_line_marker")
147     new_stmt = Assign (newsym, And(Var(last_marker), CharClass("\n")))
148
149-- Seq [] is the empty regexp which matches the empty string. 
150-- We just leave the current marker unchanged, with no new statements
151-- needed to compute it.
152--
153re2pablo_helper(Seq [], cg_state) = cg_state
154
155-- Seq (r1:rs): generate code to match r1, the first subexpression,
156-- then to match the rest, concatenating the statements.
157re2pablo_helper(Seq (r1:rs), cg_state) = re2pablo_helper(Seq rs, re2pablo_helper(r1, cg_state))
158 
159-- Alt[r] has a single alternative r to match, just match
160-- it with no other possibility.
161re2pablo_helper(Alt [r], cg_state) = re2pablo_helper(r, cg_state)
162
163-- For completeness, we define Alt[] as the regular expression that
164-- always fails (since no alternatives will match).
165re2pablo_helper(Alt [], (env, stmts, last_marker)) = (newenv, stmts ++ [new_stmt], newsym)
166   where 
167     (newenv, newsym) = gensym(env, "always_fail_marker")
168     new_stmt = Assign (newsym, All(0))
169
170-- Alt (r1:rs): we have r1 and some other alternatives, the
171-- match succeeds if either r1 matches or any of the others
172-- does.
173re2pablo_helper(Alt (r1:rs), (env, stmts, last_marker)) = (newenv, new_stmts, newsym)
174  where 
175   (e1, s1, alt1_marker) = re2pablo_helper(r1, (env, stmts, last_marker))
176   (e2, s2, alt2_marker) = re2pablo_helper(Alt rs, (e1, s1, last_marker))
177   (newenv, newsym) = gensym(e2, "alt_marker")
178   new_stmts = s2 ++ [Assign (newsym, Or(Var(alt1_marker), Var(alt2_marker)))]
179
180-- Repetition Matching Rules
181--
182-- For Kleene Star character class repetition, use MatchStar
183re2pablo_helper(Rep (CC c) 0 Unbounded, (env, stmts, last_marker)) = (newenv, stmts ++ [new_stmt], newsym)
184   where 
185     (newenv, newsym) = gensym(env, "marker")
186     new_stmt = Assign (newsym, MatchStar(Var(last_marker), CharClass(c))) 
187
188-- For general Kleene Star, we need a while loop.
189re2pablo_helper(Rep r 0 Unbounded, (env, stmts, last_marker)) = (newenv, stmts ++ while_init ++ [loop_stmt], while_accum)
190  where
191    (e1, while_test) = gensym(env, "while_test")
192    (e2, while_accum) = gensym(e1, "while_accum")
193    (newenv, loop_body_stmts, loop_result) = re2pablo_helper(r, (e2, [], while_test))
194    while_init = [Assign(while_test, Var(last_marker)), Assign(while_accum, Var(last_marker))]
195    repeat = [Assign(while_test, And(Var(loop_result), Not(Var(while_accum)))),
196              Assign(while_accum, Or(Var(while_accum), Var(loop_result)))]
197    loop_stmt = While(Var(while_test), loop_body_stmts ++ repeat)
198
199re2pablo_helper(Rep r lb Unbounded, cg_state) = re2pablo_helper(Rep r (lb-1) Unbounded, cg1_state)
200  where 
201   cg1_state = re2pablo_helper(r, cg_state)
202
203-- Now Bounded Repetition: use multiple copies
204   
205re2pablo_helper(Rep r 0 (UpperBound 0), cg_state) = cg_state
206
207re2pablo_helper(Rep r 0 (UpperBound ub), (env, stmts, last_marker)) = (newenv, new_stmts, newsym)
208  where 
209   (e1, s1, rep1_marker) = re2pablo_helper(r, (env, stmts, last_marker))
210   (e2, s2, rep2plus_marker) = re2pablo_helper(Rep r 0 (UpperBound(ub-1)), (e1, s1, rep1_marker))
211   (newenv, newsym) = gensym(e2, "alt_marker")
212   new_stmts = s2 ++ [Assign (newsym, Or(Var(last_marker), Var(rep2plus_marker)))]
213
214re2pablo_helper(Rep r lb (UpperBound ub), cg_state) = re2pablo_helper(Rep r (lb-1) (UpperBound(ub-1)), cg1_state)
215  where 
216   cg1_state = re2pablo_helper(r, cg_state)
217
218---------------
219
220searchRE :: (RE, String) -> PabloVal
221searchRE(regexp, str) = evalPabloS(compiled, marker, str)
222  where (e, compiled, marker) = compile(regexp)
223       
Note: See TracBrowser for help on using the repository browser.