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

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