#include "value.h"
#include "object.h"
#include "types.h"
#include "interpreter.h"
#include "operations.h"
#include "regexp.h"
#include "regexp_object.h"
#include "string_object.h"
#include "error_object.h"
#include <stdio.h>
#include "string_object.lut.h"
using namespace KJS;
const ClassInfo StringInstanceImp::info = {"String", 0, 0, 0};
StringInstanceImp::StringInstanceImp(ObjectImp *proto)
: ObjectImp(proto)
{
setInternalValue(String(""));
}
StringInstanceImp::StringInstanceImp(ObjectImp *proto, const UString &string)
: ObjectImp(proto)
{
setInternalValue(String(string));
}
Value StringInstanceImp::get(ExecState *exec, const Identifier &propertyName) const
{
if (propertyName == lengthPropertyName)
return Number(internalValue().toString(exec).size());
bool ok;
const unsigned index = propertyName.toArrayIndex(&ok);
if (ok) {
const UString s = internalValue().toString(exec);
const unsigned length = s.size();
if (index >= length)
return Undefined();
const UChar c = s[index];
return String(UString(&c, 1));
}
return ObjectImp::get(exec, propertyName);
}
void StringInstanceImp::put(ExecState *exec, const Identifier &propertyName, const Value &value, int attr)
{
if (propertyName == lengthPropertyName)
return;
ObjectImp::put(exec, propertyName, value, attr);
}
bool StringInstanceImp::hasProperty(ExecState *exec, const Identifier &propertyName) const
{
if (propertyName == lengthPropertyName)
return true;
bool ok;
const unsigned index = propertyName.toArrayIndex(&ok);
if (ok) {
const unsigned length = internalValue().toString(exec).size();
if (index < length)
return true;
}
return ObjectImp::hasProperty(exec, propertyName);
}
bool StringInstanceImp::deleteProperty(ExecState *exec, const Identifier &propertyName)
{
if (propertyName == lengthPropertyName)
return false;
return ObjectImp::deleteProperty(exec, propertyName);
}
const ClassInfo StringPrototypeImp::info = {"String", &StringInstanceImp::info, &stringTable, 0};
StringPrototypeImp::StringPrototypeImp(ExecState *exec,
ObjectPrototypeImp *objProto)
: StringInstanceImp(objProto)
{
Value protect(this);
putDirect(lengthPropertyName, NumberImp::zero(), DontDelete|ReadOnly|DontEnum);
}
Value StringPrototypeImp::get(ExecState *exec, const Identifier &propertyName) const
{
return lookupGetFunction<StringProtoFuncImp, StringInstanceImp>( exec, propertyName, &stringTable, this );
}
StringProtoFuncImp::StringProtoFuncImp(ExecState *exec, int i, int len)
: InternalFunctionImp(
static_cast<FunctionPrototypeImp*>(exec->lexicalInterpreter()->builtinFunctionPrototype().imp())
), id(i)
{
Value protect(this);
putDirect(lengthPropertyName, len, DontDelete|ReadOnly|DontEnum);
}
bool StringProtoFuncImp::implementsCall() const
{
return true;
}
static inline bool regExpIsGlobal(RegExpImp *regExp, ExecState *exec)
{
Value globalProperty = regExp->get(exec,"global");
return globalProperty.type() != UndefinedType && globalProperty.toBoolean(exec);
}
static inline void expandSourceRanges(UString::Range * & array, int& count, int& capacity)
{
int newCapacity;
if (capacity == 0) {
newCapacity = 16;
} else {
newCapacity = capacity * 2;
}
UString::Range *newArray = new UString::Range[newCapacity];
for (int i = 0; i < count; i++) {
newArray[i] = array[i];
}
delete [] array;
capacity = newCapacity;
array = newArray;
}
static void pushSourceRange(UString::Range * & array, int& count, int& capacity, UString::Range range)
{
if (count + 1 > capacity)
expandSourceRanges(array, count, capacity);
array[count] = range;
count++;
}
static inline void expandReplacements(UString * & array, int& count, int& capacity)
{
int newCapacity;
if (capacity == 0) {
newCapacity = 16;
} else {
newCapacity = capacity * 2;
}
UString *newArray = new UString[newCapacity];
for (int i = 0; i < count; i++) {
newArray[i] = array[i];
}
delete [] array;
capacity = newCapacity;
array = newArray;
}
static void pushReplacement(UString * & array, int& count, int& capacity, UString replacement)
{
if (count + 1 > capacity)
expandReplacements(array, count, capacity);
array[count] = replacement;
count++;
}
static inline UString substituteBackreferences(const UString &replacement, const UString &source, int **ovector, RegExp *reg)
{
UString substitutedReplacement = replacement;
bool converted;
for (int i = 0; (i = substitutedReplacement.find(UString("$"), i)) != -1; i++) {
if (i+1 < substitutedReplacement.size() && substitutedReplacement[i+1] == '$') { substitutedReplacement = substitutedReplacement.substr(0,i) + "$" + substitutedReplacement.substr(i+2);
continue;
}
unsigned long backrefIndex = substitutedReplacement.substr(i+1,1).toULong(&converted, false );
if (converted && backrefIndex <= (unsigned)reg->subPatterns()) {
int backrefStart = (*ovector)[2*backrefIndex];
int backrefLength = (*ovector)[2*backrefIndex+1] - backrefStart;
substitutedReplacement = substitutedReplacement.substr(0,i)
+ source.substr(backrefStart, backrefLength)
+ substitutedReplacement.substr(i+2);
i += backrefLength - 1; }
}
return substitutedReplacement;
}
static Value replace(ExecState *exec, const UString &source, const Value &pattern, const Value &replacement)
{
if (pattern.type() == ObjectType && pattern.toObject(exec).inherits(&RegExpImp::info)) {
RegExpImp* imp = static_cast<RegExpImp *>( pattern.toObject(exec).imp() );
RegExp *reg = imp->regExp();
bool global = regExpIsGlobal(imp, exec);
RegExpObjectImp* regExpObj = static_cast<RegExpObjectImp*>(exec->lexicalInterpreter()->builtinRegExp().imp());
UString replacementString = replacement.toString(exec);
int matchIndex = 0;
int lastIndex = 0;
int startPosition = 0;
UString::Range *sourceRanges = 0;
int sourceRangeCount = 0;
int sourceRangeCapacity = 0;
UString *replacements = 0;
int replacementCount = 0;
int replacementCapacity = 0;
do {
int **ovector = regExpObj->registerRegexp( reg, source );
UString matchString = reg->match(source, startPosition, &matchIndex, ovector);
regExpObj->setSubPatterns(reg->subPatterns());
if (matchIndex == -1)
break;
int matchLen = matchString.size();
pushSourceRange(sourceRanges, sourceRangeCount, sourceRangeCapacity, UString::Range(lastIndex, matchIndex - lastIndex));
UString substitutedReplacement = substituteBackreferences(replacementString, source, ovector, reg);
pushReplacement(replacements, replacementCount, replacementCapacity, substitutedReplacement);
lastIndex = matchIndex + matchLen;
startPosition = lastIndex;
if (matchLen == 0) {
startPosition++;
if (startPosition > source.size())
break;
}
} while (global);
if (lastIndex < source.size())
pushSourceRange(sourceRanges, sourceRangeCount, sourceRangeCapacity, UString::Range(lastIndex, source.size() - lastIndex));
UString result = source.spliceSubstringsWithSeparators(sourceRanges, sourceRangeCount, replacements, replacementCount);
delete [] sourceRanges;
delete [] replacements;
return String(result);
} else { UString patternString = pattern.toString(exec);
int matchPos = source.find(patternString);
int matchLen = patternString.size();
if (matchPos == -1)
return String(source);
else {
return String(source.substr(0, matchPos) + replacement.toString(exec) + source.substr(matchPos + matchLen));
}
}
}
Value StringProtoFuncImp::call(ExecState *exec, Object &thisObj, const List &args)
{
Value result;
if (id == ToString || id == ValueOf) {
if (thisObj.isNull() || !thisObj.inherits(&StringInstanceImp::info)) {
Object err = Error::create(exec,TypeError);
exec->setException(err);
return err;
}
return String(thisObj.internalValue().toString(exec));
}
UString u, u2, u3;
int pos, p0, i;
double dpos;
double d = 0.0;
UString s = thisObj.toString(exec);
int len = s.size();
Value a0 = args[0];
Value a1 = args[1];
switch (id) {
case ToString:
case ValueOf:
break;
case CharAt:
dpos = a0.isA(UndefinedType) ? 0 : a0.toInteger(exec);
if (dpos >= 0 && dpos < len) u = s.substr(static_cast<int>(dpos), 1);
else
u = "";
result = String(u);
break;
case CharCodeAt:
dpos = a0.isA(UndefinedType) ? 0 : a0.toInteger(exec);
if (dpos >= 0 && dpos < len) d = s[static_cast<int>(dpos)].unicode();
else
d = NaN;
result = Number(d);
break;
case Concat: {
ListIterator it = args.begin();
for ( ; it != args.end() ; ++it) {
s += it->dispatchToString(exec);
}
result = String(s);
break;
}
case IndexOf:
u2 = a0.toString(exec);
if (a1.type() == UndefinedType)
dpos = 0;
else {
dpos = a1.toInteger(exec);
if (dpos >= 0) { if (dpos > len)
dpos = len;
} else
dpos = 0;
}
d = s.find(u2, static_cast<int>(dpos));
result = Number(d);
break;
case LastIndexOf:
u2 = a0.toString(exec);
d = a1.toNumber(exec);
if (a1.type() == UndefinedType || KJS::isNaN(d))
dpos = len;
else {
dpos = a1.toInteger(exec);
if (dpos >= 0) { if (dpos > len)
dpos = len;
} else
dpos = 0;
}
d = s.rfind(u2, static_cast<int>(dpos));
result = Number(d);
break;
case Match:
case Search: {
u = s;
RegExp *reg, *tmpReg = 0;
RegExpImp *imp = 0;
if (a0.isA(ObjectType) && a0.toObject(exec).inherits(&RegExpImp::info))
{
imp = static_cast<RegExpImp *>( a0.toObject(exec).imp() );
reg = imp->regExp();
}
else
{
reg = tmpReg = new RegExp(a0.toString(exec), RegExp::None);
}
RegExpObjectImp* regExpObj = static_cast<RegExpObjectImp*>(exec->lexicalInterpreter()->builtinRegExp().imp());
int **ovector = regExpObj->registerRegexp(reg, u);
UString mstr = reg->match(u, -1, &pos, ovector);
if (id == Search) {
result = Number(pos);
} else {
if ((reg->flags() & RegExp::Global) == 0) {
if (mstr.isNull()) {
result = Null();
} else {
regExpObj->setSubPatterns(reg->subPatterns());
result = regExpObj->arrayOfMatches(exec,mstr);
}
} else {
List list;
int lastIndex = 0;
while (pos >= 0) {
if (mstr.isNull())
list.append(UndefinedImp::staticUndefined);
else
list.append(String(mstr));
lastIndex = pos;
pos += mstr.isEmpty() ? 1 : mstr.size();
delete [] *ovector;
mstr = reg->match(u, pos, &pos, ovector);
}
if (imp)
imp->put(exec, "lastIndex", Number(lastIndex), DontDelete|DontEnum);
if (list.isEmpty()) {
result = Null();
} else {
result = exec->lexicalInterpreter()->builtinArray().construct(exec, list);
}
}
}
delete tmpReg;
break;
}
case Replace:
result = replace(exec, s, a0, a1);
break;
case Slice: {
double begin = args[0].toInteger(exec);
if (begin >= 0) { if (begin > len)
begin = len;
} else {
begin += len;
if (!(begin >= 0)) begin = 0;
}
double end = len;
if (args[1].type() != UndefinedType) {
end = args[1].toInteger(exec);
if (end >= 0) { if (end > len)
end = len;
} else {
end += len;
if (!(end >= 0)) end = 0;
}
}
result = String(s.substr(static_cast<int>(begin), static_cast<int>(end-begin)));
break;
}
case Split: {
Object constructor = exec->lexicalInterpreter()->builtinArray();
Object res = Object::dynamicCast(constructor.construct(exec,List::empty()));
result = res;
u = s;
i = p0 = 0;
uint32_t limit = a1.type() == UndefinedType ? 0xFFFFFFFFU : a1.toUInt32(exec);
if (a0.type() == ObjectType && Object::dynamicCast(a0).inherits(&RegExpImp::info)) {
Object obj0 = Object::dynamicCast(a0);
RegExp reg(obj0.get(exec,"source").toString(exec));
if (u.isEmpty() && !reg.match(u, 0).isNull()) {
res.put(exec,lengthPropertyName, Number(0));
break;
}
pos = 0;
while (static_cast<uint32_t>(i) != limit && pos < u.size()) {
int mpos;
int *ovector = 0L;
UString mstr = reg.match(u, pos, &mpos, &ovector);
delete [] ovector; ovector = 0L;
if (mpos < 0)
break;
pos = mpos + (mstr.isEmpty() ? 1 : mstr.size());
if (mpos != p0 || !mstr.isEmpty()) {
res.put(exec,i, String(u.substr(p0, mpos-p0)));
p0 = mpos + mstr.size();
i++;
}
}
} else {
u2 = a0.toString(exec);
if (u2.isEmpty()) {
if (u.isEmpty()) {
put(exec,lengthPropertyName, Number(0));
break;
} else {
while (static_cast<uint32_t>(i) != limit && i < u.size()-1)
res.put(exec, i++, String(u.substr(p0++, 1)));
}
} else {
while (static_cast<uint32_t>(i) != limit && (pos = u.find(u2, p0)) >= 0) {
res.put(exec, i, String(u.substr(p0, pos-p0)));
p0 = pos + u2.size();
i++;
}
}
}
if (static_cast<uint32_t>(i) != limit)
res.put(exec, i++, String(u.substr(p0)));
res.put(exec,lengthPropertyName, Number(i));
}
break;
case Substr: {
double d = a0.toInteger(exec);
double d2 = a1.toInteger(exec);
if (!(d >= 0)) { d += len;
if (!(d >= 0)) d = 0;
}
if (isNaN(d2))
d2 = len - d;
else {
if (d2 < 0)
d2 = 0;
if (d2 > len - d)
d2 = len - d;
}
result = String(s.substr(static_cast<int>(d), static_cast<int>(d2)));
break;
}
case Substring: {
double start = a0.toNumber(exec);
double end = a1.toNumber(exec);
if (KJS::isNaN(start))
start = 0;
if (KJS::isNaN(end))
end = 0;
if (start < 0)
start = 0;
if (end < 0)
end = 0;
if (start > len)
start = len;
if (end > len)
end = len;
if (a1.type() == UndefinedType)
end = len;
if (start > end) {
double temp = end;
end = start;
start = temp;
}
result = String(s.substr((int)start, (int)end-(int)start));
}
break;
case ToLowerCase:
case ToLocaleLowerCase: u = s;
for (i = 0; i < len; i++)
u[i] = u[i].toLower();
result = String(u);
break;
case ToUpperCase:
case ToLocaleUpperCase: u = s;
for (i = 0; i < len; i++)
u[i] = u[i].toUpper();
result = String(u);
break;
#ifndef KJS_PURE_ECMA
case Big:
result = String("<big>" + s + "</big>");
break;
case Small:
result = String("<small>" + s + "</small>");
break;
case Blink:
result = String("<blink>" + s + "</blink>");
break;
case Bold:
result = String("<b>" + s + "</b>");
break;
case Fixed:
result = String("<tt>" + s + "</tt>");
break;
case Italics:
result = String("<i>" + s + "</i>");
break;
case Strike:
result = String("<strike>" + s + "</strike>");
break;
case Sub:
result = String("<sub>" + s + "</sub>");
break;
case Sup:
result = String("<sup>" + s + "</sup>");
break;
case Fontcolor:
result = String("<font color=\"" + a0.toString(exec) + "\">" + s + "</font>");
break;
case Fontsize:
result = String("<font size=\"" + a0.toString(exec) + "\">" + s + "</font>");
break;
case Anchor:
result = String("<a name=\"" + a0.toString(exec) + "\">" + s + "</a>");
break;
case Link:
result = String("<a href=\"" + a0.toString(exec) + "\">" + s + "</a>");
break;
#endif
}
return result;
}
StringObjectImp::StringObjectImp(ExecState *exec,
FunctionPrototypeImp *funcProto,
StringPrototypeImp *stringProto)
: InternalFunctionImp(funcProto)
{
Value protect(this);
putDirect(prototypePropertyName, stringProto, DontEnum|DontDelete|ReadOnly);
static Identifier fromCharCode("fromCharCode");
putDirect(fromCharCode, new StringObjectFuncImp(exec,funcProto), DontEnum);
putDirect(lengthPropertyName, NumberImp::one(), ReadOnly|DontDelete|DontEnum);
}
bool StringObjectImp::implementsConstruct() const
{
return true;
}
Object StringObjectImp::construct(ExecState *exec, const List &args)
{
ObjectImp *proto = exec->lexicalInterpreter()->builtinStringPrototype().imp();
if (args.size() == 0)
return Object(new StringInstanceImp(proto));
return Object(new StringInstanceImp(proto, args.begin()->dispatchToString(exec)));
}
bool StringObjectImp::implementsCall() const
{
return true;
}
Value StringObjectImp::call(ExecState *exec, Object &, const List &args)
{
if (args.isEmpty())
return String("");
else {
Value v = args[0];
return String(v.toString(exec));
}
}
StringObjectFuncImp::StringObjectFuncImp(ExecState *exec, FunctionPrototypeImp *funcProto)
: InternalFunctionImp(funcProto)
{
Value protect(this);
putDirect(lengthPropertyName, NumberImp::one(), DontDelete|ReadOnly|DontEnum);
}
bool StringObjectFuncImp::implementsCall() const
{
return true;
}
Value StringObjectFuncImp::call(ExecState *exec, Object &, const List &args)
{
UString s;
if (args.size()) {
UChar *buf = new UChar[args.size()];
UChar *p = buf;
ListIterator it = args.begin();
while (it != args.end()) {
unsigned short u = it->toUInt16(exec);
*p++ = UChar(u);
it++;
}
s = UString(buf, args.size(), false);
} else
s = "";
return String(s);
}