Exemplo n.º 1
0
JSValue RegExpObject::matchGlobal(ExecState* exec, JSGlobalObject* globalObject, JSString* string)
{
    RegExp* regExp = this->regExp();

    ASSERT(regExp->global());

    VM* vm = &globalObject->vm();

    setLastIndex(exec, 0);
    if (exec->hadException())
        return jsUndefined();

    String s = string->value(exec);
    RegExpConstructor* regExpConstructor = globalObject->regExpConstructor();
    
    if (regExp->unicode()) {
        unsigned stringLength = s.length();
        return collectMatches(
            *vm, exec, string, s, regExpConstructor, regExp,
            [&] (size_t end) -> size_t {
                return advanceStringUnicode(s, stringLength, end);
            });
    }
    
    return collectMatches(
        *vm, exec, string, s, regExpConstructor, regExp,
        [&] (size_t end) -> size_t {
            return end + 1;
        });
}
Exemplo n.º 2
0
void RegExpTest::test6()	{
	RegExp<char> regexp;
	regexp.evaluate("a.a.b");
	std::cout << "test6 dfa:\n" << regexp.dfa() << std::endl;
	
	Nfa<char> nfa1 = to_nfa(regexp.dfa());
	std::cout << "test6 nfa1:\n" << nfa1 << std::endl;
	
	Nfa<char> nfa2 = nfa_reverse(nfa1);
	std::cout << "test6 nfa2:\n" << nfa2 << std::endl;

	Dfa<char> dfa2 = normalize(minimize(to_dfa(nfa2)));
	std::cout << "test6 dfa2:\n" << dfa2 << std::endl;
	
	CHECK(dfa2, s_, false);
	CHECK(dfa2, s_a, false);
	CHECK(dfa2, s_b, false);
	CHECK(dfa2, s_aa, false);
	CHECK(dfa2, s_bb, false);
	CHECK(dfa2, s_baa, true);


	

}
bool RegisterVerifier::verify(string name, string query) {
    RegExp *re = v[name];
    if(re) {
        return re->match(query);
    }
    return false;
}
logical ODE_SearchReplace :: GetData (char *scope, logical do_replace, CTX_GUIBase *ctxptr )
{
  static const RegExp  deregex_search("([][*.^${}()?\\\\])", "\\\\$1");
  static const RegExp  deregex_replace("([\\\\$])","\\\\$1");
  std::string          search;
  std::string          replace;
  logical              term   = NO;
BEGINSEQ
  if ( Initialize(scope,do_replace) )                ERROR
    
  if ( ctxptr->ExecuteWindow(this,"FORM_SearchReplace",
                             do_replace ? "Replace" : "Search",NO) )
                                                     ERROR
  if ( !IsRegExp() )
  {
    search  = GetSearchString();
    replace = GetReplaceString();
    
    deregex_search.Replace(search);
    deregex_replace.Replace(replace);
    
    search_string.SetValue(const_cast<char *>(search.c_str()));
    replace_string.SetValue(const_cast<char *>(replace.c_str()));
  }

RECOVER
  term = YES;
ENDSEQ
  return(term);
}
Exemplo n.º 5
0
void KRegExpEditorPrivate::slotUpdateEditor( const TQString & txt)
{
  _updating = true;
  bool ok;
  if ( !RegExpConverter::current()->canParse() ) {
      // This can happend if the application set a text through the API.
  }
  else {
      RegExp* result = RegExpConverter::current()->parse( txt, &ok );
      if ( ok ) {
          TQPtrList<CompoundRegExp> list = _userRegExps->regExps();
          for ( TQPtrListIterator<CompoundRegExp> it( list ); *it; ++it ) {
              result->replacePart( *it );
          }

          _scrolledEditorWindow->slotSetRegExp( result );
          _error->hide();
          maybeVerify( );
          recordUndoInfo();
          result->check( _errorMap );
      }
      else {
          _error->show();
          if ( _autoVerify )
              _verifier->clearRegexp();
      }
      delete result;
  }
  _updating = false;
}
Exemplo n.º 6
0
JSValue RegExpObject::matchGlobal(ExecState* exec, JSGlobalObject* globalObject, JSString* string)
{
    VM& vm = globalObject->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);
    RegExp* regExp = this->regExp();

    ASSERT(regExp->global());

    setLastIndex(exec, 0);
    RETURN_IF_EXCEPTION(scope, { });

    String s = string->value(exec);
    RegExpConstructor* regExpConstructor = globalObject->regExpConstructor();

    if (regExp->unicode()) {
        unsigned stringLength = s.length();
        scope.release();
        return collectMatches(
            vm, exec, string, s, regExpConstructor, regExp,
            [&] (size_t end) -> size_t {
                return advanceStringUnicode(s, stringLength, end);
            });
    }

    scope.release();
    return collectMatches(
        vm, exec, string, s, regExpConstructor, regExp,
        [&] (size_t end) -> size_t {
            return end + 1;
        });
}
// ECMA 15.10.4
JSObject* constructRegExp(ExecState* exec, JSGlobalObject* globalObject, const ArgList& args, bool callAsConstructor)
{
    JSValue arg0 = args.at(0);
    JSValue arg1 = args.at(1);

    if (arg0.inherits(&RegExpObject::s_info)) {
        if (!arg1.isUndefined())
            return throwError(exec, createTypeError(exec, "Cannot supply flags when constructing one RegExp from another."));
        // If called as a function, this just returns the first argument (see 15.10.3.1).
        if (callAsConstructor) {
            RegExp* regExp = static_cast<RegExpObject*>(asObject(arg0))->regExp();
            return RegExpObject::create(exec, globalObject, globalObject->regExpStructure(), regExp);
        }
        return asObject(arg0);
    }

    UString pattern = arg0.isUndefined() ? UString("") : arg0.toString(exec)->value(exec);
    if (exec->hadException())
        return 0;

    RegExpFlags flags = NoFlags;
    if (!arg1.isUndefined()) {
        flags = regExpFlags(arg1.toString(exec)->value(exec));
        if (exec->hadException())
            return 0;
        if (flags == InvalidFlags)
            return throwError(exec, createSyntaxError(exec, "Invalid flags supplied to RegExp constructor."));
    }

    RegExp* regExp = RegExp::create(exec->globalData(), pattern, flags);
    if (!regExp->isValid())
        return throwError(exec, createSyntaxError(exec, regExp->errorMessage()));
    return RegExpObject::create(exec, exec->lexicalGlobalObject(), globalObject->regExpStructure(), regExp);
}
Exemplo n.º 8
0
// Shared implementation used by test and exec.
MatchResult RegExpObject::match(ExecState* exec, JSString* string)
{
    RegExp* regExp = this->regExp();
    RegExpConstructor* regExpConstructor = exec->lexicalGlobalObject()->regExpConstructor();
    String input = string->value(exec);
    VM& vm = exec->vm();
    if (!regExp->global())
        return regExpConstructor->performMatch(vm, regExp, string, input, 0);

    JSValue jsLastIndex = getLastIndex();
    unsigned lastIndex;
    if (LIKELY(jsLastIndex.isUInt32())) {
        lastIndex = jsLastIndex.asUInt32();
        if (lastIndex > input.length()) {
            setLastIndex(exec, 0);
            return MatchResult::failed();
        }
    } else {
        double doubleLastIndex = jsLastIndex.toInteger(exec);
        if (doubleLastIndex < 0 || doubleLastIndex > input.length()) {
            setLastIndex(exec, 0);
            return MatchResult::failed();
        }
        lastIndex = static_cast<unsigned>(doubleLastIndex);
    }

    MatchResult result = regExpConstructor->performMatch(vm, regExp, string, input, lastIndex);
    setLastIndex(exec, result.end);
    return result;
}
Exemplo n.º 9
0
void RegExpTest::test5()
{
	RegExp<char> regexp;
	regexp.evaluate("a.((b.(c|d)*)*.(e.(c|d)*)*).f");	
	std::cout << "regexp:\n" << regexp.dfa() << std::endl;
	CHECK(regexp.dfa(), std::string("af"), true);
	CHECK(regexp.dfa(), std::string("abcf"), true);
	CHECK(regexp.dfa(), std::string("abef"), true);
	CHECK(regexp.dfa(), std::string("abecf"), true);


/*	regexp.evaluate("(b.(c|d)*)*.(e.(c|d)*)*");	
	std::cout << "regexp:\n" << regexp.dfa() << std::endl;
	CHECK(regexp.dfa(), std::string("b"), true);
	CHECK(regexp.dfa(), std::string("be"), true);
*/

/*	regexp.evaluate("(b.(c|d)*)*");	
	std::cout << "regexp:\n" << regexp.dfa() << std::endl;
	CHECK(regexp.dfa(), std::string("b"), true);
*/

/*	regexp.evaluate("b*");	
	std::cout << "regexp:\n" << regexp.dfa() << std::endl;
	CHECK(regexp.dfa(), std::string("b"), true);
*/

//	regexp.evaluate("(((l.(d|f)*).(((n.(d|f)*))*.((g.(d|f)*))*).(h.(d|f)*)))");	
//	regexp.evaluate("(((l.(d|f)*).(((n.(d|f)*)*).((g.(d|f)*)*)).(h.(d|f)*)))");	
//	regexp.evaluate("(((l.(d|f)*).((n.(d|f)*)*.(g.(d|f)*)*).(h.(d|f)*)))");	
//	regexp.evaluate("(l.(((n.(d|f)*))*.((g.(d|f)*))*).h)");	

//	regexp.evaluate("l.(((n.(d|f)*)*).((g.(d|f)*)*)).h");
//	regexp.evaluate("l.(((c*.d*))).h");

//	regexp.evaluate("((n.(d|f)*)*.(g.(d|f)*)*)");
//	std::cout << "regexp:\n" << regexp.dfa() << std::endl;
//	CHECK(regexp.dfa(), std::string("lh"), true);

/*	RegExp<char> regexp2;
	regexp2.evaluate("a.((n.(d|f)*)*.(g.(d|f)*)*).b");
	std::cout << "regexp2:\n" << regexp2.dfa() << std::endl;
*/
/*
	RegExp<char> regexp2;
//	regexp2.evaluate("a.((b.(e|f)*)*.(c.(e|f)*)*).d");
//	regexp2.evaluate("((b.(e|f)*)*.(c.(e|f)*)*)");
//	std::cout << "regexp2:\n" << regexp2.dfa() << std::endl;
//	regexp2.evaluate("a.((b.(e|f)*)*.(c.(e|f)*)*)");
//	std::cout << "regexp2:\n" << regexp2.dfa() << std::endl;

//	regexp2.evaluate("((b.(e|f)*)*.(c.(e|f)*)*).g");
	regexp2.evaluate("((b.(e|f)*)*.(c.(e|f)*)*.g");
	std::cout << "regexp2:\n" << regexp2.dfa() << std::endl;
	CHECK(regexp2.dfa(), std::string("g"), true);
*/

}
Exemplo n.º 10
0
bool Diff::compare(string exclude) {
    RegExp exc;
    if (!exclude.empty()) {
        exc.setExpr(exclude);
    }
    bool same = true;
    FileWalker fw;
    vector<string> files1;
    fw.walk(file1, [&] (const File& f) {
        if (f.getType() == File::FileType::DIRECTORY) {
            return;
        }
        if (!exclude.empty() && exc.matches(f.getName())) {
            return;
        }
        string relPart = f.getPath().substr(file1.getPath().size());
        files1.push_back(relPart);
    });
    sort(files1.begin(),files1.end());
    vector<string> files2;
    fw.walk(file2, [&] (const File& f) {
        if (f.getType() == File::FileType::DIRECTORY) {
            return;
        }
        if (!exclude.empty() && exc.matches(f.getName())) {
            return;
        }
        string relPart = f.getPath().substr(file2.getPath().size());
        files2.push_back(relPart);
    });
    sort(files2.begin(),files2.end());
    vector<string> intersected;
    set_intersection(files1.begin(),files1.end(),files2.begin(), files2.end(),back_inserter(intersected));
    for (auto f:intersected) {
        string f1 = file1.getPath() + f;
        string f2 = file2.getPath() + f;
        string cmd = "cmp -s '" + f1 + "' '" + f2 + "'";
        int exitCode = system(cmd.c_str());
        if (exitCode != 0) {
            cout << "meld " << f1 << " " << f2 << endl;
            same =false;
        }
    }
    vector<string> only1;
    set_difference(files1.begin(),files1.end(),files2.begin(), files2.end(),back_inserter(only1));
    for (auto f:only1) {
        cout << "only in " << file1.getPath() << ": " << f << endl;
        same = false;
    }
    vector<string> only2;
    set_difference(files2.begin(),files2.end(),files1.begin(), files1.end(),back_inserter(only2));
    for (auto f:only2) {
        cout << "only in " << file2.getPath() << ": " << f << endl;
        same = false;
    }

    return same;
}
Exemplo n.º 11
0
void ReMatchErrorMessage(const RegExp& re)
{
	if (re.LastError() != errNone)
	{

		Message(MSG_WARNING | MSG_LEFTALIGN, MSG(MError),
			make_vector(GetReErrorString(re.LastError())),
			make_vector<string>(MSG(MOk)));
	}
}
Exemplo n.º 12
0
EncodedJSValue DFG_OPERATION operationNewRegexp(ExecState* exec, void* regexpPtr)
{
    RegExp* regexp = static_cast<RegExp*>(regexpPtr);
    if (!regexp->isValid()) {
        throwError(exec, createSyntaxError(exec, "Invalid flags supplied to RegExp constructor."));
        return JSValue::encode(jsUndefined());
    }
    
    return JSValue::encode(RegExpObject::create(exec->globalData(), exec->lexicalGlobalObject(), exec->lexicalGlobalObject()->regExpStructure(), regexp));
}
Exemplo n.º 13
0
void KRegExpEditorPrivate::recordUndoInfo()
{
  Q_ASSERT( _updating );

  // Update undo/redo stacks
  RegExp* regexp = _scrolledEditorWindow->regExp();
  if ( regexp->toXmlString() != _undoStack.top()->toXmlString() ) {
    _undoStack.push( regexp );
    _redoStack = TQPtrStack<RegExp>();
    emitUndoRedoSignals();
  }
}
Exemplo n.º 14
0
void
collectAllCatalogKeys(BString& inputStr)
{
	RegExp rx;
	struct regexp *rxprg = rx.Compile(rxString.String());
	if (rx.InitCheck() != B_OK) {
		fprintf(stderr, "regex-compilation error %s\n", rx.ErrorString());
		return;
	}
	status_t res;
	const char *in = inputStr.String();
	while (rx.RunMatcher(rxprg, in)) {
		const char *start = rxprg->startp[0];
		in = rxprg->endp[0];
		if (fetchKey(in)) {
			if (haveID) {
				if (showKeys)
					printf("CatKey(%ld)\n", id);
				res = catalog->SetString(id, "");
				if (res != B_OK) {
					fprintf(stderr, "couldn't add key %ld - error: %s\n",
						id, strerror(res));
					exit(-1);
				}
			} else {
				if (showKeys) {
					printf("CatKey(\"%s\", \"%s\", \"%s\")\n", str.String(),
						ctx.String(), cmt.String());
				}
				res = catalog->SetString(str.String(), str.String(),
					ctx.String(), cmt.String());
				if (res != B_OK) {
					fprintf(stderr, "couldn't add key %s,%s,%s - error: %s\n",
						str.String(), ctx.String(), cmt.String(),
						strerror(res));
					exit(-1);
				}
			}
		} else if (showWarnings) {
			const char *end = strchr(in, ';');
			BString match;
			if (end)
				match.SetTo(start, end-start+1);
			else {
				// can't determine end of statement, we output next 40 chars
				match.SetTo(start, 40);
			}
			fprintf(stderr, "Warning: couldn't resolve catalog-access:\n\t%s\n",
				match.String());
		}
	}
}
Exemplo n.º 15
0
RegExp* RegExpObjectImp::makeEngine(ExecState *exec, const UString &p, JSValue *flagsInput)
{
  int reflags = RegExp::None;

  if (!flagsInput->isUndefined()) {
    const UString flags = flagsInput->toString(exec);

    // Check flags
    for (int pos = 0; pos < flags.size(); ++pos) {
      switch (flags[pos].unicode()) {
      case 'g':
        if (reflags & RegExp::Global) {
          throwError(exec, SyntaxError,
                     "Regular expression flag 'g' given twice", 1, -1, "<regexp>");
          return 0;
        }
        reflags |= RegExp::Global;
        break;
      case 'i':
        if (reflags & RegExp::IgnoreCase) {
          throwError(exec, SyntaxError,
                     "Regular expression flag 'i' given twice", 1, -1, "<regexp>");
          return 0;
        }
        reflags |= RegExp::IgnoreCase;
        break;
      case 'm':
        if (reflags & RegExp::Multiline) {
          throwError(exec, SyntaxError,
                     "Regular expression flag 'm' given twice", 1, -1, "<regexp>");
          return 0;
        }
        reflags |= RegExp::Multiline;
        break;
      default: {
          throwError(exec, SyntaxError,
                     "Invalid regular expression flags", 1, -1, "<regexp>");
          return 0;
        }
      }
    }
  }

  RegExp *re = new RegExp(p, reflags);
  if (!re->isValid()) {
    throwError(exec, SyntaxError,
               "Invalid regular expression", 1, -1, "<regexp>");
    delete re;
    return 0;
  }
  return re;
}
Exemplo n.º 16
0
void RegExpCache::invalidateCode()
{
    for (int i = 0; i < maxStrongCacheableEntries; i++)
        m_strongCache[i].clear();
    m_nextEntryInStrongCache = 0;

    RegExpCacheMap::iterator end = m_weakCache.end();
    for (RegExpCacheMap::iterator it = m_weakCache.begin(); it != end; ++it) {
        RegExp* regExp = it->value.get();
        if (!regExp) // Skip zombies.
            continue;
        regExp->invalidateCode();
    }
}
Exemplo n.º 17
0
JSObject* constructRegExp(ExecState* exec, JSGlobalObject* globalObject, const ArgList& args,  JSObject* callee, JSValue newTarget)
{
    VM& vm = exec->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);
    JSValue patternArg = args.at(0);
    JSValue flagsArg = args.at(1);

    bool isPatternRegExp = patternArg.inherits(vm, RegExpObject::info());
    bool constructAsRegexp = isRegExp(vm, exec, patternArg);
    RETURN_IF_EXCEPTION(scope, nullptr);

    if (newTarget.isUndefined() && constructAsRegexp && flagsArg.isUndefined()) {
        JSValue constructor = patternArg.get(exec, vm.propertyNames->constructor);
        RETURN_IF_EXCEPTION(scope, nullptr);
        if (callee == constructor) {
            // We know that patternArg is a object otherwise constructAsRegexp would be false.
            return patternArg.getObject();
        }
    }

    if (isPatternRegExp) {
        RegExp* regExp = jsCast<RegExpObject*>(patternArg)->regExp();
        Structure* structure = getRegExpStructure(exec, globalObject, newTarget);
        RETURN_IF_EXCEPTION(scope, nullptr);

        if (!flagsArg.isUndefined()) {
            RegExpFlags flags = toFlags(exec, flagsArg);
            ASSERT(!!scope.exception() == (flags == InvalidFlags));
            if (flags == InvalidFlags)
                return nullptr;
            regExp = RegExp::create(vm, regExp->pattern(), flags);
        }

        return RegExpObject::create(vm, structure, regExp);
    }

    if (constructAsRegexp) {
        JSValue pattern = patternArg.get(exec, vm.propertyNames->source);
        RETURN_IF_EXCEPTION(scope, nullptr);
        if (flagsArg.isUndefined()) {
            flagsArg = patternArg.get(exec, vm.propertyNames->flags);
            RETURN_IF_EXCEPTION(scope, nullptr);
        }
        patternArg = pattern;
    }

    scope.release();
    return regExpCreate(exec, globalObject, newTarget, patternArg, flagsArg);
}
Exemplo n.º 18
0
void KRegExpEditorPrivate::slotUpdateLineEdit()
{
  if ( _updating )
    return;
  _updating = true;

  RegExp* regexp = _scrolledEditorWindow->regExp();
  regexp->check( _errorMap );

  TQString str = RegExpConverter::current()->toStr( regexp, false );
  _regexpEdit->setText( str );
  delete regexp;

  recordUndoInfo();

  _updating = false;
}
Exemplo n.º 19
0
void
BUrl::_ExplodeUrlString(const BString& url)
{
	// The regexp is provided in RFC3986 (URI generic syntax), Appendix B
	static RegExp urlMatcher(
		"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");

	_ResetFields();

	RegExp::MatchResult match = urlMatcher.Match(url.String());

	if (!match.HasMatched())
		return; // TODO error reporting

	// Scheme/Protocol
	url.CopyInto(fProtocol, match.GroupStartOffsetAt(1),
		match.GroupEndOffsetAt(1) - match.GroupStartOffsetAt(1));
	if (!_IsProtocolValid()) {
		fHasProtocol = false;
		fProtocol.Truncate(0);
	} else
		fHasProtocol = true;

	// Authority (including user credentials, host, and port
	url.CopyInto(fAuthority, match.GroupStartOffsetAt(3),
		match.GroupEndOffsetAt(3) - match.GroupStartOffsetAt(3));
	SetAuthority(fAuthority);

	// Path
	url.CopyInto(fPath, match.GroupStartOffsetAt(4),
		match.GroupEndOffsetAt(4) - match.GroupStartOffsetAt(4));
	if (!fPath.IsEmpty())
		fHasPath = true;

	// Query
	url.CopyInto(fRequest, match.GroupStartOffsetAt(6),
		match.GroupEndOffsetAt(6) - match.GroupStartOffsetAt(6));
	if (!fRequest.IsEmpty())
		fHasRequest = true;

	// Fragment
	url.CopyInto(fFragment, match.GroupStartOffsetAt(8),
		match.GroupEndOffsetAt(8) - match.GroupStartOffsetAt(8));
	if (!fFragment.IsEmpty())
		fHasFragment = true;
}
Exemplo n.º 20
0
RegExp* WidgetFactory::createRegExp( QDomElement node, const QString& version )
{
  QString tag = node.tagName();
  RegExp* regexp;
  if ( tag == QString::fromLocal8Bit( "TextRange" ) )
    regexp = new TextRangeRegExp( false );
  else if ( tag == QString::fromLocal8Bit( "Text" ) )
    regexp = new TextRegExp( false );
  else if ( tag == QString::fromLocal8Bit( "Concatenation" ) )
    regexp = new ConcRegExp( false );
  else if ( tag == QString::fromLocal8Bit( "Alternatives" ) )
    regexp = new AltnRegExp( false );
  else if ( tag == QString::fromLocal8Bit( "BegLine" ) )
    regexp = new PositionRegExp( false, PositionRegExp::BEGLINE );
  else if ( tag == QString::fromLocal8Bit( "EndLine" ) )
    regexp = new PositionRegExp( false, PositionRegExp::ENDLINE );
  else if ( tag == QString::fromLocal8Bit( "WordBoundary" ) )
    regexp = new PositionRegExp( false, PositionRegExp::WORDBOUNDARY );
  else if ( tag == QString::fromLocal8Bit( "NonWordBoundary" ) )
    regexp = new PositionRegExp( false, PositionRegExp::NONWORDBOUNDARY );
  else if ( tag == QString::fromLocal8Bit( "PositiveLookAhead" ) )
    regexp = new LookAheadRegExp( false, LookAheadRegExp::POSITIVE );
  else if ( tag == QString::fromLocal8Bit( "NegativeLookAhead" ) )
    regexp = new LookAheadRegExp( false, LookAheadRegExp::NEGATIVE );
  else if ( tag == QString::fromLocal8Bit( "Compound" ) )
    regexp = new CompoundRegExp( false );
  else if ( tag == QString::fromLocal8Bit( "AnyChar" ) )
    regexp = new DotRegExp( false );
  else if ( tag == QString::fromLocal8Bit( "Repeat" ) )
    regexp = new RepeatRegExp( false );
  else {
    KMessageBox::sorry( 0, i18n("<p>Unknown tag while reading XML. Tag was <b>%1</b></p>").arg(tag),
                        i18n("Error While Loading From XML File") ) ;

    return 0;
  }

  bool ok = regexp->load( node, version );
  if (ok)
    return regexp;
  else {
    delete regexp;
    return 0;
  }
  return 0;
}
Exemplo n.º 21
0
/*
 * Replace the regexp internals of |obj| with |newRegExp|.
 * Decref the replaced regexp internals.
 * Note that the refcount of |newRegExp| is unchanged.
 */
static void
SwapObjectRegExp(JSContext *cx, JSObject *obj, AlreadyIncRefed<RegExp> newRegExp)
{
    RegExp *oldRegExp = RegExp::extractFrom(obj);
#ifdef DEBUG
    if (oldRegExp)
        assertSameCompartment(cx, obj, oldRegExp->compartment);
    assertSameCompartment(cx, obj, newRegExp->compartment);
#endif

    /*
     * |obj| isn't a new regular expression, so it won't fail due to failing to
     * define the initial set of properties.
     */
    JS_ALWAYS_TRUE(obj->initRegExp(cx, newRegExp.get()));
    if (oldRegExp)
        oldRegExp->decref(cx);
}
Exemplo n.º 22
0
bool TextRegExp::operator==( const RegExp& other ) const {
    if ( other.type() != type() )
        return false;

    const TextRegExp& theOther = dynamic_cast<const TextRegExp&>( other );
    if ( text() == theOther.text() )
        return true;

    return false;
}
Exemplo n.º 23
0
RegExp* RegExpObjectImp::makeEngine(ExecState *exec, const UString &p, const Value &flagsInput)
{
  UString flags = flagsInput.type() == UndefinedType ? UString("") : flagsInput.toString(exec);

  // Check for validity of flags
  for (int pos = 0; pos < flags.size(); ++pos) {
    switch (flags[pos].unicode()) {
    case 'g':
    case 'i':
    case 'm':
      break;
    default: {
        Object err = Error::create(exec, SyntaxError,
                    "Invalid regular expression flags");
        exec->setException(err);
        return 0;
      }
    }
  }

  bool global = (flags.find("g") >= 0);
  bool ignoreCase = (flags.find("i") >= 0);
  bool multiline = (flags.find("m") >= 0);

  int reflags = RegExp::None;
  if (global)
      reflags |= RegExp::Global;
  if (ignoreCase)
      reflags |= RegExp::IgnoreCase;
  if (multiline)
      reflags |= RegExp::Multiline;

  RegExp *re = new RegExp(p, reflags);
  if (!re->isValid()) {
    Object err = Error::create(exec, SyntaxError,
                               "Invalid regular expression");
    exec->setException(err);
    delete re;
    return 0;
  }
  return re;
}
Exemplo n.º 24
0
TQString TQtRegExpConverter::toString( RepeatRegExp* regexp, bool markSelection )
{
    RegExp* child = regexp->child();
    TQString cText = toStr( child, markSelection );
    TQString startPar;
    TQString endPar;

    if ( markSelection ) {
        if ( !regexp->isSelected() && child->isSelected()) {
            startPar = TQString::fromLatin1( "(" );
            endPar = TQString::fromLatin1( ")" );
        }
        else if ( child->precedence() < regexp->precedence() ) {
            startPar = TQString::fromLatin1( "(?:" );
            endPar = TQString::fromLatin1( ")" );
        }
    }
    else if ( child->precedence() < regexp->precedence() ) {
        startPar = TQString::fromLatin1( "(" );
        endPar = TQString::fromLatin1( ")" );
    }

    if ( regexp->min() == 0 && regexp->max() == -1) {
        return startPar + cText +endPar + TQString::fromLocal8Bit("*");
    }
    else if ( regexp->min() == 0 && regexp->max() == 1 ) {
        return startPar + cText + endPar + TQString::fromLocal8Bit("?");
    }
    else if ( regexp->min() == 1 && regexp->max() == -1 ) {
        return startPar + cText + endPar + TQString::fromLocal8Bit("+");
    }
    else if ( regexp->max() == -1 ) {
        return startPar + cText + endPar + TQString::fromLocal8Bit("{") +
            TQString::number( regexp->min() ) + TQString::fromLocal8Bit(",") +
            TQString::fromLocal8Bit("}");
    }
    else {
        return startPar + cText + endPar + TQString::fromLocal8Bit("{") +
            TQString::number( regexp->min() ) + TQString::fromLocal8Bit(",") +
            TQString::number( regexp->max() ) + TQString::fromLocal8Bit("}");
    }
}
Exemplo n.º 25
0
RegExp* RegExp::create(ExecutionEngine* engine, const QString& pattern, bool ignoreCase, bool multiline)
{
    RegExpCacheKey key(pattern, ignoreCase, multiline);

    RegExpCache *cache = engine->regExpCache;
    if (cache) {
        if (RegExp *result = cache->value(key))
            return result;
    }

    RegExp *result = engine->memoryManager->alloc<RegExp>(engine, pattern, ignoreCase, multiline);

    if (!cache)
        cache = engine->regExpCache = new RegExpCache;

    result->d()->cache = cache;
    cache->insert(key, result);

    return result;
}
Exemplo n.º 26
0
static JSObject* regExpCreate(ExecState* exec, JSGlobalObject* globalObject, JSValue newTarget, JSValue patternArg, JSValue flagsArg)
{
    VM& vm = exec->vm();
    String pattern = patternArg.isUndefined() ? emptyString() : patternArg.toString(exec)->value(exec);
    if (exec->hadException())
        return nullptr;

    RegExpFlags flags = toFlags(exec, flagsArg);
    if (flags == InvalidFlags)
        return nullptr;

    RegExp* regExp = RegExp::create(vm, pattern, flags);
    if (!regExp->isValid())
        return vm.throwException(exec, createSyntaxError(exec, regExp->errorMessage()));

    Structure* structure = getRegExpStructure(exec, globalObject, newTarget);
    if (vm.exception())
        return nullptr;
    return RegExpObject::create(vm, structure, regExp);
}
Exemplo n.º 27
0
JSObject * JS_FASTCALL
js_CloneRegExpObject(JSContext *cx, JSObject *obj, JSObject *proto)
{
    JS_ASSERT(obj->getClass() == &js_RegExpClass);
    JS_ASSERT(proto);
    JS_ASSERT(proto->getClass() == &js_RegExpClass);

    JSObject *clone = NewNativeClassInstance(cx, &js_RegExpClass, proto, proto->getParent());
    if (!clone)
        return NULL;

    /*
     * This clone functionality does not duplicate the JITted code blob, which is necessary for
     * cross-compartment cloning functionality.
     */
    assertSameCompartment(cx, obj, clone);

    RegExpStatics *res = cx->regExpStatics();
    RegExp *re = RegExp::extractFrom(obj);
    {
        uint32 origFlags = re->getFlags();
        uint32 staticsFlags = res->getFlags();
        if ((origFlags & staticsFlags) != staticsFlags) {
            /*
             * This regex is lacking flags from the statics, so we must recompile with the new
             * flags instead of increffing.
             */
            AlreadyIncRefed<RegExp> clone = RegExp::create(cx, re->getSource(),
                                                           origFlags | staticsFlags, NULL);
            if (!clone)
                return NULL;
            re = clone.get();
        } else {
            re->incref(cx);
        }
    }
    JS_ASSERT(re);
    if (!clone->initRegExp(cx, re))
        return NULL;
    return clone;
}
Exemplo n.º 28
0
EncodedJSValue JSC_HOST_CALL regExpProtoFuncCompile(ExecState* exec)
{
    JSValue thisValue = exec->hostThisValue();
    if (!thisValue.inherits(&RegExpObject::s_info))
        return throwVMTypeError(exec);

    RegExp* regExp;
    JSValue arg0 = exec->argument(0);
    JSValue arg1 = exec->argument(1);

    if (arg0.isSymbolic() || arg1.isSymbolic()) {
        Statistics::statistics()->accumulate("Concolic::MissingInstrumentation::regExpProtoFuncCompile", 1);
    }
    
    if (arg0.inherits(&RegExpObject::s_info)) {
        if (!arg1.isUndefined())
            return throwVMError(exec, createTypeError(exec, "Cannot supply flags when constructing one RegExp from another."));
        regExp = asRegExpObject(arg0)->regExp();
    } else {
        UString pattern = !exec->argumentCount() ? UString("") : arg0.toString(exec)->value(exec);
        if (exec->hadException())
            return JSValue::encode(jsUndefined());

        RegExpFlags flags = NoFlags;
        if (!arg1.isUndefined()) {
            flags = regExpFlags(arg1.toString(exec)->value(exec));
            if (exec->hadException())
                return JSValue::encode(jsUndefined());
            if (flags == InvalidFlags)
                return throwVMError(exec, createSyntaxError(exec, "Invalid flags supplied to RegExp constructor."));
        }
        regExp = RegExp::create(exec->globalData(), pattern, flags);
    }

    if (!regExp->isValid())
        return throwVMError(exec, createSyntaxError(exec, regExp->errorMessage()));

    asRegExpObject(thisValue)->setRegExp(exec->globalData(), regExp);
    asRegExpObject(thisValue)->setLastIndex(exec, 0);
    return JSValue::encode(jsUndefined());
}
Exemplo n.º 29
0
static JSObject* regExpCreate(ExecState* exec, JSGlobalObject* globalObject, JSValue newTarget, JSValue patternArg, JSValue flagsArg)
{
    VM& vm = exec->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    String pattern = patternArg.isUndefined() ? emptyString() : patternArg.toWTFString(exec);
    RETURN_IF_EXCEPTION(scope, nullptr);

    RegExpFlags flags = toFlags(exec, flagsArg);
    ASSERT(!!scope.exception() == (flags == InvalidFlags));
    if (UNLIKELY(flags == InvalidFlags))
        return nullptr;

    RegExp* regExp = RegExp::create(vm, pattern, flags);
    if (!regExp->isValid())
        return throwException(exec, scope, createSyntaxError(exec, regExp->errorMessage()));

    Structure* structure = getRegExpStructure(exec, globalObject, newTarget);
    RETURN_IF_EXCEPTION(scope, nullptr);
    return RegExpObject::create(vm, structure, regExp);
}
Exemplo n.º 30
0
//RegExpMatch* match(const wstring& base, const RegExp& re)
bool match(RegExpMatch& match, const std::wstring& base, const RegExp& re)
{
	if (!re.isGlobal()) return re.exec(match, base);

	match.index = 0;
	match.input.clear();
	match.substrings.clear();

	RegExpMatch tmp;
	bool ret = re.exec(tmp, base, 0);
	while (ret)
	{
		int advance = (int)tmp.substrings[0].length();
		if (advance < 1) advance = 1;
		int lastPos = tmp.index + advance;
		match.substrings.push_back(std::move(tmp.substrings[0]));
		ret = re.exec(tmp, base, lastPos);
	}

	return true;
}