regexp_object.cpp
// -*- c-basic-offset: 2 -*-
/*
* This file is part of the KDE libraries
* Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
* Copyright (C) 2003 Apple Computer, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <stdio.h>
#include "value.h"
#include "object.h"
#include "types.h"
#include "interpreter.h"
#include "operations.h"
#include "internal.h"
#include "regexp.h"
#include "regexp_object.h"
#include "error_object.h"
#include "lookup.h"
using namespace KJS;
// ------------------------------ RegExpPrototypeImp ---------------------------
// ECMA 15.9.4
const ClassInfo RegExpPrototypeImp::info = {"RegExp", 0, 0, 0};
RegExpPrototypeImp::RegExpPrototypeImp(ExecState *exec,
ObjectPrototypeImp *objProto,
FunctionPrototypeImp *funcProto)
: ObjectImp(objProto)
{
Value protect(this);
setInternalValue(String(""));
// The constructor will be added later in RegExpObject's constructor (?)
static const Identifier execPropertyName("exec");
putDirect(execPropertyName,
new RegExpProtoFuncImp(exec,funcProto,RegExpProtoFuncImp::Exec, 0, execPropertyName), DontEnum);
static const Identifier testPropertyName("test");
putDirect(testPropertyName,
new RegExpProtoFuncImp(exec,funcProto,RegExpProtoFuncImp::Test, 0, testPropertyName), DontEnum);
putDirect(toStringPropertyName,
new RegExpProtoFuncImp(exec,funcProto,RegExpProtoFuncImp::ToString, 0, toStringPropertyName), DontEnum);
static const Identifier compilePropertyName("compile");
putDirect(compilePropertyName,
new RegExpProtoFuncImp(exec,funcProto,RegExpProtoFuncImp::Compile, 1, compilePropertyName), DontEnum);
}
// ------------------------------ RegExpProtoFuncImp ---------------------------
RegExpProtoFuncImp::RegExpProtoFuncImp(ExecState * /*exec*/, FunctionPrototypeImp *funcProto,
int i, int len, const Identifier &_ident)
: InternalFunctionImp(funcProto), id(i)
{
Value protect(this);
putDirect(lengthPropertyName, len, DontDelete|ReadOnly|DontEnum);
ident = _ident;
}
bool RegExpProtoFuncImp::implementsCall() const
{
return true;
}
Value RegExpProtoFuncImp::call(ExecState *exec, Object &thisObj, const List &args)
{
if (!thisObj.inherits(&RegExpImp::info)) {
if (thisObj.inherits(&RegExpPrototypeImp::info)) {
switch (id) {
case ToString: return String("//"); // FireFox returns /(?:)/
}
}
Object err = Error::create(exec,TypeError);
exec->setException(err);
return err;
}
RegExpImp *reimp = static_cast<RegExpImp*>(thisObj.imp());
RegExp *re = reimp->regExp();
String s;
UString str;
switch (id) {
case Exec: // 15.10.6.2
case Test:
{
s = args[0].toString(exec);
int length = s.value().size();
// Get values from the last time (in case of /g)
Value lastIndex = thisObj.get(exec,"lastIndex");
int i = lastIndex.isValid() ? lastIndex.toInt32(exec) : 0;
bool globalFlag = thisObj.get(exec,"global").toBoolean(exec);
if (!globalFlag)
i = 0;
if (i < 0 || i > length) {
thisObj.put(exec,"lastIndex", Number(0), DontDelete | DontEnum);
if (id == Test)
return Boolean(false);
else
return Null();
}
RegExpObjectImp* regExpObj = static_cast<RegExpObjectImp*>(exec->lexicalInterpreter()->builtinRegExp().imp());
int **ovector = regExpObj->registerRegexp( re, s.value() );
re->prepareMatch(s.value());
str = re->match(s.value(), i, 0L, ovector);
re->doneMatch();
regExpObj->setSubPatterns(re->subPatterns());
if (id == Test)
return Boolean(!str.isNull());
if (str.isNull()) // no match
{
if (globalFlag)
thisObj.put(exec,"lastIndex",Number(0), DontDelete | DontEnum);
return Null();
}
else // success
{
if (globalFlag)
thisObj.put(exec,"lastIndex",Number( (*ovector)[1] ), DontDelete | DontEnum);
return regExpObj->arrayOfMatches(exec,str);
}
}
break;
case ToString:
s = thisObj.get(exec,"source").toString(exec);
str = "/";
str += s.value();
str += "/";
if (thisObj.get(exec,"global").toBoolean(exec)) {
str += "g";
}
if (thisObj.get(exec,"ignoreCase").toBoolean(exec)) {
str += "i";
}
if (thisObj.get(exec,"multiline").toBoolean(exec)) {
str += "m";
}
return String(str);
case Compile: {
RegExp* newEngine = RegExpObjectImp::makeEngine(exec, args[0].toString(exec), args[1]);
if (!newEngine)
return exec->exception();
reimp->setRegExp(newEngine);
return Value(reimp);
}
}
return Undefined();
}
// ------------------------------ RegExpImp ------------------------------------
const ClassInfo RegExpImp::info = {"RegExp", 0, 0, 0};
RegExpImp::RegExpImp(RegExpPrototypeImp *regexpProto)
: ObjectImp(regexpProto), reg(0L)
{
}
RegExpImp::~RegExpImp()
{
delete reg;
}
void RegExpImp::setRegExp(RegExp *r)
{
delete reg;
reg = r;
Object protect(this);//Protect self from GC (we are allocating a StringImp, and may be new)
putDirect("global", (r->flags() & RegExp::Global) ? BooleanImp::staticTrue : BooleanImp::staticFalse,
DontDelete | ReadOnly | DontEnum);
putDirect("ignoreCase", (r->flags() & RegExp::IgnoreCase) ? BooleanImp::staticTrue : BooleanImp::staticFalse,
DontDelete | ReadOnly | DontEnum);
putDirect("multiline", (r->flags() & RegExp::Multiline) ? BooleanImp::staticTrue : BooleanImp::staticFalse,
DontDelete | ReadOnly | DontEnum);
putDirect("source", new StringImp(r->pattern()), DontDelete | ReadOnly | DontEnum);
putDirect("lastIndex", NumberImp::zero(), DontDelete | DontEnum);
}
// ------------------------------ RegExpObjectImp ------------------------------
RegExpObjectImp::RegExpObjectImp(ExecState * /*exec*/,
FunctionPrototypeImp *funcProto,
RegExpPrototypeImp *regProto)
: InternalFunctionImp(funcProto), lastOvector(0L), lastNrSubPatterns(0)
{
Value protect(this);
// ECMA 15.10.5.1 RegExp.prototype
putDirect(prototypePropertyName, regProto, DontEnum|DontDelete|ReadOnly);
// no. of arguments for constructor
putDirect(lengthPropertyName, NumberImp::two(), ReadOnly|DontDelete|DontEnum);
}
RegExpObjectImp::~RegExpObjectImp()
{
delete [] lastOvector;
}
int **RegExpObjectImp::registerRegexp( const RegExp* re, const UString& s )
{
lastString = s;
delete [] lastOvector;
lastOvector = 0;
lastNrSubPatterns = re->subPatterns();
return &lastOvector;
}
Object RegExpObjectImp::arrayOfMatches(ExecState *exec, const UString &result) const
{
List list;
// The returned array contains 'result' as first item, followed by the list of matches
list.append(String(result));
if ( lastOvector )
for ( unsigned int i = 1 ; i < lastNrSubPatterns + 1 ; ++i )
{
UString substring = lastString.substr( lastOvector[2*i], lastOvector[2*i+1] - lastOvector[2*i] );
list.append(String(substring));
}
Object arr = exec->lexicalInterpreter()->builtinArray().construct(exec, list);
arr.put(exec, "index", Number(lastOvector[0]));
arr.put(exec, "input", String(lastString));
return arr;
}
Value RegExpObjectImp::get(ExecState *exec, const Identifier &p) const
{
UString s = p.ustring();
if (s[0] == '$' && lastOvector)
{
bool ok;
unsigned long i = s.substr(1).toULong(&ok);
if (ok)
{
if (i < lastNrSubPatterns + 1)
{
UString substring = lastString.substr( lastOvector[2*i], lastOvector[2*i+1] - lastOvector[2*i] );
return String(substring);
}
return String("");
}
}
return InternalFunctionImp::get(exec, p);
}
bool RegExpObjectImp::hasProperty(ExecState *exec, const Identifier &p) const
{
UString s = p.ustring();
if (s[0] == '$' && lastOvector) {
bool ok;
(void)s.substr(1).toULong(&ok);
if (ok)
return true;
}
return InternalFunctionImp::hasProperty(exec, p);
}
bool RegExpObjectImp::implementsConstruct() const
{
return true;
}
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;
}
// ECMA 15.10.4
Object RegExpObjectImp::construct(ExecState *exec, const List &args)
{
UString p;
if (args.isEmpty()) {
p = "";
} else {
Value a0 = args[0];
if (a0.isA(ObjectType) && a0.toObject(exec).inherits(&RegExpImp::info)) {
// It's a regexp. Check that no flags were passed.
if (args.size() > 1 && args[1].type() != UndefinedType) {
Object err = Error::create(exec,TypeError);
exec->setException(err);
return err;
}
RegExpImp *rimp = static_cast<RegExpImp*>(Object::dynamicCast(a0).imp());
p = rimp->regExp()->pattern();
} else {
p = a0.toString(exec);
}
}
RegExp* re = makeEngine(exec, p, args[1]);
if (!re)
return exec->exception().toObject(exec);
RegExpPrototypeImp *proto = static_cast<RegExpPrototypeImp*>(exec->lexicalInterpreter()->builtinRegExpPrototype().imp());
RegExpImp *dat = new RegExpImp(proto);
Object obj(dat); // protect from GC
dat->setRegExp(re);
return obj;
}
bool RegExpObjectImp::implementsCall() const
{
return true;
}
// ECMA 15.10.3
Value RegExpObjectImp::call(ExecState *exec, Object &/*thisObj*/,
const List &args)
{
// TODO: handle RegExp argument case (15.10.3.1)
return construct(exec, args);
}
KJS::Value
Value objects are act as wrappers ("smart pointers") around ValueImp objects and their descendents...
Definition: value.h:168
KJS::UString::substr
UString substr(int pos=0, int len=-1) const
Definition: ustring.cpp:869
KJS::Value::type
Type type() const
Returns the type of value.
Definition: value.h:196
KJS::InternalFunctionImp
Base class for all function objects.
Definition: function.h:41
KJS::Object::get
Value get(ExecState *exec, const Identifier &propertyName) const
Retrieves the specified property from the object.
Definition: object.h:664
KJS::UString::size
int size() const
Definition: ustring.h:359
KJS::Object::construct
Object construct(ExecState *exec, const List &args)
Creates a new object based on this object.
Definition: object.h:697
KJS::Number
Represents an primitive Number value.
Definition: value.h:368
KJS::List::append
void append(const Value &val)
Append an object to the end of the list.
Definition: list.h:66
KJS::Value::toBoolean
bool toBoolean(ExecState *exec) const
Performs the ToBoolean type conversion operation on this value (ECMA 9.2)
Definition: value.h:217
KJS::UString::find
int find(const UString &f, int pos=0) const
Definition: ustring.cpp:799
KJS::Null
Represents an primitive Null value.
Definition: value.h:295
KJS::ExecState::lexicalInterpreter
Interpreter * lexicalInterpreter() const
Returns the interpreter associated with the current scope's global object.
Definition: interpreter.cpp:395
KJS::Interpreter::builtinRegExpPrototype
Object builtinRegExpPrototype() const
Returns the builtin "RegExp.prototype" object.
Definition: interpreter.cpp:254
KJS::Error::create
static Object create(ExecState *exec, ErrorType errtype=GeneralError, const char *message=0, int lineno=-1, int sourceId=-1)
Factory method for error objects.
Definition: object.cpp:504
KJS::FunctionPrototypeImp
The initial value of Function.prototype (and thus all objects created with the Function constructor) ...
Definition: function_object.h:35
KJS::Value::toInt32
int toInt32(ExecState *exec) const
Performs the ToInt32 type conversion operation on this value (ECMA 9.5)
Definition: value.h:232
KJS::Object
Represents an Object.
Definition: object.h:82
KJS::Undefined
Represents an primitive Undefined value.
Definition: value.h:270
KJS::Value::toObject
Object toObject(ExecState *exec) const
Performs the ToObject type conversion operation on this value (ECMA 9.9)
Definition: object.h:359
KJS::Value::isA
bool isA(Type t) const
Checks whether or not the value is of a particular tpye.
Definition: value.h:204
KJS::UString
Unicode string class.
Definition: ustring.h:189
KJS::String
Represents an primitive String value.
Definition: value.h:341
KJS::Object::dynamicCast
static Object dynamicCast(const Value &v)
Converts a Value into an Object.
Definition: object.cpp:46
KJS::UString::isNull
bool isNull() const
Definition: ustring.h:343
KJS::Identifier::ustring
const UString & ustring() const
returns a UString of the identifier
Definition: identifier.h:52
KJS::List::size
int size() const
Definition: list.h:90
KJS::Object::put
void put(ExecState *exec, const Identifier &propertyName, const Value &value, int attr=None)
Sets the specified property.
Definition: object.h:670
KJS::List
Native list type.
Definition: list.h:48
KJS::Boolean
Represents an primitive Boolean value.
Definition: value.h:317
KJS::Value::toString
UString toString(ExecState *exec) const
Performs the ToString type conversion operation on this value (ECMA 9.8)
Definition: value.h:247
KJS::ClassInfo
Class Information.
Definition: object.h:59
KJS::Interpreter::builtinArray
Object builtinArray() const
Returns the builtin "Array" object.
Definition: interpreter.cpp:184
KJS::List::isEmpty
bool isEmpty() const
Definition: list.h:86
KJS::Value::isValid
bool isValid() const
Returns whether or not this is a valid value.
Definition: value.h:182
KJS::Interpreter::builtinRegExp
Object builtinRegExp() const
Returns the builtin "RegExp" object.
Definition: interpreter.cpp:209
KJS::UString::toULong
unsigned long toULong(bool *ok, bool tolerateEmptyString) const
Attempts an conversion to an unsigned long integer.
Definition: ustring.cpp:686
KJS::ExecState
Represents the current state of script execution.
Definition: interpreter.h:439
KJS::Identifier
Represents an Identifier for a Javascript object.
Definition: identifier.h:32

KDE Home | KDE Accessibility Home | Description of Access Keys