Skip to content

Commit b79f44f

Browse files
authored
Merge pull request #37 from tjvr/clone
Don't re-compile RegExp in clone()
2 parents 3641afe + 1ad10eb commit b79f44f

File tree

1 file changed

+8
-20
lines changed

1 file changed

+8
-20
lines changed

moo.js

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -276,12 +276,10 @@
276276
Lexer.prototype.setState = function(state) {
277277
if (!state || this.state === state) return
278278
this.state = state
279-
var index = this.re ? this.re.lastIndex : 0
280279
var info = this.states[state]
281280
this.groups = info.groups
282281
this.error = info.error
283282
this.re = info.regexp
284-
this.re.lastIndex = index
285283
}
286284

287285
Lexer.prototype.popState = function() {
@@ -312,11 +310,11 @@
312310
var re = this.re
313311
var buffer = this.buffer
314312

315-
if (re.lastIndex === buffer.length) {
313+
if (this.index === buffer.length) {
316314
return // EOF
317315
}
318316

319-
var start = re.lastIndex
317+
var index = re.lastIndex = this.index
320318
var match = this.eat(re)
321319
var group, value, text
322320
if (match === null) {
@@ -327,7 +325,7 @@
327325
}
328326

329327
// consume rest of buffer
330-
text = value = buffer.slice(start)
328+
text = value = buffer.slice(index)
331329
re.lastIndex = buffer.length
332330

333331
} else {
@@ -366,7 +364,7 @@
366364
type: group.tokenType,
367365
value: value,
368366
toString: tokenToString,
369-
offset: start,
367+
offset: index,
370368
size: size,
371369
lineBreaks: lineBreaks,
372370
line: this.line,
@@ -377,6 +375,7 @@
377375
else if (group.push) this.pushState(group.push)
378376
else if (group.next) this.setState(group.next)
379377

378+
this.index += size
380379
this.line += lineBreaks
381380
if (lineBreaks !== 0) {
382381
this.col = size - nl + 1
@@ -403,7 +402,7 @@
403402

404403
Lexer.prototype.reset = function(data, state) {
405404
this.buffer = data || ''
406-
this.re.lastIndex = 0
405+
this.index = 0
407406
this.line = state ? state.line : 1
408407
this.col = state ? state.col : 1
409408
return this
@@ -421,19 +420,8 @@
421420
return this
422421
}
423422

424-
Lexer.prototype.clone = function(input) {
425-
var map = Object.create(null)
426-
var keys = Object.getOwnPropertyNames(this.states)
427-
for (var i = 0; i < keys.length; i++) {
428-
var key = keys[i]
429-
var s = this.states[key]
430-
map[key] = {
431-
groups: s.groups,
432-
regexp: new RegExp(s.regexp.source, s.regexp.flags),
433-
error: s.error,
434-
}
435-
}
436-
return new Lexer(map, this.state, input)
423+
Lexer.prototype.clone = function() {
424+
return new Lexer(this.states, this.state)
437425
}
438426

439427

0 commit comments

Comments
 (0)