@@ -117,15 +117,20 @@ function union(first: Automata, second: Automata): Automata {
117117 return new Automata ( start , end ) ;
118118}
119119
120- function closure ( nfa : Automata ) : Automata {
120+ function closure ( nfa : Automata , greedy : bool ) : Automata {
121121 const start = new State ( ) ;
122122 const end = new State ( ) ;
123- // to ensure greedy matches, the epsilon transitions that loop-back
124- // need to be first in the list
125- start . transitions . push ( nfa . start ) ;
126- start . transitions . push ( end ) ;
127- nfa . end . transitions . push ( nfa . start ) ;
128- nfa . end . transitions . push ( end ) ;
123+ if ( greedy ) {
124+ nfa . end . transitions . push ( nfa . start ) ;
125+ nfa . end . transitions . push ( end ) ;
126+ start . transitions . push ( nfa . start ) ;
127+ start . transitions . push ( end ) ;
128+ } else {
129+ nfa . end . transitions . push ( end ) ;
130+ nfa . end . transitions . push ( nfa . start ) ;
131+ start . transitions . push ( end ) ;
132+ start . transitions . push ( nfa . start ) ;
133+ }
129134 return new Automata ( start , end ) ;
130135}
131136
@@ -138,14 +143,17 @@ function zeroOrOne(nfa: Automata): Automata {
138143 return new Automata ( start , end ) ;
139144}
140145
141- function oneOrMore ( nfa : Automata ) : Automata {
146+ function oneOrMore ( nfa : Automata , greedy : bool ) : Automata {
142147 const start = new State ( ) ;
143148 const end = new State ( ) ;
144149 start . transitions . push ( nfa . start ) ;
145- // to ensure greedy matches, the epsilon transitions that loop-back
146- // need to be first in the list
147- nfa . end . transitions . push ( nfa . start ) ;
148- nfa . end . transitions . push ( end ) ;
150+ if ( greedy ) {
151+ nfa . end . transitions . push ( nfa . start ) ;
152+ nfa . end . transitions . push ( end ) ;
153+ } else {
154+ nfa . end . transitions . push ( end ) ;
155+ nfa . end . transitions . push ( nfa . start ) ;
156+ }
149157 return new Automata ( start , end ) ;
150158}
151159
@@ -176,9 +184,9 @@ class AutomataFactor {
176184 if ( quantifier == Char . Question ) {
177185 return zeroOrOne ( automata ) ;
178186 } else if ( quantifier == Char . Plus ) {
179- return oneOrMore ( automata ) ;
187+ return oneOrMore ( automata , node . greedy ) ;
180188 } else if ( quantifier == Char . Asterisk ) {
181- return closure ( automata ) ;
189+ return closure ( automata , node . greedy ) ;
182190 } else {
183191 throw new Error (
184192 "unsupported quantifier - " + String . fromCharCode ( quantifier )
0 commit comments