2 * Copyright 2008 Jacek Caban for CodeWeavers
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * Code in this file is based on files:
23 * from Mozilla project, released under LGPL 2.1 or later.
25 * The Original Code is Mozilla Communicator client code, released
28 * The Initial Developer of the Original Code is
29 * Netscape Communications Corporation.
30 * Portions created by the Initial Developer are Copyright (C) 1998
31 * the Initial Developer. All Rights Reserved.
38 #include "wine/debug.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(jscript);
42 #define JSREG_FOLD 0x01 /* fold uppercase to lowercase */
43 #define JSREG_GLOB 0x02 /* global exec, creates array of matches */
44 #define JSREG_MULTILINE 0x04 /* treat ^ and $ as begin and end of line */
45 #define JSREG_STICKY 0x08 /* only match starting at lastIndex */
47 typedef BYTE JSPackedBool;
48 typedef BYTE jsbytecode;
51 * This struct holds a bitmap representation of a class from a regexp.
52 * There's a list of these referenced by the classList field in the JSRegExp
53 * struct below. The initial state has startIndex set to the offset in the
54 * original regexp source of the beginning of the class contents. The first
55 * use of the class converts the source representation into a bitmap.
58 typedef struct RECharSet {
59 JSPackedBool converted;
72 WORD flags; /* flags, see jsapi.h's JSREG_* defines */
73 size_t parenCount; /* number of parenthesized submatches */
74 size_t classCount; /* count [...] bitmaps */
75 RECharSet *classList; /* list of [...] bitmaps */
76 BSTR source; /* locked source string, sans // */
77 jsbytecode program[1]; /* regular expression bytecode */
87 static const WCHAR sourceW[] = {'s','o','u','r','c','e',0};
88 static const WCHAR globalW[] = {'g','l','o','b','a','l',0};
89 static const WCHAR ignoreCaseW[] = {'i','g','n','o','r','e','C','a','s','e',0};
90 static const WCHAR multilineW[] = {'m','u','l','t','i','l','i','n','e',0};
91 static const WCHAR lastIndexW[] = {'l','a','s','t','I','n','d','e','x',0};
92 static const WCHAR toStringW[] = {'t','o','S','t','r','i','n','g',0};
93 static const WCHAR execW[] = {'e','x','e','c',0};
94 static const WCHAR testW[] = {'t','e','s','t',0};
96 static const WCHAR emptyW[] = {0};
98 /* FIXME: Better error handling */
99 #define ReportRegExpError(a,b,c)
100 #define ReportRegExpErrorHelper(a,b,c,d)
101 #define JS_ReportErrorNumber(a,b,c,d)
102 #define JS_ReportErrorFlagsAndNumber(a,b,c,d,e,f)
103 #define js_ReportOutOfScriptQuota(a)
104 #define JS_ReportOutOfMemory(a)
105 #define JS_COUNT_OPERATION(a,b)
107 #define JSMSG_MIN_TOO_BIG 47
108 #define JSMSG_MAX_TOO_BIG 48
109 #define JSMSG_OUT_OF_ORDER 49
110 #define JSMSG_OUT_OF_MEMORY 137
112 #define LINE_SEPARATOR 0x2028
113 #define PARA_SEPARATOR 0x2029
115 #define RE_IS_LETTER(c) (((c >= 'A') && (c <= 'Z')) || \
116 ((c >= 'a') && (c <= 'z')) )
117 #define RE_IS_LINE_TERM(c) ((c == '\n') || (c == '\r') || \
118 (c == LINE_SEPARATOR) || (c == PARA_SEPARATOR))
120 #define JS_ISWORD(c) ((c) < 128 && (isalnum(c) || (c) == '_'))
122 #define JS7_ISDEC(c) ((((unsigned)(c)) - '0') <= 9)
123 #define JS7_UNDEC(c) ((c) - '0')
175 REOP_LIMIT /* META: no operator >= to this */
178 #define REOP_IS_SIMPLE(op) ((op) <= REOP_NCLASS)
180 static const char *reop_names[] = {
233 typedef struct RECapture {
234 ptrdiff_t index; /* start of contents, -1 for empty */
235 size_t length; /* length of capture */
238 typedef struct REMatchState {
240 RECapture parens[1]; /* first of 're->parenCount' captures,
241 allocated at end of this struct */
244 typedef struct REProgState {
245 jsbytecode *continue_pc; /* current continuation data */
246 jsbytecode continue_op;
247 ptrdiff_t index; /* progress in text */
248 size_t parenSoFar; /* highest indexed paren started */
251 UINT min; /* current quantifier limits */
255 size_t top; /* backtrack stack state */
261 typedef struct REBackTrackData {
262 size_t sz; /* size of previous stack entry */
263 jsbytecode *backtrack_pc; /* where to backtrack to */
264 jsbytecode backtrack_op;
265 const WCHAR *cp; /* index in text of match at backtrack */
266 size_t parenIndex; /* start index of saved paren contents */
267 size_t parenCount; /* # of saved paren contents */
268 size_t saveStateStackTop; /* number of parent states */
269 /* saved parent states follow */
270 /* saved paren contents follow */
273 #define INITIAL_STATESTACK 100
274 #define INITIAL_BACKTRACK 8000
276 typedef struct REGlobalData {
278 JSRegExp *regexp; /* the RE in execution */
279 BOOL ok; /* runtime error (out_of_memory only?) */
280 size_t start; /* offset to start at */
281 ptrdiff_t skipped; /* chars skipped anchoring this r.e. */
282 const WCHAR *cpbegin; /* text base address */
283 const WCHAR *cpend; /* text limit address */
285 REProgState *stateStack; /* stack of state of current parents */
286 size_t stateStackTop;
287 size_t stateStackLimit;
289 REBackTrackData *backTrackStack;/* stack of matched-so-far positions */
290 REBackTrackData *backTrackSP;
291 size_t backTrackStackSize;
292 size_t cursz; /* size of current stack entry */
293 size_t backTrackCount; /* how many times we've backtracked */
294 size_t backTrackLimit; /* upper limit on backtrack states */
296 jsheap_t *pool; /* It's faster to use one malloc'd pool
297 than to malloc/free the three items
298 that are allocated from this pool */
301 typedef struct RENode RENode;
303 REOp op; /* r.e. op bytecode */
304 RENode *next; /* next in concatenation order */
305 void *kid; /* first operand */
307 void *kid2; /* second operand */
308 INT num; /* could be a number */
309 size_t parenIndex; /* or a parenthesis index */
310 struct { /* or a quantifier range */
315 struct { /* or a character class */
317 size_t kidlen; /* length of string at kid, in jschars */
318 size_t index; /* index into class list */
319 WORD bmsize; /* bitmap size, based on max char code */
322 struct { /* or a literal sequence */
323 WCHAR chr; /* of one character */
324 size_t length; /* or many (via the kid) */
327 RENode *kid2; /* second operand from ALT */
328 WCHAR ch1; /* match char for ALTPREREQ */
329 WCHAR ch2; /* ditto, or class index for ALTPREREQ2 */
334 #define CLASS_CACHE_SIZE 4
336 typedef struct CompilerState {
337 script_ctx_t *context;
338 const WCHAR *cpbegin;
342 size_t classCount; /* number of [] encountered */
343 size_t treeDepth; /* maximum depth of parse tree */
344 size_t progLength; /* estimated bytecode length */
346 size_t classBitmapsMem; /* memory to hold all class bitmaps */
348 const WCHAR *start; /* small cache of class strings */
349 size_t length; /* since they're often the same */
351 } classCache[CLASS_CACHE_SIZE];
355 typedef struct EmitStateStackEntry {
356 jsbytecode *altHead; /* start of REOP_ALT* opcode */
357 jsbytecode *nextAltFixup; /* fixup pointer to next-alt offset */
358 jsbytecode *nextTermFixup; /* fixup ptr. to REOP_JUMP offset */
359 jsbytecode *endTermFixup; /* fixup ptr. to REOPT_ALTPREREQ* offset */
360 RENode *continueNode; /* original REOP_ALT* node being stacked */
361 jsbytecode continueOp; /* REOP_JUMP or REOP_ENDALT continuation */
362 JSPackedBool jumpToJumpFlag; /* true if we've patched jump-to-jump to
363 avoid 16-bit unsigned offset overflow */
364 } EmitStateStackEntry;
367 * Immediate operand sizes and getter/setters. Unlike the ones in jsopcode.h,
368 * the getters and setters take the pc of the offset, not of the opcode before
372 #define GET_ARG(pc) ((WORD)(((pc)[0] << 8) | (pc)[1]))
373 #define SET_ARG(pc, arg) ((pc)[0] = (jsbytecode) ((arg) >> 8), \
374 (pc)[1] = (jsbytecode) (arg))
376 #define OFFSET_LEN ARG_LEN
377 #define OFFSET_MAX ((1 << (ARG_LEN * 8)) - 1)
378 #define GET_OFFSET(pc) GET_ARG(pc)
380 static BOOL ParseRegExp(CompilerState*);
383 * Maximum supported tree depth is maximum size of EmitStateStackEntry stack.
384 * For sanity, we limit it to 2^24 bytes.
386 #define TREE_DEPTH_MAX ((1 << 24) / sizeof(EmitStateStackEntry))
389 * The maximum memory that can be allocated for class bitmaps.
390 * For sanity, we limit it to 2^24 bytes.
392 #define CLASS_BITMAPS_MEM_LIMIT (1 << 24)
395 * Functions to get size and write/read bytecode that represent small indexes
397 * Each byte in the code represent 7-bit chunk of the index. 8th bit when set
398 * indicates that the following byte brings more bits to the index. Otherwise
399 * this is the last byte in the index bytecode representing highest index bits.
402 GetCompactIndexWidth(size_t index)
406 for (width = 1; (index >>= 7) != 0; ++width) { }
410 static inline jsbytecode *
411 WriteCompactIndex(jsbytecode *pc, size_t index)
415 while ((next = index >> 7) != 0) {
416 *pc++ = (jsbytecode)(index | 0x80);
419 *pc++ = (jsbytecode)index;
423 static inline jsbytecode *
424 ReadCompactIndex(jsbytecode *pc, size_t *result)
429 if ((nextByte & 0x80) == 0) {
431 * Short-circuit the most common case when compact index <= 127.
436 *result = 0x7F & nextByte;
439 *result |= (nextByte & 0x7F) << shift;
441 } while ((nextByte & 0x80) != 0);
446 /* Construct and initialize an RENode, returning NULL for out-of-memory */
448 NewRENode(CompilerState *state, REOp op)
452 ren = jsheap_alloc(&state->context->tmp_heap, sizeof(*ren));
454 /* js_ReportOutOfScriptQuota(cx); */
464 * Validates and converts hex ascii value.
467 isASCIIHexDigit(WCHAR c, UINT *digit)
478 if (cv >= 'a' && cv <= 'f') {
479 *digit = cv - 'a' + 10;
491 #define JUMP_OFFSET_HI(off) ((jsbytecode)((off) >> 8))
492 #define JUMP_OFFSET_LO(off) ((jsbytecode)(off))
495 SetForwardJumpOffset(jsbytecode *jump, jsbytecode *target)
497 ptrdiff_t offset = target - jump;
499 /* Check that target really points forward. */
501 if ((size_t)offset > OFFSET_MAX)
504 jump[0] = JUMP_OFFSET_HI(offset);
505 jump[1] = JUMP_OFFSET_LO(offset);
510 * Generate bytecode for the tree rooted at t using an explicit stack instead
514 EmitREBytecode(CompilerState *state, JSRegExp *re, size_t treeDepth,
515 jsbytecode *pc, RENode *t)
517 EmitStateStackEntry *emitStateSP, *emitStateStack;
521 if (treeDepth == 0) {
522 emitStateStack = NULL;
524 emitStateStack = heap_alloc(sizeof(EmitStateStackEntry) * treeDepth);
528 emitStateSP = emitStateStack;
530 assert(op < REOP_LIMIT);
539 case REOP_ALTPREREQ2:
542 emitStateSP->altHead = pc - 1;
543 emitStateSP->endTermFixup = pc;
545 SET_ARG(pc, t->u.altprereq.ch1);
547 SET_ARG(pc, t->u.altprereq.ch2);
550 emitStateSP->nextAltFixup = pc; /* offset to next alternate */
553 emitStateSP->continueNode = t;
554 emitStateSP->continueOp = REOP_JUMP;
555 emitStateSP->jumpToJumpFlag = FALSE;
557 assert((size_t)(emitStateSP - emitStateStack) <= treeDepth);
560 assert(op < REOP_LIMIT);
564 emitStateSP->nextTermFixup = pc; /* offset to following term */
566 if (!SetForwardJumpOffset(emitStateSP->nextAltFixup, pc))
568 emitStateSP->continueOp = REOP_ENDALT;
570 assert((size_t)(emitStateSP - emitStateStack) <= treeDepth);
573 assert(op < REOP_LIMIT);
578 * If we already patched emitStateSP->nextTermFixup to jump to
579 * a nearer jump, to avoid 16-bit immediate offset overflow, we
582 if (emitStateSP->jumpToJumpFlag)
586 * Fix up the REOP_JUMP offset to go to the op after REOP_ENDALT.
587 * REOP_ENDALT is executed only on successful match of the last
588 * alternate in a group.
590 if (!SetForwardJumpOffset(emitStateSP->nextTermFixup, pc))
592 if (t->op != REOP_ALT) {
593 if (!SetForwardJumpOffset(emitStateSP->endTermFixup, pc))
598 * If the program is bigger than the REOP_JUMP offset range, then
599 * we must check for alternates before this one that are part of
600 * the same group, and fix up their jump offsets to target jumps
601 * close enough to fit in a 16-bit unsigned offset immediate.
603 if ((size_t)(pc - re->program) > OFFSET_MAX &&
604 emitStateSP > emitStateStack) {
605 EmitStateStackEntry *esp, *esp2;
606 jsbytecode *alt, *jump;
607 ptrdiff_t span, header;
611 for (esp = esp2 - 1; esp >= emitStateStack; --esp) {
612 if (esp->continueOp == REOP_ENDALT &&
613 !esp->jumpToJumpFlag &&
614 esp->nextTermFixup + OFFSET_LEN == alt &&
615 (size_t)(pc - ((esp->continueNode->op != REOP_ALT)
617 : esp->nextTermFixup)) > OFFSET_MAX) {
619 jump = esp->nextTermFixup;
622 * The span must be 1 less than the distance from
623 * jump offset to jump offset, so we actually jump
624 * to a REOP_JUMP bytecode, not to its offset!
627 assert(jump < esp2->nextTermFixup);
628 span = esp2->nextTermFixup - jump - 1;
629 if ((size_t)span <= OFFSET_MAX)
634 } while (esp2->continueOp != REOP_ENDALT);
637 jump[0] = JUMP_OFFSET_HI(span);
638 jump[1] = JUMP_OFFSET_LO(span);
640 if (esp->continueNode->op != REOP_ALT) {
642 * We must patch the offset at esp->endTermFixup
643 * as well, for the REOP_ALTPREREQ{,2} opcodes.
644 * If we're unlucky and endTermFixup is more than
645 * OFFSET_MAX bytes from its target, we cheat by
646 * jumping 6 bytes to the jump whose offset is at
647 * esp->nextTermFixup, which has the same target.
649 jump = esp->endTermFixup;
650 header = esp->nextTermFixup - jump;
652 if ((size_t)span > OFFSET_MAX)
655 jump[0] = JUMP_OFFSET_HI(span);
656 jump[1] = JUMP_OFFSET_LO(span);
659 esp->jumpToJumpFlag = TRUE;
667 emitStateSP->altHead = pc - 1;
668 emitStateSP->nextAltFixup = pc; /* offset to next alternate */
670 emitStateSP->continueNode = t;
671 emitStateSP->continueOp = REOP_JUMP;
672 emitStateSP->jumpToJumpFlag = FALSE;
674 assert((size_t)(emitStateSP - emitStateStack) <= treeDepth);
677 assert(op < REOP_LIMIT);
682 * Coalesce FLATs if possible and if it would not increase bytecode
683 * beyond preallocated limit. The latter happens only when bytecode
684 * size for coalesced string with offset p and length 2 exceeds 6
685 * bytes preallocated for 2 single char nodes, i.e. when
686 * 1 + GetCompactIndexWidth(p) + GetCompactIndexWidth(2) > 6 or
687 * GetCompactIndexWidth(p) > 4.
688 * Since when GetCompactIndexWidth(p) <= 4 coalescing of 3 or more
689 * nodes strictly decreases bytecode size, the check has to be
690 * done only for the first coalescing.
693 GetCompactIndexWidth((WCHAR*)t->kid - state->cpbegin) <= 4)
696 t->next->op == REOP_FLAT &&
697 (WCHAR*)t->kid + t->u.flat.length ==
699 t->u.flat.length += t->next->u.flat.length;
700 t->next = t->next->next;
703 if (t->kid && t->u.flat.length > 1) {
704 pc[-1] = (state->flags & JSREG_FOLD) ? REOP_FLATi : REOP_FLAT;
705 pc = WriteCompactIndex(pc, (WCHAR*)t->kid - state->cpbegin);
706 pc = WriteCompactIndex(pc, t->u.flat.length);
707 } else if (t->u.flat.chr < 256) {
708 pc[-1] = (state->flags & JSREG_FOLD) ? REOP_FLAT1i : REOP_FLAT1;
709 *pc++ = (jsbytecode) t->u.flat.chr;
711 pc[-1] = (state->flags & JSREG_FOLD)
714 SET_ARG(pc, t->u.flat.chr);
721 pc = WriteCompactIndex(pc, t->u.parenIndex);
722 emitStateSP->continueNode = t;
723 emitStateSP->continueOp = REOP_RPAREN;
725 assert((size_t)(emitStateSP - emitStateStack) <= treeDepth);
731 pc = WriteCompactIndex(pc, t->u.parenIndex);
735 pc = WriteCompactIndex(pc, t->u.parenIndex);
740 emitStateSP->nextTermFixup = pc;
742 emitStateSP->continueNode = t;
743 emitStateSP->continueOp = REOP_ASSERTTEST;
745 assert((size_t)(emitStateSP - emitStateStack) <= treeDepth);
750 case REOP_ASSERTTEST:
751 case REOP_ASSERTNOTTEST:
752 if (!SetForwardJumpOffset(emitStateSP->nextTermFixup, pc))
756 case REOP_ASSERT_NOT:
758 emitStateSP->nextTermFixup = pc;
760 emitStateSP->continueNode = t;
761 emitStateSP->continueOp = REOP_ASSERTNOTTEST;
763 assert((size_t)(emitStateSP - emitStateStack) <= treeDepth);
770 if (t->u.range.min == 0 && t->u.range.max == (UINT)-1) {
771 pc[-1] = (t->u.range.greedy) ? REOP_STAR : REOP_MINIMALSTAR;
772 } else if (t->u.range.min == 0 && t->u.range.max == 1) {
773 pc[-1] = (t->u.range.greedy) ? REOP_OPT : REOP_MINIMALOPT;
774 } else if (t->u.range.min == 1 && t->u.range.max == (UINT) -1) {
775 pc[-1] = (t->u.range.greedy) ? REOP_PLUS : REOP_MINIMALPLUS;
777 if (!t->u.range.greedy)
778 pc[-1] = REOP_MINIMALQUANT;
779 pc = WriteCompactIndex(pc, t->u.range.min);
781 * Write max + 1 to avoid using size_t(max) + 1 bytes
782 * for (UINT)-1 sentinel.
784 pc = WriteCompactIndex(pc, t->u.range.max + 1);
786 emitStateSP->nextTermFixup = pc;
788 emitStateSP->continueNode = t;
789 emitStateSP->continueOp = REOP_ENDCHILD;
791 assert((size_t)(emitStateSP - emitStateStack) <= treeDepth);
797 if (!SetForwardJumpOffset(emitStateSP->nextTermFixup, pc))
802 if (!t->u.ucclass.sense)
803 pc[-1] = REOP_NCLASS;
804 pc = WriteCompactIndex(pc, t->u.ucclass.index);
805 charSet = &re->classList[t->u.ucclass.index];
806 charSet->converted = FALSE;
807 charSet->length = t->u.ucclass.bmsize;
808 charSet->u.src.startIndex = t->u.ucclass.startIndex;
809 charSet->u.src.length = t->u.ucclass.kidlen;
810 charSet->sense = t->u.ucclass.sense;
821 if (emitStateSP == emitStateStack)
824 t = emitStateSP->continueNode;
825 op = (REOp) emitStateSP->continueOp;
830 heap_free(emitStateStack);
834 ReportRegExpError(state, JSREPORT_ERROR, JSMSG_REGEXP_TOO_COMPLEX);
840 * Process the op against the two top operands, reducing them to a single
841 * operand in the penultimate slot. Update progLength and treeDepth.
844 ProcessOp(CompilerState *state, REOpData *opData, RENode **operandStack,
849 switch (opData->op) {
851 result = NewRENode(state, REOP_ALT);
854 result->kid = operandStack[operandSP - 2];
855 result->u.kid2 = operandStack[operandSP - 1];
856 operandStack[operandSP - 2] = result;
858 if (state->treeDepth == TREE_DEPTH_MAX) {
859 ReportRegExpError(state, JSREPORT_ERROR, JSMSG_REGEXP_TOO_COMPLEX);
865 * Look at both alternates to see if there's a FLAT or a CLASS at
866 * the start of each. If so, use a prerequisite match.
868 if (((RENode *) result->kid)->op == REOP_FLAT &&
869 ((RENode *) result->u.kid2)->op == REOP_FLAT &&
870 (state->flags & JSREG_FOLD) == 0) {
871 result->op = REOP_ALTPREREQ;
872 result->u.altprereq.ch1 = ((RENode *) result->kid)->u.flat.chr;
873 result->u.altprereq.ch2 = ((RENode *) result->u.kid2)->u.flat.chr;
874 /* ALTPREREQ, <end>, uch1, uch2, <next>, ...,
875 JUMP, <end> ... ENDALT */
876 state->progLength += 13;
879 if (((RENode *) result->kid)->op == REOP_CLASS &&
880 ((RENode *) result->kid)->u.ucclass.index < 256 &&
881 ((RENode *) result->u.kid2)->op == REOP_FLAT &&
882 (state->flags & JSREG_FOLD) == 0) {
883 result->op = REOP_ALTPREREQ2;
884 result->u.altprereq.ch1 = ((RENode *) result->u.kid2)->u.flat.chr;
885 result->u.altprereq.ch2 = ((RENode *) result->kid)->u.ucclass.index;
886 /* ALTPREREQ2, <end>, uch1, uch2, <next>, ...,
887 JUMP, <end> ... ENDALT */
888 state->progLength += 13;
891 if (((RENode *) result->kid)->op == REOP_FLAT &&
892 ((RENode *) result->u.kid2)->op == REOP_CLASS &&
893 ((RENode *) result->u.kid2)->u.ucclass.index < 256 &&
894 (state->flags & JSREG_FOLD) == 0) {
895 result->op = REOP_ALTPREREQ2;
896 result->u.altprereq.ch1 = ((RENode *) result->kid)->u.flat.chr;
897 result->u.altprereq.ch2 =
898 ((RENode *) result->u.kid2)->u.ucclass.index;
899 /* ALTPREREQ2, <end>, uch1, uch2, <next>, ...,
900 JUMP, <end> ... ENDALT */
901 state->progLength += 13;
904 /* ALT, <next>, ..., JUMP, <end> ... ENDALT */
905 state->progLength += 7;
910 result = operandStack[operandSP - 2];
912 result = result->next;
913 result->next = operandStack[operandSP - 1];
917 case REOP_ASSERT_NOT:
920 /* These should have been processed by a close paren. */
921 ReportRegExpErrorHelper(state, JSREPORT_ERROR, JSMSG_MISSING_PAREN,
931 * Hack two bits in CompilerState.flags, for use within FindParenCount to flag
932 * its being on the stack, and to propagate errors to its callers.
934 #define JSREG_FIND_PAREN_COUNT 0x8000
935 #define JSREG_FIND_PAREN_ERROR 0x4000
938 * Magic return value from FindParenCount and GetDecimalValue, to indicate
939 * overflow beyond GetDecimalValue's max parameter, or a computed maximum if
940 * its findMax parameter is non-null.
942 #define OVERFLOW_VALUE ((UINT)-1)
945 FindParenCount(CompilerState *state)
950 if (state->flags & JSREG_FIND_PAREN_COUNT)
951 return OVERFLOW_VALUE;
954 * Copy state into temp, flag it so we never report an invalid backref,
955 * and reset its members to parse the entire regexp. This is obviously
956 * suboptimal, but GetDecimalValue calls us only if a backref appears to
957 * refer to a forward parenthetical, which is rare.
960 temp.flags |= JSREG_FIND_PAREN_COUNT;
961 temp.cp = temp.cpbegin;
966 temp.classBitmapsMem = 0;
967 for (i = 0; i < CLASS_CACHE_SIZE; i++)
968 temp.classCache[i].start = NULL;
970 if (!ParseRegExp(&temp)) {
971 state->flags |= JSREG_FIND_PAREN_ERROR;
972 return OVERFLOW_VALUE;
974 return temp.parenCount;
978 * Extract and return a decimal value at state->cp. The initial character c
979 * has already been read. Return OVERFLOW_VALUE if the result exceeds max.
980 * Callers who pass a non-null findMax should test JSREG_FIND_PAREN_ERROR in
981 * state->flags to discover whether an error occurred under findMax.
984 GetDecimalValue(WCHAR c, UINT max, UINT (*findMax)(CompilerState *state),
985 CompilerState *state)
987 UINT value = JS7_UNDEC(c);
988 BOOL overflow = (value > max && (!findMax || value > findMax(state)));
990 /* The following restriction allows simpler overflow checks. */
991 assert(max <= ((UINT)-1 - 9) / 10);
992 while (state->cp < state->cpend) {
996 value = 10 * value + JS7_UNDEC(c);
997 if (!overflow && value > max && (!findMax || value > findMax(state)))
1001 return overflow ? OVERFLOW_VALUE : value;
1005 * Calculate the total size of the bitmap required for a class expression.
1008 CalculateBitmapSize(CompilerState *state, RENode *target, const WCHAR *src,
1012 BOOL inRange = FALSE;
1013 WCHAR c, rangeStart = 0;
1014 UINT n, digit, nDigits, i;
1016 target->u.ucclass.bmsize = 0;
1017 target->u.ucclass.sense = TRUE;
1024 target->u.ucclass.sense = FALSE;
1027 while (src != end) {
1028 BOOL canStartRange = TRUE;
1055 if (src < end && RE_IS_LETTER(*src)) {
1056 localMax = (UINT) (*src++) & 0x1F;
1069 for (i = 0; (i < nDigits) && (src < end); i++) {
1071 if (!isASCIIHexDigit(c, &digit)) {
1073 * Back off to accepting the original
1080 n = (n << 4) | digit;
1085 canStartRange = FALSE;
1087 JS_ReportErrorNumber(state->context,
1088 js_GetErrorMessage, NULL,
1089 JSMSG_BAD_CLASS_RANGE);
1099 canStartRange = FALSE;
1101 JS_ReportErrorNumber(state->context,
1102 js_GetErrorMessage, NULL,
1103 JSMSG_BAD_CLASS_RANGE);
1109 * If this is the start of a range, ensure that it's less than
1123 * This is a non-ECMA extension - decimal escapes (in this
1124 * case, octal!) are supposed to be an error inside class
1125 * ranges, but supported here for backwards compatibility.
1130 if ('0' <= c && c <= '7') {
1132 n = 8 * n + JS7_UNDEC(c);
1134 if ('0' <= c && c <= '7') {
1136 i = 8 * n + JS7_UNDEC(c);
1157 /* Throw a SyntaxError here, per ECMA-262, 15.10.2.15. */
1158 if (rangeStart > localMax) {
1159 JS_ReportErrorNumber(state->context,
1160 js_GetErrorMessage, NULL,
1161 JSMSG_BAD_CLASS_RANGE);
1166 if (canStartRange && src < end - 1) {
1170 rangeStart = (WCHAR)localMax;
1174 if (state->flags & JSREG_FOLD)
1175 rangeStart = localMax; /* one run of the uc/dc loop below */
1178 if (state->flags & JSREG_FOLD) {
1179 WCHAR maxch = localMax;
1181 for (i = rangeStart; i <= localMax; i++) {
1197 target->u.ucclass.bmsize = max;
1202 ParseMinMaxQuantifier(CompilerState *state, BOOL ignoreValues)
1206 const WCHAR *errp = state->cp++;
1211 min = GetDecimalValue(c, 0xFFFF, NULL, state);
1214 if (!ignoreValues && min == OVERFLOW_VALUE)
1215 return JSMSG_MIN_TOO_BIG;
1221 max = GetDecimalValue(c, 0xFFFF, NULL, state);
1223 if (!ignoreValues && max == OVERFLOW_VALUE)
1224 return JSMSG_MAX_TOO_BIG;
1225 if (!ignoreValues && min > max)
1226 return JSMSG_OUT_OF_ORDER;
1234 state->result = NewRENode(state, REOP_QUANT);
1236 return JSMSG_OUT_OF_MEMORY;
1237 state->result->u.range.min = min;
1238 state->result->u.range.max = max;
1240 * QUANT, <min>, <max>, <next> ... <ENDCHILD>
1241 * where <max> is written as compact(max+1) to make
1242 * (UINT)-1 sentinel to occupy 1 byte, not width_of(max)+1.
1244 state->progLength += (1 + GetCompactIndexWidth(min)
1245 + GetCompactIndexWidth(max + 1)
1256 ParseQuantifier(CompilerState *state)
1259 term = state->result;
1260 if (state->cp < state->cpend) {
1261 switch (*state->cp) {
1263 state->result = NewRENode(state, REOP_QUANT);
1266 state->result->u.range.min = 1;
1267 state->result->u.range.max = (UINT)-1;
1268 /* <PLUS>, <next> ... <ENDCHILD> */
1269 state->progLength += 4;
1272 state->result = NewRENode(state, REOP_QUANT);
1275 state->result->u.range.min = 0;
1276 state->result->u.range.max = (UINT)-1;
1277 /* <STAR>, <next> ... <ENDCHILD> */
1278 state->progLength += 4;
1281 state->result = NewRENode(state, REOP_QUANT);
1284 state->result->u.range.min = 0;
1285 state->result->u.range.max = 1;
1286 /* <OPT>, <next> ... <ENDCHILD> */
1287 state->progLength += 4;
1289 case '{': /* balance '}' */
1293 err = ParseMinMaxQuantifier(state, FALSE);
1299 ReportRegExpErrorHelper(state, JSREPORT_ERROR, err, errp);
1308 if (state->treeDepth == TREE_DEPTH_MAX) {
1309 ReportRegExpError(state, JSREPORT_ERROR, JSMSG_REGEXP_TOO_COMPLEX);
1315 state->result->kid = term;
1316 if (state->cp < state->cpend && *state->cp == '?') {
1318 state->result->u.range.greedy = FALSE;
1320 state->result->u.range.greedy = TRUE;
1326 * item: assertion An item is either an assertion or
1327 * quantatom a quantified atom.
1329 * assertion: '^' Assertions match beginning of string
1330 * (or line if the class static property
1331 * RegExp.multiline is true).
1332 * '$' End of string (or line if the class
1333 * static property RegExp.multiline is
1335 * '\b' Word boundary (between \w and \W).
1336 * '\B' Word non-boundary.
1338 * quantatom: atom An unquantified atom.
1339 * quantatom '{' n ',' m '}'
1340 * Atom must occur between n and m times.
1341 * quantatom '{' n ',' '}' Atom must occur at least n times.
1342 * quantatom '{' n '}' Atom must occur exactly n times.
1343 * quantatom '*' Zero or more times (same as {0,}).
1344 * quantatom '+' One or more times (same as {1,}).
1345 * quantatom '?' Zero or one time (same as {0,1}).
1347 * any of which can be optionally followed by '?' for ungreedy
1349 * atom: '(' regexp ')' A parenthesized regexp (what matched
1350 * can be addressed using a backreference,
1352 * '.' Matches any char except '\n'.
1353 * '[' classlist ']' A character class.
1354 * '[' '^' classlist ']' A negated character class.
1356 * '\n' Newline (Line Feed).
1357 * '\r' Carriage Return.
1358 * '\t' Horizontal Tab.
1359 * '\v' Vertical Tab.
1360 * '\d' A digit (same as [0-9]).
1362 * '\w' A word character, [0-9a-z_A-Z].
1363 * '\W' A non-word character.
1364 * '\s' A whitespace character, [ \b\f\n\r\t\v].
1365 * '\S' A non-whitespace character.
1366 * '\' n A backreference to the nth (n decimal
1367 * and positive) parenthesized expression.
1368 * '\' octal An octal escape sequence (octal must be
1369 * two or three digits long, unless it is
1370 * 0 for the null character).
1371 * '\x' hex A hex escape (hex must be two digits).
1372 * '\u' unicode A unicode escape (must be four digits).
1373 * '\c' ctrl A control character, ctrl is a letter.
1374 * '\' literalatomchar Any character except one of the above
1375 * that follow '\' in an atom.
1376 * otheratomchar Any character not first among the other
1377 * atom right-hand sides.
1380 ParseTerm(CompilerState *state)
1382 WCHAR c = *state->cp++;
1384 UINT num, tmp, n, i;
1385 const WCHAR *termStart;
1388 /* assertions and atoms */
1390 state->result = NewRENode(state, REOP_BOL);
1393 state->progLength++;
1396 state->result = NewRENode(state, REOP_EOL);
1399 state->progLength++;
1402 if (state->cp >= state->cpend) {
1403 /* a trailing '\' is an error */
1404 ReportRegExpError(state, JSREPORT_ERROR, JSMSG_TRAILING_SLASH);
1409 /* assertion escapes */
1411 state->result = NewRENode(state, REOP_WBDRY);
1414 state->progLength++;
1417 state->result = NewRENode(state, REOP_WNONBDRY);
1420 state->progLength++;
1422 /* Decimal escape */
1424 /* Give a strict warning. See also the note below. */
1425 WARN("non-octal digit in an escape sequence that doesn't match a back-reference\n");
1428 while (state->cp < state->cpend) {
1430 if (c < '0' || '7' < c)
1433 tmp = 8 * num + (UINT)JS7_UNDEC(c);
1440 state->result = NewRENode(state, REOP_FLAT);
1443 state->result->u.flat.chr = c;
1444 state->result->u.flat.length = 1;
1445 state->progLength += 3;
1456 termStart = state->cp - 1;
1457 num = GetDecimalValue(c, state->parenCount, FindParenCount, state);
1458 if (state->flags & JSREG_FIND_PAREN_ERROR)
1460 if (num == OVERFLOW_VALUE) {
1461 /* Give a strict mode warning. */
1462 WARN("back-reference exceeds number of capturing parentheses\n");
1465 * Note: ECMA 262, 15.10.2.9 says that we should throw a syntax
1466 * error here. However, for compatibility with IE, we treat the
1467 * whole backref as flat if the first character in it is not a
1468 * valid octal character, and as an octal escape otherwise.
1470 state->cp = termStart;
1472 /* Treat this as flat. termStart - 1 is the \. */
1477 /* Treat this as an octal escape. */
1480 assert(1 <= num && num <= 0x10000);
1481 state->result = NewRENode(state, REOP_BACKREF);
1484 state->result->u.parenIndex = num - 1;
1486 += 1 + GetCompactIndexWidth(state->result->u.parenIndex);
1488 /* Control escape */
1504 /* Control letter */
1506 if (state->cp < state->cpend && RE_IS_LETTER(*state->cp)) {
1507 c = (WCHAR) (*state->cp++ & 0x1F);
1509 /* back off to accepting the original '\' as a literal */
1514 /* HexEscapeSequence */
1518 /* UnicodeEscapeSequence */
1523 for (i = 0; i < nDigits && state->cp < state->cpend; i++) {
1526 if (!isASCIIHexDigit(c, &digit)) {
1528 * Back off to accepting the original 'u' or 'x' as a
1535 n = (n << 4) | digit;
1539 /* Character class escapes */
1541 state->result = NewRENode(state, REOP_DIGIT);
1545 state->progLength++;
1548 state->result = NewRENode(state, REOP_NONDIGIT);
1551 state->result = NewRENode(state, REOP_SPACE);
1554 state->result = NewRENode(state, REOP_NONSPACE);
1557 state->result = NewRENode(state, REOP_ALNUM);
1560 state->result = NewRENode(state, REOP_NONALNUM);
1562 /* IdentityEscape */
1564 state->result = NewRENode(state, REOP_FLAT);
1567 state->result->u.flat.chr = c;
1568 state->result->u.flat.length = 1;
1569 state->result->kid = (void *) (state->cp - 1);
1570 state->progLength += 3;
1575 state->result = NewRENode(state, REOP_CLASS);
1578 termStart = state->cp;
1579 state->result->u.ucclass.startIndex = termStart - state->cpbegin;
1581 if (state->cp == state->cpend) {
1582 ReportRegExpErrorHelper(state, JSREPORT_ERROR,
1583 JSMSG_UNTERM_CLASS, termStart);
1587 if (*state->cp == '\\') {
1589 if (state->cp != state->cpend)
1593 if (*state->cp == ']') {
1594 state->result->u.ucclass.kidlen = state->cp - termStart;
1599 for (i = 0; i < CLASS_CACHE_SIZE; i++) {
1600 if (!state->classCache[i].start) {
1601 state->classCache[i].start = termStart;
1602 state->classCache[i].length = state->result->u.ucclass.kidlen;
1603 state->classCache[i].index = state->classCount;
1606 if (state->classCache[i].length ==
1607 state->result->u.ucclass.kidlen) {
1608 for (n = 0; ; n++) {
1609 if (n == state->classCache[i].length) {
1610 state->result->u.ucclass.index
1611 = state->classCache[i].index;
1614 if (state->classCache[i].start[n] != termStart[n])
1619 state->result->u.ucclass.index = state->classCount++;
1623 * Call CalculateBitmapSize now as we want any errors it finds
1624 * to be reported during the parse phase, not at execution.
1626 if (!CalculateBitmapSize(state, state->result, termStart, state->cp++))
1629 * Update classBitmapsMem with number of bytes to hold bmsize bits,
1630 * which is (bitsCount + 7) / 8 or (highest_bit + 1 + 7) / 8
1631 * or highest_bit / 8 + 1 where highest_bit is u.ucclass.bmsize.
1633 n = (state->result->u.ucclass.bmsize >> 3) + 1;
1634 if (n > CLASS_BITMAPS_MEM_LIMIT - state->classBitmapsMem) {
1635 ReportRegExpError(state, JSREPORT_ERROR, JSMSG_REGEXP_TOO_COMPLEX);
1638 state->classBitmapsMem += n;
1639 /* CLASS, <index> */
1641 += 1 + GetCompactIndexWidth(state->result->u.ucclass.index);
1645 state->result = NewRENode(state, REOP_DOT);
1650 const WCHAR *errp = state->cp--;
1653 err = ParseMinMaxQuantifier(state, TRUE);
1664 ReportRegExpErrorHelper(state, JSREPORT_ERROR,
1665 JSMSG_BAD_QUANTIFIER, state->cp - 1);
1669 state->result = NewRENode(state, REOP_FLAT);
1672 state->result->u.flat.chr = c;
1673 state->result->u.flat.length = 1;
1674 state->result->kid = (void *) (state->cp - 1);
1675 state->progLength += 3;
1678 return ParseQuantifier(state);
1682 * Top-down regular expression grammar, based closely on Perl4.
1684 * regexp: altern A regular expression is one or more
1685 * altern '|' regexp alternatives separated by vertical bar.
1687 #define INITIAL_STACK_SIZE 128
1690 ParseRegExp(CompilerState *state)
1694 REOpData *operatorStack;
1695 RENode **operandStack;
1698 BOOL result = FALSE;
1700 INT operatorSP = 0, operatorStackSize = INITIAL_STACK_SIZE;
1701 INT operandSP = 0, operandStackSize = INITIAL_STACK_SIZE;
1703 /* Watch out for empty regexp */
1704 if (state->cp == state->cpend) {
1705 state->result = NewRENode(state, REOP_EMPTY);
1706 return (state->result != NULL);
1709 operatorStack = heap_alloc(sizeof(REOpData) * operatorStackSize);
1713 operandStack = heap_alloc(sizeof(RENode *) * operandStackSize);
1718 parenIndex = state->parenCount;
1719 if (state->cp == state->cpend) {
1721 * If we are at the end of the regexp and we're short one or more
1722 * operands, the regexp must have the form /x|/ or some such, with
1723 * left parentheses making us short more than one operand.
1725 if (operatorSP >= operandSP) {
1726 operand = NewRENode(state, REOP_EMPTY);
1732 switch (*state->cp) {
1735 if (state->cp + 1 < state->cpend &&
1736 *state->cp == '?' &&
1737 (state->cp[1] == '=' ||
1738 state->cp[1] == '!' ||
1739 state->cp[1] == ':')) {
1740 switch (state->cp[1]) {
1743 /* ASSERT, <next>, ... ASSERTTEST */
1744 state->progLength += 4;
1747 op = REOP_ASSERT_NOT;
1748 /* ASSERTNOT, <next>, ... ASSERTNOTTEST */
1749 state->progLength += 4;
1752 op = REOP_LPARENNON;
1758 /* LPAREN, <index>, ... RPAREN, <index> */
1760 += 2 * (1 + GetCompactIndexWidth(parenIndex));
1761 state->parenCount++;
1762 if (state->parenCount == 65535) {
1763 ReportRegExpError(state, JSREPORT_ERROR,
1764 JSMSG_TOO_MANY_PARENS);
1772 * If there's no stacked open parenthesis, throw syntax error.
1774 for (i = operatorSP - 1; ; i--) {
1776 ReportRegExpError(state, JSREPORT_ERROR,
1777 JSMSG_UNMATCHED_RIGHT_PAREN);
1780 if (operatorStack[i].op == REOP_ASSERT ||
1781 operatorStack[i].op == REOP_ASSERT_NOT ||
1782 operatorStack[i].op == REOP_LPARENNON ||
1783 operatorStack[i].op == REOP_LPAREN) {
1790 /* Expected an operand before these, so make an empty one */
1791 operand = NewRENode(state, REOP_EMPTY);
1797 if (!ParseTerm(state))
1799 operand = state->result;
1801 if (operandSP == operandStackSize) {
1803 operandStackSize += operandStackSize;
1804 tmp = heap_realloc(operandStack, sizeof(RENode *) * operandStackSize);
1809 operandStack[operandSP++] = operand;
1814 /* At the end; process remaining operators. */
1816 if (state->cp == state->cpend) {
1817 while (operatorSP) {
1819 if (!ProcessOp(state, &operatorStack[operatorSP],
1820 operandStack, operandSP))
1824 assert(operandSP == 1);
1825 state->result = operandStack[0];
1830 switch (*state->cp) {
1832 /* Process any stacked 'concat' operators */
1834 while (operatorSP &&
1835 operatorStack[operatorSP - 1].op == REOP_CONCAT) {
1837 if (!ProcessOp(state, &operatorStack[operatorSP],
1838 operandStack, operandSP)) {
1848 * If there's no stacked open parenthesis, throw syntax error.
1850 for (i = operatorSP - 1; ; i--) {
1852 ReportRegExpError(state, JSREPORT_ERROR,
1853 JSMSG_UNMATCHED_RIGHT_PAREN);
1856 if (operatorStack[i].op == REOP_ASSERT ||
1857 operatorStack[i].op == REOP_ASSERT_NOT ||
1858 operatorStack[i].op == REOP_LPARENNON ||
1859 operatorStack[i].op == REOP_LPAREN) {
1865 /* Process everything on the stack until the open parenthesis. */
1869 switch (operatorStack[operatorSP].op) {
1871 case REOP_ASSERT_NOT:
1873 operand = NewRENode(state, operatorStack[operatorSP].op);
1876 operand->u.parenIndex =
1877 operatorStack[operatorSP].parenIndex;
1879 operand->kid = operandStack[operandSP - 1];
1880 operandStack[operandSP - 1] = operand;
1881 if (state->treeDepth == TREE_DEPTH_MAX) {
1882 ReportRegExpError(state, JSREPORT_ERROR,
1883 JSMSG_REGEXP_TOO_COMPLEX);
1889 case REOP_LPARENNON:
1890 state->result = operandStack[operandSP - 1];
1891 if (!ParseQuantifier(state))
1893 operandStack[operandSP - 1] = state->result;
1894 goto restartOperator;
1896 if (!ProcessOp(state, &operatorStack[operatorSP],
1897 operandStack, operandSP))
1907 const WCHAR *errp = state->cp;
1909 if (ParseMinMaxQuantifier(state, TRUE) < 0) {
1911 * This didn't even scan correctly as a quantifier, so we should
1925 ReportRegExpErrorHelper(state, JSREPORT_ERROR, JSMSG_BAD_QUANTIFIER,
1931 /* Anything else is the start of the next term. */
1934 if (operatorSP == operatorStackSize) {
1936 operatorStackSize += operatorStackSize;
1937 tmp = heap_realloc(operatorStack, sizeof(REOpData) * operatorStackSize);
1940 operatorStack = tmp;
1942 operatorStack[operatorSP].op = op;
1943 operatorStack[operatorSP].errPos = state->cp;
1944 operatorStack[operatorSP++].parenIndex = parenIndex;
1949 heap_free(operatorStack);
1950 heap_free(operandStack);
1955 * Save the current state of the match - the position in the input
1956 * text as well as the position in the bytecode. The state of any
1957 * parent expressions is also saved (preceding state).
1958 * Contents of parenCount parentheses from parenIndex are also saved.
1960 static REBackTrackData *
1961 PushBackTrackState(REGlobalData *gData, REOp op,
1962 jsbytecode *target, REMatchState *x, const WCHAR *cp,
1963 size_t parenIndex, size_t parenCount)
1966 REBackTrackData *result =
1967 (REBackTrackData *) ((char *)gData->backTrackSP + gData->cursz);
1969 size_t sz = sizeof(REBackTrackData) +
1970 gData->stateStackTop * sizeof(REProgState) +
1971 parenCount * sizeof(RECapture);
1973 ptrdiff_t btsize = gData->backTrackStackSize;
1974 ptrdiff_t btincr = ((char *)result + sz) -
1975 ((char *)gData->backTrackStack + btsize);
1977 TRACE("\tBT_Push: %lu,%lu\n", (unsigned long) parenIndex, (unsigned long) parenCount);
1979 JS_COUNT_OPERATION(gData->cx, JSOW_JUMP * (1 + parenCount));
1981 ptrdiff_t offset = (char *)result - (char *)gData->backTrackStack;
1983 JS_COUNT_OPERATION(gData->cx, JSOW_ALLOCATION);
1984 btincr = ((btincr+btsize-1)/btsize)*btsize;
1985 gData->backTrackStack = jsheap_grow(gData->pool, gData->backTrackStack, btsize, btincr);
1986 if (!gData->backTrackStack) {
1987 js_ReportOutOfScriptQuota(gData->cx);
1991 gData->backTrackStackSize = btsize + btincr;
1992 result = (REBackTrackData *) ((char *)gData->backTrackStack + offset);
1994 gData->backTrackSP = result;
1995 result->sz = gData->cursz;
1998 result->backtrack_op = op;
1999 result->backtrack_pc = target;
2001 result->parenCount = parenCount;
2002 result->parenIndex = parenIndex;
2004 result->saveStateStackTop = gData->stateStackTop;
2005 assert(gData->stateStackTop);
2006 memcpy(result + 1, gData->stateStack,
2007 sizeof(REProgState) * result->saveStateStackTop);
2009 if (parenCount != 0) {
2010 memcpy((char *)(result + 1) +
2011 sizeof(REProgState) * result->saveStateStackTop,
2012 &x->parens[parenIndex],
2013 sizeof(RECapture) * parenCount);
2014 for (i = 0; i != parenCount; i++)
2015 x->parens[parenIndex + i].index = -1;
2021 static inline REMatchState *
2022 FlatNIMatcher(REGlobalData *gData, REMatchState *x, WCHAR *matchChars,
2026 assert(gData->cpend >= x->cp);
2027 if (length > (size_t)(gData->cpend - x->cp))
2029 for (i = 0; i != length; i++) {
2030 if (toupperW(matchChars[i]) != toupperW(x->cp[i]))
2038 * 1. Evaluate DecimalEscape to obtain an EscapeValue E.
2039 * 2. If E is not a character then go to step 6.
2040 * 3. Let ch be E's character.
2041 * 4. Let A be a one-element RECharSet containing the character ch.
2042 * 5. Call CharacterSetMatcher(A, false) and return its Matcher result.
2043 * 6. E must be an integer. Let n be that integer.
2044 * 7. If n=0 or n>NCapturingParens then throw a SyntaxError exception.
2045 * 8. Return an internal Matcher closure that takes two arguments, a State x
2046 * and a Continuation c, and performs the following:
2047 * 1. Let cap be x's captures internal array.
2048 * 2. Let s be cap[n].
2049 * 3. If s is undefined, then call c(x) and return its result.
2050 * 4. Let e be x's endIndex.
2051 * 5. Let len be s's length.
2052 * 6. Let f be e+len.
2053 * 7. If f>InputLength, return failure.
2054 * 8. If there exists an integer i between 0 (inclusive) and len (exclusive)
2055 * such that Canonicalize(s[i]) is not the same character as
2056 * Canonicalize(Input [e+i]), then return failure.
2057 * 9. Let y be the State (f, cap).
2058 * 10. Call c(y) and return its result.
2060 static REMatchState *
2061 BackrefMatcher(REGlobalData *gData, REMatchState *x, size_t parenIndex)
2064 const WCHAR *parenContent;
2065 RECapture *cap = &x->parens[parenIndex];
2067 if (cap->index == -1)
2071 if (x->cp + len > gData->cpend)
2074 parenContent = &gData->cpbegin[cap->index];
2075 if (gData->regexp->flags & JSREG_FOLD) {
2076 for (i = 0; i < len; i++) {
2077 if (toupperW(parenContent[i]) != toupperW(x->cp[i]))
2081 for (i = 0; i < len; i++) {
2082 if (parenContent[i] != x->cp[i])
2090 /* Add a single character to the RECharSet */
2092 AddCharacterToCharSet(RECharSet *cs, WCHAR c)
2094 UINT byteIndex = (UINT)(c >> 3);
2095 assert(c <= cs->length);
2096 cs->u.bits[byteIndex] |= 1 << (c & 0x7);
2100 /* Add a character range, c1 to c2 (inclusive) to the RECharSet */
2102 AddCharacterRangeToCharSet(RECharSet *cs, UINT c1, UINT c2)
2106 UINT byteIndex1 = c1 >> 3;
2107 UINT byteIndex2 = c2 >> 3;
2109 assert(c2 <= cs->length && c1 <= c2);
2114 if (byteIndex1 == byteIndex2) {
2115 cs->u.bits[byteIndex1] |= ((BYTE)0xFF >> (7 - (c2 - c1))) << c1;
2117 cs->u.bits[byteIndex1] |= 0xFF << c1;
2118 for (i = byteIndex1 + 1; i < byteIndex2; i++)
2119 cs->u.bits[i] = 0xFF;
2120 cs->u.bits[byteIndex2] |= (BYTE)0xFF >> (7 - c2);
2124 /* Compile the source of the class into a RECharSet */
2126 ProcessCharSet(REGlobalData *gData, RECharSet *charSet)
2128 const WCHAR *src, *end;
2129 BOOL inRange = FALSE;
2130 WCHAR rangeStart = 0;
2135 assert(!charSet->converted);
2137 * Assert that startIndex and length points to chars inside [] inside
2140 assert(1 <= charSet->u.src.startIndex);
2141 assert(charSet->u.src.startIndex
2142 < SysStringLen(gData->regexp->source));
2143 assert(charSet->u.src.length <= SysStringLen(gData->regexp->source)
2144 - 1 - charSet->u.src.startIndex);
2146 charSet->converted = TRUE;
2147 src = gData->regexp->source + charSet->u.src.startIndex;
2149 end = src + charSet->u.src.length;
2151 assert(src[-1] == '[' && end[0] == ']');
2153 byteLength = (charSet->length >> 3) + 1;
2154 charSet->u.bits = heap_alloc(byteLength);
2155 if (!charSet->u.bits) {
2156 JS_ReportOutOfMemory(gData->cx);
2160 memset(charSet->u.bits, 0, byteLength);
2166 assert(charSet->sense == FALSE);
2169 assert(charSet->sense == TRUE);
2172 while (src != end) {
2197 if (src < end && JS_ISWORD(*src)) {
2198 thisCh = (WCHAR)(*src++ & 0x1F);
2211 for (i = 0; (i < nDigits) && (src < end); i++) {
2214 if (!isASCIIHexDigit(c, &digit)) {
2216 * Back off to accepting the original '\'
2223 n = (n << 4) | digit;
2236 * This is a non-ECMA extension - decimal escapes (in this
2237 * case, octal!) are supposed to be an error inside class
2238 * ranges, but supported here for backwards compatibility.
2242 if ('0' <= c && c <= '7') {
2244 n = 8 * n + JS7_UNDEC(c);
2246 if ('0' <= c && c <= '7') {
2248 i = 8 * n + JS7_UNDEC(c);
2259 AddCharacterRangeToCharSet(charSet, '0', '9');
2260 continue; /* don't need range processing */
2262 AddCharacterRangeToCharSet(charSet, 0, '0' - 1);
2263 AddCharacterRangeToCharSet(charSet,
2265 (WCHAR)charSet->length);
2268 for (i = (INT)charSet->length; i >= 0; i--)
2270 AddCharacterToCharSet(charSet, (WCHAR)i);
2273 for (i = (INT)charSet->length; i >= 0; i--)
2275 AddCharacterToCharSet(charSet, (WCHAR)i);
2278 for (i = (INT)charSet->length; i >= 0; i--)
2280 AddCharacterToCharSet(charSet, (WCHAR)i);
2283 for (i = (INT)charSet->length; i >= 0; i--)
2285 AddCharacterToCharSet(charSet, (WCHAR)i);
2300 if (gData->regexp->flags & JSREG_FOLD) {
2303 assert(rangeStart <= thisCh);
2304 for (i = rangeStart; i <= thisCh; i++) {
2307 AddCharacterToCharSet(charSet, i);
2311 AddCharacterToCharSet(charSet, uch);
2313 AddCharacterToCharSet(charSet, dch);
2316 AddCharacterRangeToCharSet(charSet, rangeStart, thisCh);
2320 if (gData->regexp->flags & JSREG_FOLD) {
2321 AddCharacterToCharSet(charSet, toupperW(thisCh));
2322 AddCharacterToCharSet(charSet, tolowerW(thisCh));
2324 AddCharacterToCharSet(charSet, thisCh);
2326 if (src < end - 1) {
2330 rangeStart = thisCh;
2339 ReallocStateStack(REGlobalData *gData)
2341 size_t limit = gData->stateStackLimit;
2342 size_t sz = sizeof(REProgState) * limit;
2344 gData->stateStack = jsheap_grow(gData->pool, gData->stateStack, sz, sz);
2345 if (!gData->stateStack) {
2346 js_ReportOutOfScriptQuota(gData->cx);
2350 gData->stateStackLimit = limit + limit;
2354 #define PUSH_STATE_STACK(data) \
2356 ++(data)->stateStackTop; \
2357 if ((data)->stateStackTop == (data)->stateStackLimit && \
2358 !ReallocStateStack((data))) { \
2364 * Apply the current op against the given input to see if it's going to match
2365 * or fail. Return false if we don't get a match, true if we do. If updatecp is
2366 * true, then update the current state's cp. Always update startpc to the next
2369 static inline REMatchState *
2370 SimpleMatch(REGlobalData *gData, REMatchState *x, REOp op,
2371 jsbytecode **startpc, BOOL updatecp)
2373 REMatchState *result = NULL;
2376 size_t offset, length, index;
2377 jsbytecode *pc = *startpc; /* pc has already been incremented past op */
2379 const WCHAR *startcp = x->cp;
2383 const char *opname = reop_names[op];
2384 TRACE("\n%06d: %*s%s\n", pc - gData->regexp->program,
2385 (int)gData->stateStackTop * 2, "", opname);
2392 if (x->cp != gData->cpbegin) {
2393 if (/*!gData->cx->regExpStatics.multiline && FIXME !!! */
2394 !(gData->regexp->flags & JSREG_MULTILINE)) {
2397 if (!RE_IS_LINE_TERM(x->cp[-1]))
2403 if (x->cp != gData->cpend) {
2404 if (/*!gData->cx->regExpStatics.multiline &&*/
2405 !(gData->regexp->flags & JSREG_MULTILINE)) {
2408 if (!RE_IS_LINE_TERM(*x->cp))
2414 if ((x->cp == gData->cpbegin || !JS_ISWORD(x->cp[-1])) ^
2415 !(x->cp != gData->cpend && JS_ISWORD(*x->cp))) {
2420 if ((x->cp == gData->cpbegin || !JS_ISWORD(x->cp[-1])) ^
2421 (x->cp != gData->cpend && JS_ISWORD(*x->cp))) {
2426 if (x->cp != gData->cpend && !RE_IS_LINE_TERM(*x->cp)) {
2432 if (x->cp != gData->cpend && JS7_ISDEC(*x->cp)) {
2438 if (x->cp != gData->cpend && !JS7_ISDEC(*x->cp)) {
2444 if (x->cp != gData->cpend && JS_ISWORD(*x->cp)) {
2450 if (x->cp != gData->cpend && !JS_ISWORD(*x->cp)) {
2456 if (x->cp != gData->cpend && isspaceW(*x->cp)) {
2462 if (x->cp != gData->cpend && !isspaceW(*x->cp)) {
2468 pc = ReadCompactIndex(pc, &parenIndex);
2469 assert(parenIndex < gData->regexp->parenCount);
2470 result = BackrefMatcher(gData, x, parenIndex);
2473 pc = ReadCompactIndex(pc, &offset);
2474 assert(offset < SysStringLen(gData->regexp->source));
2475 pc = ReadCompactIndex(pc, &length);
2476 assert(1 <= length);
2477 assert(length <= SysStringLen(gData->regexp->source) - offset);
2478 if (length <= (size_t)(gData->cpend - x->cp)) {
2479 source = gData->regexp->source + offset;
2480 TRACE("%s\n", debugstr_wn(source, length));
2481 for (index = 0; index != length; index++) {
2482 if (source[index] != x->cp[index])
2491 TRACE(" '%c' == '%c'\n", (char)matchCh, (char)*x->cp);
2492 if (x->cp != gData->cpend && *x->cp == matchCh) {
2498 pc = ReadCompactIndex(pc, &offset);
2499 assert(offset < SysStringLen(gData->regexp->source));
2500 pc = ReadCompactIndex(pc, &length);
2501 assert(1 <= length);
2502 assert(length <= SysStringLen(gData->regexp->source) - offset);
2503 source = gData->regexp->source;
2504 result = FlatNIMatcher(gData, x, source + offset, length);
2508 if (x->cp != gData->cpend && toupperW(*x->cp) == toupperW(matchCh)) {
2514 matchCh = GET_ARG(pc);
2515 TRACE(" '%c' == '%c'\n", (char)matchCh, (char)*x->cp);
2517 if (x->cp != gData->cpend && *x->cp == matchCh) {
2523 matchCh = GET_ARG(pc);
2525 if (x->cp != gData->cpend && toupperW(*x->cp) == toupperW(matchCh)) {
2531 pc = ReadCompactIndex(pc, &index);
2532 assert(index < gData->regexp->classCount);
2533 if (x->cp != gData->cpend) {
2534 charSet = &gData->regexp->classList[index];
2535 assert(charSet->converted);
2538 if (charSet->length != 0 &&
2539 ch <= charSet->length &&
2540 (charSet->u.bits[index] & (1 << (ch & 0x7)))) {
2547 pc = ReadCompactIndex(pc, &index);
2548 assert(index < gData->regexp->classCount);
2549 if (x->cp != gData->cpend) {
2550 charSet = &gData->regexp->classList[index];
2551 assert(charSet->converted);
2554 if (charSet->length == 0 ||
2555 ch > charSet->length ||
2556 !(charSet->u.bits[index] & (1 << (ch & 0x7)))) {
2577 static inline REMatchState *
2578 ExecuteREBytecode(REGlobalData *gData, REMatchState *x)
2580 REMatchState *result = NULL;
2581 REBackTrackData *backTrackData;
2582 jsbytecode *nextpc, *testpc;
2585 REProgState *curState;
2586 const WCHAR *startcp;
2587 size_t parenIndex, k;
2588 size_t parenSoFar = 0;
2590 WCHAR matchCh1, matchCh2;
2594 jsbytecode *pc = gData->regexp->program;
2595 REOp op = (REOp) *pc++;
2598 * If the first node is a simple match, step the index into the string
2599 * until that match is made, or fail if it can't be found at all.
2601 if (REOP_IS_SIMPLE(op) && !(gData->regexp->flags & JSREG_STICKY)) {
2603 while (x->cp <= gData->cpend) {
2604 nextpc = pc; /* reset back to start each time */
2605 result = SimpleMatch(gData, x, op, &nextpc, TRUE);
2609 pc = nextpc; /* accept skip to next opcode */
2611 assert(op < REOP_LIMIT);
2622 const char *opname = reop_names[op];
2623 TRACE("\n%06d: %*s%s\n", pc - gData->regexp->program,
2624 (int)gData->stateStackTop * 2, "", opname);
2626 if (REOP_IS_SIMPLE(op)) {
2627 result = SimpleMatch(gData, x, op, &pc, TRUE);
2629 curState = &gData->stateStack[gData->stateStackTop];
2633 case REOP_ALTPREREQ2:
2634 nextpc = pc + GET_OFFSET(pc); /* start of next op */
2636 matchCh2 = GET_ARG(pc);
2641 if (x->cp != gData->cpend) {
2642 if (*x->cp == matchCh2)
2645 charSet = &gData->regexp->classList[k];
2646 if (!charSet->converted && !ProcessCharSet(gData, charSet))
2650 if ((charSet->length == 0 ||
2651 matchCh1 > charSet->length ||
2652 !(charSet->u.bits[k] & (1 << (matchCh1 & 0x7)))) ^
2660 case REOP_ALTPREREQ:
2661 nextpc = pc + GET_OFFSET(pc); /* start of next op */
2663 matchCh1 = GET_ARG(pc);
2665 matchCh2 = GET_ARG(pc);
2667 if (x->cp == gData->cpend ||
2668 (*x->cp != matchCh1 && *x->cp != matchCh2)) {
2672 /* else false thru... */
2676 nextpc = pc + GET_OFFSET(pc); /* start of next alternate */
2677 pc += ARG_LEN; /* start of this alternate */
2678 curState->parenSoFar = parenSoFar;
2679 PUSH_STATE_STACK(gData);
2682 if (REOP_IS_SIMPLE(op)) {
2683 if (!SimpleMatch(gData, x, op, &pc, TRUE)) {
2684 op = (REOp) *nextpc++;
2691 nextop = (REOp) *nextpc++;
2692 if (!PushBackTrackState(gData, nextop, nextpc, x, startcp, 0, 0))
2697 * Occurs at (successful) end of REOP_ALT,
2701 * If we have not gotten a result here, it is because of an
2702 * empty match. Do the same thing REOP_EMPTY would do.
2707 --gData->stateStackTop;
2708 pc += GET_OFFSET(pc);
2713 * Occurs at last (successful) end of REOP_ALT,
2717 * If we have not gotten a result here, it is because of an
2718 * empty match. Do the same thing REOP_EMPTY would do.
2723 --gData->stateStackTop;
2728 pc = ReadCompactIndex(pc, &parenIndex);
2729 TRACE("[ %lu ]\n", (unsigned long) parenIndex);
2730 assert(parenIndex < gData->regexp->parenCount);
2731 if (parenIndex + 1 > parenSoFar)
2732 parenSoFar = parenIndex + 1;
2733 x->parens[parenIndex].index = x->cp - gData->cpbegin;
2734 x->parens[parenIndex].length = 0;
2742 pc = ReadCompactIndex(pc, &parenIndex);
2743 assert(parenIndex < gData->regexp->parenCount);
2744 cap = &x->parens[parenIndex];
2745 delta = x->cp - (gData->cpbegin + cap->index);
2746 cap->length = (delta < 0) ? 0 : (size_t) delta;
2754 nextpc = pc + GET_OFFSET(pc); /* start of term after ASSERT */
2755 pc += ARG_LEN; /* start of ASSERT child */
2758 if (REOP_IS_SIMPLE(op) &&
2759 !SimpleMatch(gData, x, op, &testpc, FALSE)) {
2763 curState->u.assertion.top =
2764 (char *)gData->backTrackSP - (char *)gData->backTrackStack;
2765 curState->u.assertion.sz = gData->cursz;
2766 curState->index = x->cp - gData->cpbegin;
2767 curState->parenSoFar = parenSoFar;
2768 PUSH_STATE_STACK(gData);
2769 if (!PushBackTrackState(gData, REOP_ASSERTTEST,
2770 nextpc, x, x->cp, 0, 0)) {
2775 case REOP_ASSERT_NOT:
2776 nextpc = pc + GET_OFFSET(pc);
2780 if (REOP_IS_SIMPLE(op) /* Note - fail to fail! */ &&
2781 SimpleMatch(gData, x, op, &testpc, FALSE) &&
2782 *testpc == REOP_ASSERTNOTTEST) {
2786 curState->u.assertion.top
2787 = (char *)gData->backTrackSP -
2788 (char *)gData->backTrackStack;
2789 curState->u.assertion.sz = gData->cursz;
2790 curState->index = x->cp - gData->cpbegin;
2791 curState->parenSoFar = parenSoFar;
2792 PUSH_STATE_STACK(gData);
2793 if (!PushBackTrackState(gData, REOP_ASSERTNOTTEST,
2794 nextpc, x, x->cp, 0, 0)) {
2799 case REOP_ASSERTTEST:
2800 --gData->stateStackTop;
2802 x->cp = gData->cpbegin + curState->index;
2803 gData->backTrackSP =
2804 (REBackTrackData *) ((char *)gData->backTrackStack +
2805 curState->u.assertion.top);
2806 gData->cursz = curState->u.assertion.sz;
2811 case REOP_ASSERTNOTTEST:
2812 --gData->stateStackTop;
2814 x->cp = gData->cpbegin + curState->index;
2815 gData->backTrackSP =
2816 (REBackTrackData *) ((char *)gData->backTrackStack +
2817 curState->u.assertion.top);
2818 gData->cursz = curState->u.assertion.sz;
2819 result = (!result) ? x : NULL;
2822 curState->u.quantifier.min = 0;
2823 curState->u.quantifier.max = (UINT)-1;
2826 curState->u.quantifier.min = 1;
2827 curState->u.quantifier.max = (UINT)-1;
2830 curState->u.quantifier.min = 0;
2831 curState->u.quantifier.max = 1;
2834 pc = ReadCompactIndex(pc, &k);
2835 curState->u.quantifier.min = k;
2836 pc = ReadCompactIndex(pc, &k);
2837 /* max is k - 1 to use one byte for (UINT)-1 sentinel. */
2838 curState->u.quantifier.max = k - 1;
2839 assert(curState->u.quantifier.min <= curState->u.quantifier.max);
2841 if (curState->u.quantifier.max == 0) {
2842 pc = pc + GET_OFFSET(pc);
2847 /* Step over <next> */
2848 nextpc = pc + ARG_LEN;
2849 op = (REOp) *nextpc++;
2851 if (REOP_IS_SIMPLE(op)) {
2852 if (!SimpleMatch(gData, x, op, &nextpc, TRUE)) {
2853 if (curState->u.quantifier.min == 0)
2857 pc = pc + GET_OFFSET(pc);
2860 op = (REOp) *nextpc++;
2863 curState->index = startcp - gData->cpbegin;
2864 curState->continue_op = REOP_REPEAT;
2865 curState->continue_pc = pc;
2866 curState->parenSoFar = parenSoFar;
2867 PUSH_STATE_STACK(gData);
2868 if (curState->u.quantifier.min == 0 &&
2869 !PushBackTrackState(gData, REOP_REPEAT, pc, x, startcp,
2876 case REOP_ENDCHILD: /* marks the end of a quantifier child */
2877 pc = curState[-1].continue_pc;
2878 op = (REOp) curState[-1].continue_op;
2887 --gData->stateStackTop;
2889 /* Failed, see if we have enough children. */
2890 if (curState->u.quantifier.min == 0)
2894 if (curState->u.quantifier.min == 0 &&
2895 x->cp == gData->cpbegin + curState->index) {
2896 /* matched an empty string, that'll get us nowhere */
2900 if (curState->u.quantifier.min != 0)
2901 curState->u.quantifier.min--;
2902 if (curState->u.quantifier.max != (UINT) -1)
2903 curState->u.quantifier.max--;
2904 if (curState->u.quantifier.max == 0)
2906 nextpc = pc + ARG_LEN;
2907 nextop = (REOp) *nextpc;
2909 if (REOP_IS_SIMPLE(nextop)) {
2911 if (!SimpleMatch(gData, x, nextop, &nextpc, TRUE)) {
2912 if (curState->u.quantifier.min == 0)
2919 curState->index = startcp - gData->cpbegin;
2920 PUSH_STATE_STACK(gData);
2921 if (curState->u.quantifier.min == 0 &&
2922 !PushBackTrackState(gData, REOP_REPEAT,
2924 curState->parenSoFar,
2926 curState->parenSoFar)) {
2929 } while (*nextpc == REOP_ENDCHILD);
2932 parenSoFar = curState->parenSoFar;
2937 pc += GET_OFFSET(pc);
2940 case REOP_MINIMALSTAR:
2941 curState->u.quantifier.min = 0;
2942 curState->u.quantifier.max = (UINT)-1;
2943 goto minimalquantcommon;
2944 case REOP_MINIMALPLUS:
2945 curState->u.quantifier.min = 1;
2946 curState->u.quantifier.max = (UINT)-1;
2947 goto minimalquantcommon;
2948 case REOP_MINIMALOPT:
2949 curState->u.quantifier.min = 0;
2950 curState->u.quantifier.max = 1;
2951 goto minimalquantcommon;
2952 case REOP_MINIMALQUANT:
2953 pc = ReadCompactIndex(pc, &k);
2954 curState->u.quantifier.min = k;
2955 pc = ReadCompactIndex(pc, &k);
2956 /* See REOP_QUANT comments about k - 1. */
2957 curState->u.quantifier.max = k - 1;
2958 assert(curState->u.quantifier.min
2959 <= curState->u.quantifier.max);
2961 curState->index = x->cp - gData->cpbegin;
2962 curState->parenSoFar = parenSoFar;
2963 PUSH_STATE_STACK(gData);
2964 if (curState->u.quantifier.min != 0) {
2965 curState->continue_op = REOP_MINIMALREPEAT;
2966 curState->continue_pc = pc;
2967 /* step over <next> */
2971 if (!PushBackTrackState(gData, REOP_MINIMALREPEAT,
2972 pc, x, x->cp, 0, 0)) {
2975 --gData->stateStackTop;
2976 pc = pc + GET_OFFSET(pc);
2981 case REOP_MINIMALREPEAT:
2982 --gData->stateStackTop;
2985 TRACE("{%d,%d}\n", curState->u.quantifier.min, curState->u.quantifier.max);
2986 #define PREPARE_REPEAT() \
2988 curState->index = x->cp - gData->cpbegin; \
2989 curState->continue_op = REOP_MINIMALREPEAT; \
2990 curState->continue_pc = pc; \
2992 for (k = curState->parenSoFar; k < parenSoFar; k++) \
2993 x->parens[k].index = -1; \
2994 PUSH_STATE_STACK(gData); \
2995 op = (REOp) *pc++; \
2996 assert(op < REOP_LIMIT); \
3002 * Non-greedy failure - try to consume another child.
3004 if (curState->u.quantifier.max == (UINT) -1 ||
3005 curState->u.quantifier.max > 0) {
3009 /* Don't need to adjust pc since we're going to pop. */
3012 if (curState->u.quantifier.min == 0 &&
3013 x->cp == gData->cpbegin + curState->index) {
3014 /* Matched an empty string, that'll get us nowhere. */
3018 if (curState->u.quantifier.min != 0)
3019 curState->u.quantifier.min--;
3020 if (curState->u.quantifier.max != (UINT) -1)
3021 curState->u.quantifier.max--;
3022 if (curState->u.quantifier.min != 0) {
3026 curState->index = x->cp - gData->cpbegin;
3027 curState->parenSoFar = parenSoFar;
3028 PUSH_STATE_STACK(gData);
3029 if (!PushBackTrackState(gData, REOP_MINIMALREPEAT,
3031 curState->parenSoFar,
3032 parenSoFar - curState->parenSoFar)) {
3035 --gData->stateStackTop;
3036 pc = pc + GET_OFFSET(pc);
3038 assert(op < REOP_LIMIT);
3048 * If the match failed and there's a backtrack option, take it.
3049 * Otherwise this is a complete and utter failure.
3052 if (gData->cursz == 0)
3055 /* Potentially detect explosive regex here. */
3056 gData->backTrackCount++;
3057 if (gData->backTrackLimit &&
3058 gData->backTrackCount >= gData->backTrackLimit) {
3059 JS_ReportErrorNumber(gData->cx, js_GetErrorMessage, NULL,
3060 JSMSG_REGEXP_TOO_COMPLEX);
3065 backTrackData = gData->backTrackSP;
3066 gData->cursz = backTrackData->sz;
3067 gData->backTrackSP =
3068 (REBackTrackData *) ((char *)backTrackData - backTrackData->sz);
3069 x->cp = backTrackData->cp;
3070 pc = backTrackData->backtrack_pc;
3071 op = (REOp) backTrackData->backtrack_op;
3072 assert(op < REOP_LIMIT);
3073 gData->stateStackTop = backTrackData->saveStateStackTop;
3074 assert(gData->stateStackTop);
3076 memcpy(gData->stateStack, backTrackData + 1,
3077 sizeof(REProgState) * backTrackData->saveStateStackTop);
3078 curState = &gData->stateStack[gData->stateStackTop - 1];
3080 if (backTrackData->parenCount) {
3081 memcpy(&x->parens[backTrackData->parenIndex],
3082 (char *)(backTrackData + 1) +
3083 sizeof(REProgState) * backTrackData->saveStateStackTop,
3084 sizeof(RECapture) * backTrackData->parenCount);
3085 parenSoFar = backTrackData->parenIndex + backTrackData->parenCount;
3087 for (k = curState->parenSoFar; k < parenSoFar; k++)
3088 x->parens[k].index = -1;
3089 parenSoFar = curState->parenSoFar;
3092 TRACE("\tBT_Pop: %ld,%ld\n",
3093 (unsigned long) backTrackData->parenIndex,
3094 (unsigned long) backTrackData->parenCount);
3100 * Continue with the expression.
3103 assert(op < REOP_LIMIT);
3115 static REMatchState *MatchRegExp(REGlobalData *gData, REMatchState *x)
3117 REMatchState *result;
3118 const WCHAR *cp = x->cp;
3123 * Have to include the position beyond the last character
3124 * in order to detect end-of-input/line condition.
3126 for (cp2 = cp; cp2 <= gData->cpend; cp2++) {
3127 gData->skipped = cp2 - cp;
3129 for (j = 0; j < gData->regexp->parenCount; j++)
3130 x->parens[j].index = -1;
3131 result = ExecuteREBytecode(gData, x);
3132 if (!gData->ok || result || (gData->regexp->flags & JSREG_STICKY))
3134 gData->backTrackSP = gData->backTrackStack;
3136 gData->stateStackTop = 0;
3137 cp2 = cp + gData->skipped;
3142 #define MIN_BACKTRACK_LIMIT 400000
3144 static REMatchState *InitMatch(script_ctx_t *cx, REGlobalData *gData, JSRegExp *re, size_t length)
3146 REMatchState *result;
3149 gData->backTrackStackSize = INITIAL_BACKTRACK;
3150 gData->backTrackStack = jsheap_alloc(gData->pool, INITIAL_BACKTRACK);
3151 if (!gData->backTrackStack)
3154 gData->backTrackSP = gData->backTrackStack;
3156 gData->backTrackCount = 0;
3157 gData->backTrackLimit = 0;
3159 gData->stateStackLimit = INITIAL_STATESTACK;
3160 gData->stateStack = jsheap_alloc(gData->pool, sizeof(REProgState) * INITIAL_STATESTACK);
3161 if (!gData->stateStack)
3164 gData->stateStackTop = 0;
3169 result = jsheap_alloc(gData->pool, offsetof(REMatchState, parens) + re->parenCount * sizeof(RECapture));
3173 for (i = 0; i < re->classCount; i++) {
3174 if (!re->classList[i].converted &&
3175 !ProcessCharSet(gData, &re->classList[i])) {
3183 js_ReportOutOfScriptQuota(cx);
3189 js_DestroyRegExp(JSRegExp *re)
3191 if (re->classList) {
3193 for (i = 0; i < re->classCount; i++) {
3194 if (re->classList[i].converted)
3195 heap_free(re->classList[i].u.bits);
3196 re->classList[i].u.bits = NULL;
3198 heap_free(re->classList);
3204 js_NewRegExp(script_ctx_t *cx, BSTR str, UINT flags, BOOL flat)
3208 CompilerState state;
3215 mark = jsheap_mark(&cx->tmp_heap);
3216 len = SysStringLen(str);
3222 state.cpbegin = state.cp;
3223 state.cpend = state.cp + len;
3224 state.flags = flags;
3225 state.parenCount = 0;
3226 state.classCount = 0;
3227 state.progLength = 0;
3228 state.treeDepth = 0;
3229 state.classBitmapsMem = 0;
3230 for (i = 0; i < CLASS_CACHE_SIZE; i++)
3231 state.classCache[i].start = NULL;
3233 if (len != 0 && flat) {
3234 state.result = NewRENode(&state, REOP_FLAT);
3237 state.result->u.flat.chr = *state.cpbegin;
3238 state.result->u.flat.length = len;
3239 state.result->kid = (void *) state.cpbegin;
3240 /* Flat bytecode: REOP_FLAT compact(string_offset) compact(len). */
3241 state.progLength += 1 + GetCompactIndexWidth(0)
3242 + GetCompactIndexWidth(len);
3244 if (!ParseRegExp(&state))
3247 resize = offsetof(JSRegExp, program) + state.progLength + 1;
3248 re = heap_alloc(resize);
3252 assert(state.classBitmapsMem <= CLASS_BITMAPS_MEM_LIMIT);
3253 re->classCount = state.classCount;
3254 if (re->classCount) {
3255 re->classList = heap_alloc(re->classCount * sizeof(RECharSet));
3256 if (!re->classList) {
3257 js_DestroyRegExp(re);
3261 for (i = 0; i < re->classCount; i++)
3262 re->classList[i].converted = FALSE;
3264 re->classList = NULL;
3266 endPC = EmitREBytecode(&state, re, state.treeDepth, re->program, state.result);
3268 js_DestroyRegExp(re);
3272 *endPC++ = REOP_END;
3274 * Check whether size was overestimated and shrink using realloc.
3275 * This is safe since no pointers to newly parsed regexp or its parts
3276 * besides re exist here.
3278 if ((size_t)(endPC - re->program) != state.progLength + 1) {
3280 assert((size_t)(endPC - re->program) < state.progLength + 1);
3281 resize = offsetof(JSRegExp, program) + (endPC - re->program);
3282 tmp = heap_realloc(re, resize);
3288 re->parenCount = state.parenCount;
3296 static HRESULT do_regexp_match_next(RegExpInstance *regexp, const WCHAR *str, DWORD len,
3297 const WCHAR **cp, match_result_t **parens, DWORD *parens_size, DWORD *parens_cnt, match_result_t *ret)
3299 REMatchState *x, *result;
3303 gData.cpbegin = *cp;
3304 gData.cpend = str + len;
3305 gData.start = *cp-str;
3307 gData.pool = ®exp->dispex.ctx->tmp_heap;
3309 x = InitMatch(NULL, &gData, regexp->jsregexp, gData.cpend - gData.cpbegin);
3311 WARN("InitMatch failed\n");
3316 result = MatchRegExp(&gData, x);
3318 WARN("MatchRegExp failed\n");
3328 if(regexp->jsregexp->parenCount > *parens_size) {
3329 match_result_t *new_parens;
3332 new_parens = heap_realloc(*parens, sizeof(match_result_t)*regexp->jsregexp->parenCount);
3334 new_parens = heap_alloc(sizeof(match_result_t)*regexp->jsregexp->parenCount);
3336 return E_OUTOFMEMORY;
3338 *parens = new_parens;
3341 *parens_cnt = regexp->jsregexp->parenCount;
3343 for(i=0; i < regexp->jsregexp->parenCount; i++) {
3344 (*parens)[i].str = *cp + result->parens[i].index;
3345 (*parens)[i].len = result->parens[i].length;
3349 matchlen = (result->cp-*cp) - gData.skipped;
3351 ret->str = result->cp-matchlen;
3352 ret->len = matchlen;
3357 HRESULT regexp_match_next(DispatchEx *dispex, BOOL gcheck, const WCHAR *str, DWORD len,
3358 const WCHAR **cp, match_result_t **parens, DWORD *parens_size, DWORD *parens_cnt, match_result_t *ret)
3360 RegExpInstance *regexp = (RegExpInstance*)dispex;
3364 if(gcheck && !(regexp->jsregexp->flags & JSREG_GLOB))
3367 mark = jsheap_mark(®exp->dispex.ctx->tmp_heap);
3369 hres = do_regexp_match_next(regexp, str, len, cp, parens, parens_size, parens_cnt, ret);
3375 HRESULT regexp_match(DispatchEx *dispex, const WCHAR *str, DWORD len, BOOL gflag, match_result_t **match_result,
3378 RegExpInstance *This = (RegExpInstance*)dispex;
3379 match_result_t *ret = NULL, cres;
3380 const WCHAR *cp = str;
3381 DWORD i=0, ret_size = 0;
3385 mark = jsheap_mark(&This->dispex.ctx->tmp_heap);
3388 hres = do_regexp_match_next(This, str, len, &cp, NULL, NULL, NULL, &cres);
3389 if(hres == S_FALSE) {
3399 ret = heap_realloc(ret, (ret_size <<= 1) * sizeof(match_result_t));
3401 ret = heap_alloc((ret_size=4) * sizeof(match_result_t));
3403 hres = E_OUTOFMEMORY;
3410 if(!gflag && !(This->jsregexp->flags & JSREG_GLOB)) {
3422 *match_result = ret;
3427 static HRESULT RegExp_source(DispatchEx *dispex, LCID lcid, WORD flags, DISPPARAMS *dp,
3428 VARIANT *retv, jsexcept_t *ei, IServiceProvider *sp)
3434 static HRESULT RegExp_global(DispatchEx *dispex, LCID lcid, WORD flags, DISPPARAMS *dp,
3435 VARIANT *retv, jsexcept_t *ei, IServiceProvider *sp)
3441 static HRESULT RegExp_ignoreCase(DispatchEx *dispex, LCID lcid, WORD flags, DISPPARAMS *dp,
3442 VARIANT *retv, jsexcept_t *ei, IServiceProvider *sp)
3448 static HRESULT RegExp_multiline(DispatchEx *dispex, LCID lcid, WORD flags, DISPPARAMS *dp,
3449 VARIANT *retv, jsexcept_t *ei, IServiceProvider *sp)
3455 static HRESULT RegExp_lastIndex(DispatchEx *dispex, LCID lcid, WORD flags, DISPPARAMS *dp,
3456 VARIANT *retv, jsexcept_t *ei, IServiceProvider *sp)
3462 static HRESULT RegExp_toString(DispatchEx *dispex, LCID lcid, WORD flags, DISPPARAMS *dp,
3463 VARIANT *retv, jsexcept_t *ei, IServiceProvider *sp)
3469 static HRESULT RegExp_exec(DispatchEx *dispex, LCID lcid, WORD flags, DISPPARAMS *dp,
3470 VARIANT *retv, jsexcept_t *ei, IServiceProvider *sp)
3476 static HRESULT RegExp_test(DispatchEx *dispex, LCID lcid, WORD flags, DISPPARAMS *dp,
3477 VARIANT *retv, jsexcept_t *ei, IServiceProvider *sp)
3483 static HRESULT RegExp_value(DispatchEx *dispex, LCID lcid, WORD flags, DISPPARAMS *dp,
3484 VARIANT *retv, jsexcept_t *ei, IServiceProvider *sp)
3490 return throw_type_error(dispex->ctx, ei, IDS_NOT_FUNC, NULL);
3492 FIXME("unimplemented flags %x\n", flags);
3499 static void RegExp_destructor(DispatchEx *dispex)
3501 RegExpInstance *This = (RegExpInstance*)dispex;
3504 js_DestroyRegExp(This->jsregexp);
3505 SysFreeString(This->str);
3509 static const builtin_prop_t RegExp_props[] = {
3510 {execW, RegExp_exec, PROPF_METHOD},
3511 {globalW, RegExp_global, 0},
3512 {ignoreCaseW, RegExp_ignoreCase, 0},
3513 {lastIndexW, RegExp_lastIndex, 0},
3514 {multilineW, RegExp_multiline, 0},
3515 {sourceW, RegExp_source, 0},
3516 {testW, RegExp_test, PROPF_METHOD},
3517 {toStringW, RegExp_toString, PROPF_METHOD}
3520 static const builtin_info_t RegExp_info = {
3522 {NULL, RegExp_value, 0},
3523 sizeof(RegExp_props)/sizeof(*RegExp_props),
3529 static HRESULT alloc_regexp(script_ctx_t *ctx, DispatchEx *object_prototype, RegExpInstance **ret)
3531 RegExpInstance *regexp;
3534 regexp = heap_alloc_zero(sizeof(RegExpInstance));
3536 return E_OUTOFMEMORY;
3538 if(object_prototype)
3539 hres = init_dispex(®exp->dispex, ctx, &RegExp_info, object_prototype);
3541 hres = init_dispex_from_constr(®exp->dispex, ctx, &RegExp_info, ctx->regexp_constr);
3552 static HRESULT create_regexp(script_ctx_t *ctx, const WCHAR *exp, int len, DWORD flags, DispatchEx **ret)
3554 RegExpInstance *regexp;
3557 TRACE("%s %x\n", debugstr_w(exp), flags);
3559 hres = alloc_regexp(ctx, NULL, ®exp);
3564 regexp->str = SysAllocString(exp);
3566 regexp->str = SysAllocStringLen(exp, len);
3568 jsdisp_release(®exp->dispex);
3569 return E_OUTOFMEMORY;
3572 regexp->jsregexp = js_NewRegExp(ctx, regexp->str, flags, FALSE);
3573 if(!regexp->jsregexp) {
3574 WARN("js_NewRegExp failed\n");
3575 jsdisp_release(®exp->dispex);
3579 *ret = ®exp->dispex;
3583 static HRESULT regexp_constructor(script_ctx_t *ctx, DISPPARAMS *dp, VARIANT *retv)
3585 const WCHAR *opt = emptyW, *src;
3595 arg = get_arg(dp,0);
3596 if(V_VT(arg) == VT_DISPATCH) {
3599 obj = iface_to_jsdisp((IUnknown*)V_DISPATCH(arg));
3601 if(is_class(obj, JSCLASS_REGEXP)) {
3602 RegExpInstance *regexp = (RegExpInstance*)obj;
3604 hres = create_regexp(ctx, regexp->str, -1, regexp->jsregexp->flags, &ret);
3605 jsdisp_release(obj);
3609 V_VT(retv) = VT_DISPATCH;
3610 V_DISPATCH(retv) = (IDispatch*)_IDispatchEx_(ret);
3614 jsdisp_release(obj);
3618 if(V_VT(arg) != VT_BSTR) {
3619 FIXME("vt arg0 = %d\n", V_VT(arg));
3625 if(arg_cnt(dp) >= 2) {
3626 arg = get_arg(dp,1);
3627 if(V_VT(arg) != VT_BSTR) {
3628 FIXME("unimplemented for vt %d\n", V_VT(arg));
3635 hres = create_regexp_str(ctx, src, -1, opt, strlenW(opt), &ret);
3639 V_VT(retv) = VT_DISPATCH;
3640 V_DISPATCH(retv) = (IDispatch*)_IDispatchEx_(ret);
3644 static HRESULT RegExpConstr_value(DispatchEx *dispex, LCID lcid, WORD flags, DISPPARAMS *dp,
3645 VARIANT *retv, jsexcept_t *ei, IServiceProvider *sp)
3650 case DISPATCH_CONSTRUCT:
3651 return regexp_constructor(dispex->ctx, dp, retv);
3653 FIXME("unimplemented flags: %x\n", flags);
3660 HRESULT create_regexp_constr(script_ctx_t *ctx, DispatchEx *object_prototype, DispatchEx **ret)
3662 RegExpInstance *regexp;
3665 hres = alloc_regexp(ctx, object_prototype, ®exp);
3669 hres = create_builtin_function(ctx, RegExpConstr_value, NULL, PROPF_CONSTR, ®exp->dispex, ret);
3671 jsdisp_release(®exp->dispex);
3675 HRESULT create_regexp_str(script_ctx_t *ctx, const WCHAR *exp, DWORD exp_len, const WCHAR *opt,
3676 DWORD opt_len, DispatchEx **ret)
3682 for (p = opt; p < opt+opt_len; p++) {
3685 flags |= JSREG_GLOB;
3688 flags |= JSREG_FOLD;
3691 flags |= JSREG_MULTILINE;
3694 flags |= JSREG_STICKY;
3697 WARN("wrong flag %c\n", *p);
3703 return create_regexp(ctx, exp, exp_len, flags, ret);