source: webkit/trunk/JavaScriptCore/kjs/function.cpp@ 26808

Last change on this file since 26808 was 26808, checked in by ggaren, 18 years ago

Reviewed by Darin Adler.


To improve encapsulation, moved processDeclarations call into
FunctionBodyNode::execute. Also marked processDeclarations
ALWAYS_INLINE, since it has only 1 caller now. This is a .71% speedup
on command-line JS iBench.

  • kjs/function.cpp: (KJS::FunctionImp::callAsFunction): (KJS::GlobalFuncImp::callAsFunction):
  • kjs/function.h:
  • kjs/interpreter.cpp: (KJS::Interpreter::evaluate):
  • kjs/nodes.cpp: (FunctionBodyNode::execute):
  • kjs/nodes.h:
  • Property svn:eol-style set to native
File size: 26.6 KB
Line 
1// -*- c-basic-offset: 2 -*-
2/*
3 * Copyright (C) 1999-2002 Harri Porten ([email protected])
4 * Copyright (C) 2001 Peter Kelly ([email protected])
5 * Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
6 * Copyright (C) 2007 Cameron Zwarich ([email protected])
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
17 *
18 * You should have received a copy of the GNU Library General Public License
19 * along with this library; see the file COPYING.LIB. If not, write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
22 *
23 */
24
25#include "config.h"
26#include "function.h"
27
28#include "context.h"
29#include "debugger.h"
30#include "dtoa.h"
31#include "function_object.h"
32#include "internal.h"
33#include "lexer.h"
34#include "nodes.h"
35#include "operations.h"
36#include <errno.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <wtf/ASCIICType.h>
41#include <wtf/Assertions.h>
42#include <wtf/unicode/Unicode.h>
43
44using namespace WTF;
45using namespace Unicode;
46
47namespace KJS {
48
49// ----------------------------- FunctionImp ----------------------------------
50
51const ClassInfo FunctionImp::info = { "Function", &InternalFunctionImp::info, 0, 0 };
52
53FunctionImp::FunctionImp(ExecState* exec, const Identifier& name, FunctionBodyNode* b, const ScopeChain& sc)
54 : InternalFunctionImp(static_cast<FunctionPrototype*>(exec->lexicalInterpreter()->builtinFunctionPrototype()), name)
55 , body(b)
56 , _scope(sc)
57{
58}
59
60void FunctionImp::mark()
61{
62 InternalFunctionImp::mark();
63 _scope.mark();
64}
65
66JSValue* FunctionImp::callAsFunction(ExecState* exec, JSObject* thisObj, const List& args)
67{
68 JSObject* globalObj = exec->dynamicInterpreter()->globalObject();
69
70 // enter a new execution context
71 Context ctx(globalObj, exec->dynamicInterpreter(), thisObj, body.get(),
72 FunctionCode, exec->context(), this, &args);
73 ExecState newExec(exec->dynamicInterpreter(), &ctx);
74 if (exec->hadException())
75 newExec.setException(exec->exception());
76 ctx.setExecState(&newExec);
77
78 passInParameters(&newExec, args);
79
80 Debugger* dbg = exec->dynamicInterpreter()->debugger();
81 int sid = -1;
82 int lineno = -1;
83 if (dbg) {
84 sid = body->sourceId();
85 lineno = body->firstLine();
86
87 bool cont = dbg->callEvent(&newExec,sid,lineno,this,args);
88 if (!cont) {
89 dbg->imp()->abort();
90 return jsUndefined();
91 }
92 }
93
94 Completion comp = execute(&newExec);
95
96 // if an exception occured, propogate it back to the previous execution object
97 if (newExec.hadException())
98 comp = Completion(Throw, newExec.exception());
99
100 // The debugger may have been deallocated by now if the WebFrame
101 // we were running in has been destroyed, so refetch it.
102 // See http://bugs.webkit.org/show_bug.cgi?id=9477
103 dbg = exec->dynamicInterpreter()->debugger();
104
105 if (dbg) {
106 lineno = body->lastLine();
107
108 if (comp.complType() == Throw)
109 newExec.setException(comp.value());
110
111 int cont = dbg->returnEvent(&newExec,sid,lineno,this);
112 if (!cont) {
113 dbg->imp()->abort();
114 return jsUndefined();
115 }
116 }
117
118 if (comp.complType() == Throw) {
119 exec->setException(comp.value());
120 return comp.value();
121 }
122 else if (comp.complType() == ReturnValue)
123 return comp.value();
124 else
125 return jsUndefined();
126}
127
128// ECMA 10.1.3q
129inline void FunctionImp::passInParameters(ExecState* exec, const List& args)
130{
131 Vector<Identifier>& parameters = body->parameters();
132
133 JSObject* variable = exec->context()->variableObject();
134
135 size_t size = parameters.size();
136 for (size_t i = 0; i < size; ++i) {
137 variable->put(exec, parameters[i], args[i], DontDelete);
138 }
139}
140
141JSValue* FunctionImp::argumentsGetter(ExecState* exec, JSObject*, const Identifier& propertyName, const PropertySlot& slot)
142{
143 FunctionImp* thisObj = static_cast<FunctionImp*>(slot.slotBase());
144 Context* context = exec->m_context;
145 while (context) {
146 if (context->function() == thisObj)
147 return static_cast<ActivationImp*>(context->activationObject())->get(exec, propertyName);
148 context = context->callingContext();
149 }
150 return jsNull();
151}
152
153JSValue* FunctionImp::callerGetter(ExecState* exec, JSObject*, const Identifier&, const PropertySlot& slot)
154{
155 FunctionImp* thisObj = static_cast<FunctionImp*>(slot.slotBase());
156 Context* context = exec->m_context;
157 while (context) {
158 if (context->function() == thisObj)
159 break;
160 context = context->callingContext();
161 }
162
163 if (!context)
164 return jsNull();
165
166 Context* callingContext = context->callingContext();
167 if (!callingContext)
168 return jsNull();
169
170 FunctionImp* callingFunction = callingContext->function();
171 if (!callingFunction)
172 return jsNull();
173
174 return callingFunction;
175}
176
177JSValue* FunctionImp::lengthGetter(ExecState*, JSObject*, const Identifier&, const PropertySlot& slot)
178{
179 FunctionImp* thisObj = static_cast<FunctionImp*>(slot.slotBase());
180 return jsNumber(thisObj->body->numParams());
181}
182
183bool FunctionImp::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
184{
185 // Find the arguments from the closest context.
186 if (propertyName == exec->propertyNames().arguments) {
187 slot.setCustom(this, argumentsGetter);
188 return true;
189 }
190
191 // Compute length of parameters.
192 if (propertyName == exec->propertyNames().length) {
193 slot.setCustom(this, lengthGetter);
194 return true;
195 }
196
197 if (propertyName == exec->propertyNames().caller) {
198 slot.setCustom(this, callerGetter);
199 return true;
200 }
201
202 return InternalFunctionImp::getOwnPropertySlot(exec, propertyName, slot);
203}
204
205void FunctionImp::put(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr)
206{
207 if (propertyName == exec->propertyNames().arguments || propertyName == exec->propertyNames().length)
208 return;
209 InternalFunctionImp::put(exec, propertyName, value, attr);
210}
211
212bool FunctionImp::deleteProperty(ExecState* exec, const Identifier& propertyName)
213{
214 if (propertyName == exec->propertyNames().arguments || propertyName == exec->propertyNames().length)
215 return false;
216 return InternalFunctionImp::deleteProperty(exec, propertyName);
217}
218
219/* Returns the parameter name corresponding to the given index. eg:
220 * function f1(x, y, z): getParameterName(0) --> x
221 *
222 * If a name appears more than once, only the last index at which
223 * it appears associates with it. eg:
224 * function f2(x, x): getParameterName(0) --> null
225 */
226Identifier FunctionImp::getParameterName(int index)
227{
228 Vector<Identifier>& parameters = body->parameters();
229
230 if (static_cast<size_t>(index) >= body->numParams())
231 return CommonIdentifiers::shared()->nullIdentifier;
232
233 Identifier name = parameters[index];
234
235 // Are there any subsequent parameters with the same name?
236 size_t size = parameters.size();
237 for (size_t i = index + 1; i < size; ++i)
238 if (parameters[i] == name)
239 return CommonIdentifiers::shared()->nullIdentifier;
240
241 return name;
242}
243
244// ECMA 13.2.2 [[Construct]]
245JSObject* FunctionImp::construct(ExecState* exec, const List& args)
246{
247 JSObject* proto;
248 JSValue* p = get(exec, exec->propertyNames().prototype);
249 if (p->isObject())
250 proto = static_cast<JSObject*>(p);
251 else
252 proto = exec->lexicalInterpreter()->builtinObjectPrototype();
253
254 JSObject* obj(new JSObject(proto));
255
256 JSValue* res = call(exec,obj,args);
257
258 if (res->isObject())
259 return static_cast<JSObject*>(res);
260 else
261 return obj;
262}
263
264Completion FunctionImp::execute(ExecState* exec)
265{
266 Completion result = body->execute(exec);
267
268 if (result.complType() == Throw || result.complType() == ReturnValue)
269 return result;
270 return Completion(Normal, jsUndefined()); // TODO: or ReturnValue ?
271}
272
273// ------------------------------ IndexToNameMap ---------------------------------
274
275// We map indexes in the arguments array to their corresponding argument names.
276// Example: function f(x, y, z): arguments[0] = x, so we map 0 to Identifier("x").
277
278// Once we have an argument name, we can get and set the argument's value in the
279// activation object.
280
281// We use Identifier::null to indicate that a given argument's value
282// isn't stored in the activation object.
283
284IndexToNameMap::IndexToNameMap(FunctionImp* func, const List& args)
285{
286 _map = new Identifier[args.size()];
287 this->size = args.size();
288
289 int i = 0;
290 ListIterator iterator = args.begin();
291 for (; iterator != args.end(); i++, iterator++)
292 _map[i] = func->getParameterName(i); // null if there is no corresponding parameter
293}
294
295IndexToNameMap::~IndexToNameMap() {
296 delete [] _map;
297}
298
299bool IndexToNameMap::isMapped(const Identifier& index) const
300{
301 bool indexIsNumber;
302 int indexAsNumber = index.toUInt32(&indexIsNumber);
303
304 if (!indexIsNumber)
305 return false;
306
307 if (indexAsNumber >= size)
308 return false;
309
310 if (_map[indexAsNumber].isNull())
311 return false;
312
313 return true;
314}
315
316void IndexToNameMap::unMap(const Identifier& index)
317{
318 bool indexIsNumber;
319 int indexAsNumber = index.toUInt32(&indexIsNumber);
320
321 ASSERT(indexIsNumber && indexAsNumber < size);
322
323 _map[indexAsNumber] = CommonIdentifiers::shared()->nullIdentifier;
324}
325
326Identifier& IndexToNameMap::operator[](int index)
327{
328 return _map[index];
329}
330
331Identifier& IndexToNameMap::operator[](const Identifier& index)
332{
333 bool indexIsNumber;
334 int indexAsNumber = index.toUInt32(&indexIsNumber);
335
336 ASSERT(indexIsNumber && indexAsNumber < size);
337
338 return (*this)[indexAsNumber];
339}
340
341// ------------------------------ Arguments ---------------------------------
342
343const ClassInfo Arguments::info = {"Arguments", 0, 0, 0};
344
345// ECMA 10.1.8
346Arguments::Arguments(ExecState* exec, FunctionImp* func, const List& args, ActivationImp* act)
347: JSObject(exec->lexicalInterpreter()->builtinObjectPrototype()),
348_activationObject(act),
349indexToNameMap(func, args)
350{
351 putDirect(exec->propertyNames().callee, func, DontEnum);
352 putDirect(exec->propertyNames().length, args.size(), DontEnum);
353
354 int i = 0;
355 ListIterator iterator = args.begin();
356 for (; iterator != args.end(); i++, iterator++) {
357 if (!indexToNameMap.isMapped(Identifier::from(i))) {
358 JSObject::put(exec, Identifier::from(i), *iterator, DontEnum);
359 }
360 }
361}
362
363void Arguments::mark()
364{
365 JSObject::mark();
366 if (_activationObject && !_activationObject->marked())
367 _activationObject->mark();
368}
369
370JSValue* Arguments::mappedIndexGetter(ExecState* exec, JSObject*, const Identifier& propertyName, const PropertySlot& slot)
371{
372 Arguments* thisObj = static_cast<Arguments*>(slot.slotBase());
373 return thisObj->_activationObject->get(exec, thisObj->indexToNameMap[propertyName]);
374}
375
376bool Arguments::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
377{
378 if (indexToNameMap.isMapped(propertyName)) {
379 slot.setCustom(this, mappedIndexGetter);
380 return true;
381 }
382
383 return JSObject::getOwnPropertySlot(exec, propertyName, slot);
384}
385
386void Arguments::put(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr)
387{
388 if (indexToNameMap.isMapped(propertyName)) {
389 _activationObject->put(exec, indexToNameMap[propertyName], value, attr);
390 } else {
391 JSObject::put(exec, propertyName, value, attr);
392 }
393}
394
395bool Arguments::deleteProperty(ExecState* exec, const Identifier& propertyName)
396{
397 if (indexToNameMap.isMapped(propertyName)) {
398 indexToNameMap.unMap(propertyName);
399 return true;
400 } else {
401 return JSObject::deleteProperty(exec, propertyName);
402 }
403}
404
405// ------------------------------ ActivationImp --------------------------------
406
407const ClassInfo ActivationImp::info = {"Activation", 0, 0, 0};
408
409// ECMA 10.1.6
410ActivationImp::ActivationImp(FunctionImp* function, const List& arguments)
411 : _function(function), _arguments(arguments), _argumentsObject(0)
412{
413 // FIXME: Do we need to support enumerating the arguments property?
414}
415
416JSValue* ActivationImp::argumentsGetter(ExecState* exec, JSObject*, const Identifier&, const PropertySlot& slot)
417{
418 ActivationImp* thisObj = static_cast<ActivationImp*>(slot.slotBase());
419
420 // default: return builtin arguments array
421 if (!thisObj->_argumentsObject)
422 thisObj->createArgumentsObject(exec);
423
424 return thisObj->_argumentsObject;
425}
426
427PropertySlot::GetValueFunc ActivationImp::getArgumentsGetter()
428{
429 return ActivationImp::argumentsGetter;
430}
431
432bool ActivationImp::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
433{
434 // do this first so property map arguments property wins over the below
435 // we don't call JSObject because we won't have getter/setter properties
436 // and we don't want to support __proto__
437
438 if (JSValue** location = getDirectLocation(propertyName)) {
439 slot.setValueSlot(this, location);
440 return true;
441 }
442
443 if (propertyName == exec->propertyNames().arguments) {
444 slot.setCustom(this, getArgumentsGetter());
445 return true;
446 }
447
448 return false;
449}
450
451bool ActivationImp::deleteProperty(ExecState* exec, const Identifier& propertyName)
452{
453 if (propertyName == exec->propertyNames().arguments)
454 return false;
455 return JSObject::deleteProperty(exec, propertyName);
456}
457
458void ActivationImp::put(ExecState*, const Identifier& propertyName, JSValue* value, int attr)
459{
460 // There's no way that an activation object can have a prototype or getter/setter properties
461 ASSERT(!_prop.hasGetterSetterProperties());
462 ASSERT(prototype() == jsNull());
463
464 _prop.put(propertyName, value, attr, (attr == None || attr == DontDelete));
465}
466
467void ActivationImp::mark()
468{
469 if (_function && !_function->marked())
470 _function->mark();
471 if (_argumentsObject && !_argumentsObject->marked())
472 _argumentsObject->mark();
473 JSObject::mark();
474}
475
476void ActivationImp::createArgumentsObject(ExecState* exec)
477{
478 _argumentsObject = new Arguments(exec, _function, _arguments, const_cast<ActivationImp*>(this));
479 // The arguments list is only needed to create the arguments object, so discard it now
480 _arguments.reset();
481}
482
483// ------------------------------ GlobalFunc -----------------------------------
484
485
486GlobalFuncImp::GlobalFuncImp(ExecState* exec, FunctionPrototype* funcProto, int i, int len, const Identifier& name)
487 : InternalFunctionImp(funcProto, name)
488 , id(i)
489{
490 putDirect(exec->propertyNames().length, len, DontDelete|ReadOnly|DontEnum);
491}
492
493static JSValue* encode(ExecState* exec, const List& args, const char* do_not_escape)
494{
495 UString r = "", s, str = args[0]->toString(exec);
496 CString cstr = str.UTF8String();
497 const char* p = cstr.c_str();
498 for (size_t k = 0; k < cstr.size(); k++, p++) {
499 char c = *p;
500 if (c && strchr(do_not_escape, c)) {
501 r.append(c);
502 } else {
503 char tmp[4];
504 sprintf(tmp, "%%%02X", (unsigned char)c);
505 r += tmp;
506 }
507 }
508 return jsString(r);
509}
510
511static JSValue* decode(ExecState* exec, const List& args, const char* do_not_unescape, bool strict)
512{
513 UString s = "", str = args[0]->toString(exec);
514 int k = 0, len = str.size();
515 const UChar* d = str.data();
516 UChar u;
517 while (k < len) {
518 const UChar* p = d + k;
519 UChar c = *p;
520 if (c == '%') {
521 int charLen = 0;
522 if (k <= len - 3 && isASCIIHexDigit(p[1].uc) && isASCIIHexDigit(p[2].uc)) {
523 const char b0 = Lexer::convertHex(p[1].uc, p[2].uc);
524 const int sequenceLen = UTF8SequenceLength(b0);
525 if (sequenceLen != 0 && k <= len - sequenceLen * 3) {
526 charLen = sequenceLen * 3;
527 char sequence[5];
528 sequence[0] = b0;
529 for (int i = 1; i < sequenceLen; ++i) {
530 const UChar* q = p + i * 3;
531 if (q[0] == '%' && isASCIIHexDigit(q[1].uc) && isASCIIHexDigit(q[2].uc))
532 sequence[i] = Lexer::convertHex(q[1].uc, q[2].uc);
533 else {
534 charLen = 0;
535 break;
536 }
537 }
538 if (charLen != 0) {
539 sequence[sequenceLen] = 0;
540 const int character = decodeUTF8Sequence(sequence);
541 if (character < 0 || character >= 0x110000) {
542 charLen = 0;
543 } else if (character >= 0x10000) {
544 // Convert to surrogate pair.
545 s.append(static_cast<unsigned short>(0xD800 | ((character - 0x10000) >> 10)));
546 u = static_cast<unsigned short>(0xDC00 | ((character - 0x10000) & 0x3FF));
547 } else {
548 u = static_cast<unsigned short>(character);
549 }
550 }
551 }
552 }
553 if (charLen == 0) {
554 if (strict)
555 return throwError(exec, URIError);
556 // The only case where we don't use "strict" mode is the "unescape" function.
557 // For that, it's good to support the wonky "%u" syntax for compatibility with WinIE.
558 if (k <= len - 6 && p[1] == 'u'
559 && isASCIIHexDigit(p[2].uc) && isASCIIHexDigit(p[3].uc)
560 && isASCIIHexDigit(p[4].uc) && isASCIIHexDigit(p[5].uc)) {
561 charLen = 6;
562 u = Lexer::convertUnicode(p[2].uc, p[3].uc, p[4].uc, p[5].uc);
563 }
564 }
565 if (charLen && (u.uc == 0 || u.uc >= 128 || !strchr(do_not_unescape, u.low()))) {
566 c = u;
567 k += charLen - 1;
568 }
569 }
570 k++;
571 s.append(c);
572 }
573 return jsString(s);
574}
575
576static bool isStrWhiteSpace(unsigned short c)
577{
578 switch (c) {
579 case 0x0009:
580 case 0x000A:
581 case 0x000B:
582 case 0x000C:
583 case 0x000D:
584 case 0x0020:
585 case 0x00A0:
586 case 0x2028:
587 case 0x2029:
588 return true;
589 default:
590 return isSeparatorSpace(c);
591 }
592}
593
594static int parseDigit(unsigned short c, int radix)
595{
596 int digit = -1;
597
598 if (c >= '0' && c <= '9') {
599 digit = c - '0';
600 } else if (c >= 'A' && c <= 'Z') {
601 digit = c - 'A' + 10;
602 } else if (c >= 'a' && c <= 'z') {
603 digit = c - 'a' + 10;
604 }
605
606 if (digit >= radix)
607 return -1;
608 return digit;
609}
610
611double parseIntOverflow(const char* s, int length, int radix)
612{
613 double number = 0.0;
614 double radixMultiplier = 1.0;
615
616 for (const char* p = s + length - 1; p >= s; p--) {
617 if (radixMultiplier == Inf) {
618 if (*p != '0') {
619 number = Inf;
620 break;
621 }
622 } else {
623 int digit = parseDigit(*p, radix);
624 number += digit * radixMultiplier;
625 }
626
627 radixMultiplier *= radix;
628 }
629
630 return number;
631}
632
633static double parseInt(const UString& s, int radix)
634{
635 int length = s.size();
636 int p = 0;
637
638 while (p < length && isStrWhiteSpace(s[p].uc)) {
639 ++p;
640 }
641
642 double sign = 1;
643 if (p < length) {
644 if (s[p] == '+') {
645 ++p;
646 } else if (s[p] == '-') {
647 sign = -1;
648 ++p;
649 }
650 }
651
652 if ((radix == 0 || radix == 16) && length - p >= 2 && s[p] == '0' && (s[p + 1] == 'x' || s[p + 1] == 'X')) {
653 radix = 16;
654 p += 2;
655 } else if (radix == 0) {
656 if (p < length && s[p] == '0')
657 radix = 8;
658 else
659 radix = 10;
660 }
661
662 if (radix < 2 || radix > 36)
663 return NaN;
664
665 int firstDigitPosition = p;
666 bool sawDigit = false;
667 double number = 0;
668 while (p < length) {
669 int digit = parseDigit(s[p].uc, radix);
670 if (digit == -1)
671 break;
672 sawDigit = true;
673 number *= radix;
674 number += digit;
675 ++p;
676 }
677
678 if (number >= mantissaOverflowLowerBound) {
679 if (radix == 10)
680 number = kjs_strtod(s.substr(firstDigitPosition, p - firstDigitPosition).ascii(), 0);
681 else if (radix == 2 || radix == 4 || radix == 8 || radix == 16 || radix == 32)
682 number = parseIntOverflow(s.substr(firstDigitPosition, p - firstDigitPosition).ascii(), p - firstDigitPosition, radix);
683 }
684
685 if (!sawDigit)
686 return NaN;
687
688 return sign * number;
689}
690
691static double parseFloat(const UString& s)
692{
693 // Check for 0x prefix here, because toDouble allows it, but we must treat it as 0.
694 // Need to skip any whitespace and then one + or - sign.
695 int length = s.size();
696 int p = 0;
697 while (p < length && isStrWhiteSpace(s[p].uc)) {
698 ++p;
699 }
700 if (p < length && (s[p] == '+' || s[p] == '-')) {
701 ++p;
702 }
703 if (length - p >= 2 && s[p] == '0' && (s[p + 1] == 'x' || s[p + 1] == 'X')) {
704 return 0;
705 }
706
707 return s.toDouble( true /*tolerant*/, false /* NaN for empty string */ );
708}
709
710JSValue* GlobalFuncImp::callAsFunction(ExecState* exec, JSObject* thisObj, const List& args)
711{
712 JSValue* res = jsUndefined();
713
714 static const char do_not_escape[] =
715 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
716 "abcdefghijklmnopqrstuvwxyz"
717 "0123456789"
718 "*+-./@_";
719
720 static const char do_not_escape_when_encoding_URI_component[] =
721 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
722 "abcdefghijklmnopqrstuvwxyz"
723 "0123456789"
724 "!'()*-._~";
725 static const char do_not_escape_when_encoding_URI[] =
726 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
727 "abcdefghijklmnopqrstuvwxyz"
728 "0123456789"
729 "!#$&'()*+,-./:;=?@_~";
730 static const char do_not_unescape_when_decoding_URI[] =
731 "#$&+,/:;=?@";
732
733 switch (id) {
734 case Eval: { // eval()
735 JSValue* x = args[0];
736 if (!x->isString())
737 return x;
738 else {
739 UString s = x->toString(exec);
740
741 int sid;
742 int errLine;
743 UString errMsg;
744 RefPtr<ProgramNode> progNode(Parser::parse(UString(), 0, s.data(),s.size(),&sid,&errLine,&errMsg));
745
746 Debugger* dbg = exec->dynamicInterpreter()->debugger();
747 if (dbg) {
748 bool cont = dbg->sourceParsed(exec, sid, UString(), s, 0, errLine, errMsg);
749 if (!cont)
750 return jsUndefined();
751 }
752
753 // no program node means a syntax occurred
754 if (!progNode)
755 return throwError(exec, SyntaxError, errMsg, errLine, sid, NULL);
756
757 bool switchGlobal = thisObj && exec->dynamicInterpreter()->isGlobalObject(thisObj) && thisObj != exec->dynamicInterpreter()->globalObject();
758
759 // enter a new execution context
760 Interpreter* interpreter = switchGlobal ? exec->dynamicInterpreter()->interpreterForGlobalObject(thisObj) : exec->dynamicInterpreter();
761 JSObject* thisVal = static_cast<JSObject*>(exec->context()->thisValue());
762 Context ctx(interpreter->globalObject(),
763 interpreter,
764 thisVal,
765 progNode.get(),
766 EvalCode,
767 exec->context());
768 ExecState newExec(interpreter, &ctx);
769 if (exec->hadException())
770 newExec.setException(exec->exception());
771 ctx.setExecState(&newExec);
772
773 if (switchGlobal) {
774 ctx.pushScope(thisObj);
775 ctx.setVariableObject(thisObj);
776 }
777
778 Completion c = progNode->execute(&newExec);
779
780 if (switchGlobal)
781 ctx.popScope();
782
783 // if an exception occured, propogate it back to the previous execution object
784 if (newExec.hadException())
785 exec->setException(newExec.exception());
786
787 res = jsUndefined();
788 if (c.complType() == Throw)
789 exec->setException(c.value());
790 else if (c.isValueCompletion())
791 res = c.value();
792 }
793 break;
794 }
795 case ParseInt:
796 res = jsNumber(parseInt(args[0]->toString(exec), args[1]->toInt32(exec)));
797 break;
798 case ParseFloat:
799 res = jsNumber(parseFloat(args[0]->toString(exec)));
800 break;
801 case IsNaN:
802 res = jsBoolean(isNaN(args[0]->toNumber(exec)));
803 break;
804 case IsFinite: {
805 double n = args[0]->toNumber(exec);
806 res = jsBoolean(!isNaN(n) && !isInf(n));
807 break;
808 }
809 case DecodeURI:
810 res = decode(exec, args, do_not_unescape_when_decoding_URI, true);
811 break;
812 case DecodeURIComponent:
813 res = decode(exec, args, "", true);
814 break;
815 case EncodeURI:
816 res = encode(exec, args, do_not_escape_when_encoding_URI);
817 break;
818 case EncodeURIComponent:
819 res = encode(exec, args, do_not_escape_when_encoding_URI_component);
820 break;
821 case Escape:
822 {
823 UString r = "", s, str = args[0]->toString(exec);
824 const UChar* c = str.data();
825 for (int k = 0; k < str.size(); k++, c++) {
826 int u = c->uc;
827 if (u > 255) {
828 char tmp[7];
829 sprintf(tmp, "%%u%04X", u);
830 s = UString(tmp);
831 } else if (u != 0 && strchr(do_not_escape, (char)u)) {
832 s = UString(c, 1);
833 } else {
834 char tmp[4];
835 sprintf(tmp, "%%%02X", u);
836 s = UString(tmp);
837 }
838 r += s;
839 }
840 res = jsString(r);
841 break;
842 }
843 case UnEscape:
844 {
845 UString s = "", str = args[0]->toString(exec);
846 int k = 0, len = str.size();
847 while (k < len) {
848 const UChar* c = str.data() + k;
849 UChar u;
850 if (*c == UChar('%') && k <= len - 6 && *(c+1) == UChar('u')) {
851 if (Lexer::isHexDigit((c+2)->uc) && Lexer::isHexDigit((c+3)->uc) &&
852 Lexer::isHexDigit((c+4)->uc) && Lexer::isHexDigit((c+5)->uc)) {
853 u = Lexer::convertUnicode((c+2)->uc, (c+3)->uc,
854 (c+4)->uc, (c+5)->uc);
855 c = &u;
856 k += 5;
857 }
858 } else if (*c == UChar('%') && k <= len - 3 &&
859 Lexer::isHexDigit((c+1)->uc) && Lexer::isHexDigit((c+2)->uc)) {
860 u = UChar(Lexer::convertHex((c+1)->uc, (c+2)->uc));
861 c = &u;
862 k += 2;
863 }
864 k++;
865 s += UString(c, 1);
866 }
867 res = jsString(s);
868 break;
869 }
870#ifndef NDEBUG
871 case KJSPrint:
872 puts(args[0]->toString(exec).ascii());
873 break;
874#endif
875 }
876
877 return res;
878}
879
880UString escapeStringForPrettyPrinting(const UString& s)
881{
882 UString escapedString;
883
884 for (int i = 0; i < s.size(); i++) {
885 unsigned short c = s.data()[i].unicode();
886
887 switch (c) {
888 case '\"':
889 escapedString += "\\\"";
890 break;
891 case '\n':
892 escapedString += "\\n";
893 break;
894 case '\r':
895 escapedString += "\\r";
896 break;
897 case '\t':
898 escapedString += "\\t";
899 break;
900 case '\\':
901 escapedString += "\\\\";
902 break;
903 default:
904 if (c < 128 && isPrintableChar(c))
905 escapedString.append(c);
906 else {
907 char hexValue[7];
908
909#if PLATFORM(WIN_OS)
910 _snprintf(hexValue, 7, "\\u%04x", c);
911#else
912 snprintf(hexValue, 7, "\\u%04x", c);
913#endif
914 escapedString += hexValue;
915 }
916 }
917 }
918
919 return escapedString;
920}
921
922} // namespace
Note: See TracBrowser for help on using the repository browser.