本文整理汇总了C++中JSObject类的典型用法代码示例。如果您正苦于以下问题:C++ JSObject类的具体用法?C++ JSObject怎么用?C++ JSObject使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JSObject类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: JS_ASSERT
JSScript *
frontend::CompileScript(JSContext *cx, JSObject *scopeChain, StackFrame *callerFrame,
JSPrincipals *principals, JSPrincipals *originPrincipals,
uint32_t tcflags,
const jschar *chars, size_t length,
const char *filename, unsigned lineno, JSVersion version,
JSString *source /* = NULL */,
unsigned staticLevel /* = 0 */)
{
TokenKind tt;
ParseNode *pn;
bool inDirectivePrologue;
JS_ASSERT(!(tcflags & ~(TCF_COMPILE_N_GO | TCF_NO_SCRIPT_RVAL | TCF_COMPILE_FOR_EVAL
| TCF_NEED_SCRIPT_GLOBAL)));
/*
* The scripted callerFrame can only be given for compile-and-go scripts
* and non-zero static level requires callerFrame.
*/
JS_ASSERT_IF(callerFrame, tcflags & TCF_COMPILE_N_GO);
JS_ASSERT_IF(staticLevel != 0, callerFrame);
Parser parser(cx, principals, originPrincipals, callerFrame);
if (!parser.init(chars, length, filename, lineno, version))
return NULL;
TokenStream &tokenStream = parser.tokenStream;
BytecodeEmitter bce(&parser, tokenStream.getLineno());
if (!bce.init(cx, TreeContext::USED_AS_TREE_CONTEXT))
return NULL;
Probes::compileScriptBegin(cx, filename, lineno);
MUST_FLOW_THROUGH("out");
// We can specialize a bit for the given scope chain if that scope chain is the global object.
JSObject *globalObj = scopeChain && scopeChain == &scopeChain->global()
? &scopeChain->global()
: NULL;
JS_ASSERT_IF(globalObj, globalObj->isNative());
JS_ASSERT_IF(globalObj, JSCLASS_HAS_GLOBAL_FLAG_AND_SLOTS(globalObj->getClass()));
RootedVar<JSScript*> script(cx);
GlobalScope globalScope(cx, globalObj, &bce);
bce.flags |= tcflags;
bce.setScopeChain(scopeChain);
bce.globalScope = &globalScope;
if (!SetStaticLevel(&bce, staticLevel))
goto out;
/* If this is a direct call to eval, inherit the caller's strictness. */
if (callerFrame &&
callerFrame->isScriptFrame() &&
callerFrame->script()->strictModeCode) {
bce.flags |= TCF_STRICT_MODE_CODE;
tokenStream.setStrictMode();
}
#ifdef DEBUG
bool savedCallerFun;
savedCallerFun = false;
#endif
if (tcflags & TCF_COMPILE_N_GO) {
if (source) {
/*
* Save eval program source in script->atoms[0] for the
* eval cache (see EvalCacheLookup in jsobj.cpp).
*/
JSAtom *atom = js_AtomizeString(cx, source);
jsatomid _;
if (!atom || !bce.makeAtomIndex(atom, &_))
goto out;
}
if (callerFrame && callerFrame->isFunctionFrame()) {
/*
* An eval script in a caller frame needs to have its enclosing
* function captured in case it refers to an upvar, and someone
* wishes to decompile it while it's running.
*/
ObjectBox *funbox = parser.newObjectBox(callerFrame->fun());
if (!funbox)
goto out;
funbox->emitLink = bce.objectList.lastbox;
bce.objectList.lastbox = funbox;
bce.objectList.length++;
#ifdef DEBUG
savedCallerFun = true;
#endif
}
}
/*
* Inline this->statements to emit as we go to save AST space. We must
* generate our script-body blockid since we aren't calling Statements.
*/
uint32_t bodyid;
//.........这里部分代码省略.........
示例2: source
JSScript *
frontend::CompileScript(JSContext *cx, HandleObject scopeChain, StackFrame *callerFrame,
JSPrincipals *principals, JSPrincipals *originPrincipals,
bool compileAndGo, bool noScriptRval,
const jschar *chars, size_t length,
const char *filename, unsigned lineno, JSVersion version,
JSString *source_ /* = NULL */,
unsigned staticLevel /* = 0 */)
{
RootedString source(cx, source_);
class ProbesManager
{
const char* filename;
unsigned lineno;
public:
ProbesManager(const char *f, unsigned l) : filename(f), lineno(l) {
Probes::compileScriptBegin(filename, lineno);
}
~ProbesManager() { Probes::compileScriptEnd(filename, lineno); }
};
ProbesManager probesManager(filename, lineno);
/*
* The scripted callerFrame can only be given for compile-and-go scripts
* and non-zero static level requires callerFrame.
*/
JS_ASSERT_IF(callerFrame, compileAndGo);
JS_ASSERT_IF(staticLevel != 0, callerFrame);
Parser parser(cx, principals, originPrincipals, chars, length, filename, lineno, version,
/* foldConstants = */ true, compileAndGo);
if (!parser.init())
return NULL;
SharedContext sc(cx, scopeChain, /* fun = */ NULL, /* funbox = */ NULL, StrictModeFromContext(cx));
TreeContext tc(&parser, &sc, staticLevel, /* bodyid = */ 0);
if (!tc.init())
return NULL;
bool savedCallerFun = compileAndGo && callerFrame && callerFrame->isFunctionFrame();
Rooted<JSScript*> script(cx, JSScript::Create(cx,
/* enclosingScope = */ NullPtr(),
savedCallerFun,
principals,
originPrincipals,
compileAndGo,
noScriptRval,
version,
staticLevel));
if (!script)
return NULL;
// We can specialize a bit for the given scope chain if that scope chain is the global object.
JSObject *globalScope = scopeChain && scopeChain == &scopeChain->global() ? (JSObject*) scopeChain : NULL;
JS_ASSERT_IF(globalScope, globalScope->isNative());
JS_ASSERT_IF(globalScope, JSCLASS_HAS_GLOBAL_FLAG_AND_SLOTS(globalScope->getClass()));
BytecodeEmitter bce(/* parent = */ NULL, &parser, &sc, script, callerFrame, !!globalScope,
lineno);
if (!bce.init())
return NULL;
/* If this is a direct call to eval, inherit the caller's strictness. */
if (callerFrame && callerFrame->isScriptFrame() && callerFrame->script()->strictModeCode)
sc.strictModeState = StrictMode::STRICT;
if (compileAndGo) {
if (source) {
/*
* Save eval program source in script->atoms[0] for the
* eval cache (see EvalCacheLookup in jsobj.cpp).
*/
JSAtom *atom = js_AtomizeString(cx, source);
jsatomid _;
if (!atom || !bce.makeAtomIndex(atom, &_))
return NULL;
}
if (callerFrame && callerFrame->isFunctionFrame()) {
/*
* An eval script in a caller frame needs to have its enclosing
* function captured in case it refers to an upvar, and someone
* wishes to decompile it while it's running.
*/
ObjectBox *funbox = parser.newObjectBox(callerFrame->fun());
if (!funbox)
return NULL;
funbox->emitLink = bce.objectList.lastbox;
bce.objectList.lastbox = funbox;
bce.objectList.length++;
}
}
ParseNode *pn;
#if JS_HAS_XML_SUPPORT
pn = NULL;
bool onlyXML;
//.........这里部分代码省略.........
示例3: Exception
static JSBool
Exception(JSContext *cx, uintN argc, Value *vp)
{
JSString *message, *filename;
JSStackFrame *fp;
/*
* ECMA ed. 3, 15.11.1 requires Error, etc., to construct even when
* called as functions, without operator new. But as we do not give
* each constructor a distinct JSClass, whose .name member is used by
* NewNativeClassInstance to find the class prototype, we must get the
* class prototype ourselves.
*/
JSObject &callee = vp[0].toObject();
Value protov;
if (!callee.getProperty(cx, ATOM_TO_JSID(cx->runtime->atomState.classPrototypeAtom), &protov))
return JS_FALSE;
JSObject *errProto = &protov.toObject();
JSObject *obj = NewNativeClassInstance(cx, &js_ErrorClass, errProto, errProto->getParent());
if (!obj)
return JS_FALSE;
/*
* If it's a new object of class Exception, then null out the private
* data so that the finalizer doesn't attempt to free it.
*/
if (obj->getClass() == &js_ErrorClass)
obj->setPrivate(NULL);
/* Set the 'message' property. */
Value *argv = vp + 2;
if (argc != 0) {
message = js_ValueToString(cx, argv[0]);
if (!message)
return JS_FALSE;
argv[0].setString(message);
} else {
message = cx->runtime->emptyString;
}
/* Set the 'fileName' property. */
if (argc > 1) {
filename = js_ValueToString(cx, argv[1]);
if (!filename)
return JS_FALSE;
argv[1].setString(filename);
fp = NULL;
} else {
fp = js_GetScriptedCaller(cx, NULL);
if (fp) {
filename = FilenameToString(cx, fp->script()->filename);
if (!filename)
return JS_FALSE;
} else {
filename = cx->runtime->emptyString;
}
}
/* Set the 'lineNumber' property. */
uint32_t lineno;
if (argc > 2) {
if (!ValueToECMAUint32(cx, argv[2], &lineno))
return JS_FALSE;
} else {
if (!fp)
fp = js_GetScriptedCaller(cx, NULL);
lineno = (fp && fp->pc(cx)) ? js_FramePCToLineNumber(cx, fp) : 0;
}
if (obj->getClass() == &js_ErrorClass &&
!InitExnPrivate(cx, obj, message, filename, lineno, NULL)) {
return JS_FALSE;
}
vp->setObject(*obj);
return JS_TRUE;
}
示例4: compileArrayWithLength
CompileStatus
mjit::Compiler::inlineNativeFunction(uint32_t argc, bool callingNew)
{
if (!cx->typeInferenceEnabled())
return Compile_InlineAbort;
FrameEntry *origCallee = frame.peek(-((int)argc + 2));
FrameEntry *thisValue = frame.peek(-((int)argc + 1));
types::TypeSet *thisTypes = analysis->poppedTypes(PC, argc);
if (!origCallee->isConstant() || !origCallee->isType(JSVAL_TYPE_OBJECT))
return Compile_InlineAbort;
JSObject *callee = &origCallee->getValue().toObject();
if (!callee->isFunction())
return Compile_InlineAbort;
/*
* The callee must have the same parent as the script's global, otherwise
* inference may not have accounted for any side effects correctly.
*/
if (!globalObj || globalObj != &callee->global())
return Compile_InlineAbort;
Native native = callee->toFunction()->maybeNative();
if (!native)
return Compile_InlineAbort;
JSValueType type = knownPushedType(0);
JSValueType thisType = thisValue->isTypeKnown()
? thisValue->getKnownType()
: JSVAL_TYPE_UNKNOWN;
/*
* Note: when adding new natives which operate on properties, add relevant
* constraint generation to the behavior of TypeConstraintCall.
*/
/* Handle natives that can be called either with or without 'new'. */
if (native == js_Array && type == JSVAL_TYPE_OBJECT && globalObj) {
if (argc == 0 || argc == 1)
return compileArrayWithLength(argc);
return compileArrayWithArgs(argc);
}
/* Remaining natives must not be called with 'new'. */
if (callingNew)
return Compile_InlineAbort;
if (native == js::num_parseInt && argc >= 1) {
FrameEntry *arg = frame.peek(-(int32_t)argc);
JSValueType argType = arg->isTypeKnown() ? arg->getKnownType() : JSVAL_TYPE_UNKNOWN;
if ((argType == JSVAL_TYPE_DOUBLE || argType == JSVAL_TYPE_INT32) &&
type == JSVAL_TYPE_INT32) {
return compileParseInt(argType, argc);
}
}
if (argc == 0) {
if ((native == js::array_pop || native == js::array_shift) && thisType == JSVAL_TYPE_OBJECT) {
/*
* Only handle pop/shift on dense arrays which have never been used
* in an iterator --- when popping elements we don't account for
* suppressing deleted properties in active iterators.
*
* Constraints propagating properties directly into the result
* type set are generated by TypeConstraintCall during inference.
*/
if (!thisTypes->hasObjectFlags(cx, types::OBJECT_FLAG_NON_DENSE_ARRAY |
types::OBJECT_FLAG_ITERATED) &&
!types::ArrayPrototypeHasIndexedProperty(cx, outerScript)) {
bool packed = !thisTypes->hasObjectFlags(cx, types::OBJECT_FLAG_NON_PACKED_ARRAY);
return compileArrayPopShift(thisValue, packed, native == js::array_pop);
}
}
} else if (argc == 1) {
FrameEntry *arg = frame.peek(-1);
types::TypeSet *argTypes = frame.extra(arg).types;
if (!argTypes)
return Compile_InlineAbort;
JSValueType argType = arg->isTypeKnown() ? arg->getKnownType() : JSVAL_TYPE_UNKNOWN;
if (native == js_math_abs) {
if (argType == JSVAL_TYPE_INT32 && type == JSVAL_TYPE_INT32)
return compileMathAbsInt(arg);
if (argType == JSVAL_TYPE_DOUBLE && type == JSVAL_TYPE_DOUBLE)
return compileMathAbsDouble(arg);
}
if (native == js_math_floor && argType == JSVAL_TYPE_DOUBLE &&
type == JSVAL_TYPE_INT32) {
return compileRound(arg, Floor);
}
if (native == js_math_round && argType == JSVAL_TYPE_DOUBLE &&
type == JSVAL_TYPE_INT32) {
return compileRound(arg, Round);
}
//.........这里部分代码省略.........
示例5: source
JSScript *
frontend::CompileScript(ExclusiveContext *cx, LifoAlloc *alloc, HandleObject scopeChain,
HandleScript evalCaller,
const CompileOptions &options,
const jschar *chars, size_t length,
JSString *source_ /* = NULL */,
unsigned staticLevel /* = 0 */,
SourceCompressionTask *extraSct /* = NULL */)
{
RootedString source(cx, source_);
SkipRoot skip(cx, &chars);
#if JS_TRACE_LOGGING
js::AutoTraceLog logger(js::TraceLogging::defaultLogger(),
js::TraceLogging::PARSER_COMPILE_SCRIPT_START,
js::TraceLogging::PARSER_COMPILE_SCRIPT_STOP,
options);
#endif
if (cx->isJSContext())
MaybeCallSourceHandler(cx->asJSContext(), options, chars, length);
/*
* The scripted callerFrame can only be given for compile-and-go scripts
* and non-zero static level requires callerFrame.
*/
JS_ASSERT_IF(evalCaller, options.compileAndGo);
JS_ASSERT_IF(evalCaller, options.forEval);
JS_ASSERT_IF(staticLevel != 0, evalCaller);
if (!CheckLength(cx, length))
return NULL;
JS_ASSERT_IF(staticLevel != 0, options.sourcePolicy != CompileOptions::LAZY_SOURCE);
ScriptSource *ss = cx->new_<ScriptSource>(options.originPrincipals());
if (!ss)
return NULL;
if (options.filename && !ss->setFilename(cx, options.filename))
return NULL;
RootedScriptSource sourceObject(cx, ScriptSourceObject::create(cx, ss));
if (!sourceObject)
return NULL;
SourceCompressionTask mysct(cx);
SourceCompressionTask *sct = extraSct ? extraSct : &mysct;
switch (options.sourcePolicy) {
case CompileOptions::SAVE_SOURCE:
if (!ss->setSourceCopy(cx, chars, length, false, sct))
return NULL;
break;
case CompileOptions::LAZY_SOURCE:
ss->setSourceRetrievable();
break;
case CompileOptions::NO_SOURCE:
break;
}
bool canLazilyParse = CanLazilyParse(cx, options);
Maybe<Parser<SyntaxParseHandler> > syntaxParser;
if (canLazilyParse) {
syntaxParser.construct(cx, alloc, options, chars, length, /* foldConstants = */ false,
(Parser<SyntaxParseHandler> *) NULL,
(LazyScript *) NULL);
}
Parser<FullParseHandler> parser(cx, alloc, options, chars, length, /* foldConstants = */ true,
canLazilyParse ? &syntaxParser.ref() : NULL, NULL);
parser.sct = sct;
parser.ss = ss;
Directives directives(options.strictOption);
GlobalSharedContext globalsc(cx, scopeChain, directives, options.extraWarningsOption);
bool savedCallerFun =
options.compileAndGo &&
evalCaller &&
(evalCaller->function() || evalCaller->savedCallerFun);
Rooted<JSScript*> script(cx, JSScript::Create(cx, NullPtr(), savedCallerFun,
options, staticLevel, sourceObject, 0, length));
if (!script)
return NULL;
// Global/eval script bindings are always empty (all names are added to the
// scope dynamically via JSOP_DEFFUN/VAR).
InternalHandle<Bindings*> bindings(script, &script->bindings);
if (!Bindings::initWithTemporaryStorage(cx, bindings, 0, 0, NULL))
return NULL;
// We can specialize a bit for the given scope chain if that scope chain is the global object.
JSObject *globalScope = scopeChain && scopeChain == &scopeChain->global() ? (JSObject*) scopeChain : NULL;
JS_ASSERT_IF(globalScope, globalScope->isNative());
JS_ASSERT_IF(globalScope, JSCLASS_HAS_GLOBAL_FLAG_AND_SLOTS(globalScope->getClass()));
BytecodeEmitter::EmitterMode emitterMode =
options.selfHostingMode ? BytecodeEmitter::SelfHosting : BytecodeEmitter::Normal;
BytecodeEmitter bce(/* parent = */ NULL, &parser, &globalsc, script, options.forEval, evalCaller,
!!globalScope, options.lineno, emitterMode);
if (!bce.init())
//.........这里部分代码省略.........
示例6: StatsCellCallback
static void
StatsCellCallback(JSRuntime *rt, void *data, void *thing, JSGCTraceKind traceKind,
size_t thingSize)
{
IteratorClosure *closure = static_cast<IteratorClosure *>(data);
RuntimeStats *rtStats = closure->rtStats;
CompartmentStats *cStats = rtStats->currCompartmentStats;
switch (traceKind) {
case JSTRACE_OBJECT:
{
JSObject *obj = static_cast<JSObject *>(thing);
if (obj->isFunction()) {
cStats->gcHeapObjectsFunction += thingSize;
} else {
cStats->gcHeapObjectsNonFunction += thingSize;
}
size_t slotsSize, elementsSize, miscSize;
obj->sizeOfExcludingThis(rtStats->mallocSizeOf, &slotsSize,
&elementsSize, &miscSize);
cStats->objectSlots += slotsSize;
cStats->objectElements += elementsSize;
cStats->objectMisc += miscSize;
if (ObjectPrivateVisitor *opv = closure->opv) {
js::Class *clazz = js::GetObjectClass(obj);
if (clazz->flags & JSCLASS_HAS_PRIVATE &&
clazz->flags & JSCLASS_PRIVATE_IS_NSISUPPORTS)
{
cStats->objectPrivate += opv->sizeOfIncludingThis(GetObjectPrivate(obj));
}
}
break;
}
case JSTRACE_STRING:
{
JSString *str = static_cast<JSString *>(thing);
cStats->gcHeapStrings += thingSize;
cStats->stringChars += str->sizeOfExcludingThis(rtStats->mallocSizeOf);
break;
}
case JSTRACE_SHAPE:
{
Shape *shape = static_cast<Shape*>(thing);
size_t propTableSize, kidsSize;
shape->sizeOfExcludingThis(rtStats->mallocSizeOf, &propTableSize, &kidsSize);
if (shape->inDictionary()) {
cStats->gcHeapShapesDict += thingSize;
cStats->shapesExtraDictTables += propTableSize;
JS_ASSERT(kidsSize == 0);
} else {
cStats->gcHeapShapesTree += thingSize;
cStats->shapesExtraTreeTables += propTableSize;
cStats->shapesExtraTreeShapeKids += kidsSize;
}
break;
}
case JSTRACE_BASE_SHAPE:
{
cStats->gcHeapShapesBase += thingSize;
break;
}
case JSTRACE_SCRIPT:
{
JSScript *script = static_cast<JSScript *>(thing);
cStats->gcHeapScripts += thingSize;
cStats->scriptData += script->sizeOfData(rtStats->mallocSizeOf);
#ifdef JS_METHODJIT
cStats->mjitData += script->sizeOfJitScripts(rtStats->mallocSizeOf);
# ifdef JS_ION
if (script->hasIonScript())
cStats->mjitData += script->ion->size();
# endif
#endif
ScriptSource *ss = script->scriptSource();
SourceSet::AddPtr entry = closure->seenSources.lookupForAdd(ss);
if (!entry) {
closure->seenSources.add(entry, ss); // Not much to be done on failure.
rtStats->runtime.scriptSources += ss->sizeOfIncludingThis(rtStats->mallocSizeOf);
}
break;
}
case JSTRACE_IONCODE:
{
#ifdef JS_METHODJIT
# ifdef JS_ION
ion::IonCode *code = static_cast<ion::IonCode *>(thing);
cStats->gcHeapScripts += thingSize;
cStats->mjitData += code->bufferSize();
# endif
#endif
break;
}
case JSTRACE_TYPE_OBJECT:
{
types::TypeObject *obj = static_cast<types::TypeObject *>(thing);
cStats->gcHeapTypeObjects += thingSize;
obj->sizeOfExcludingThis(&cStats->typeInferenceSizes, rtStats->mallocSizeOf);
break;
}
//.........这里部分代码省略.........
示例7: JS_ASSERT
PropertyCacheEntry *
PropertyCache::fill(JSContext *cx, JSObject *obj, JSObject *pobj, Shape *shape)
{
JS_ASSERT(this == &JS_PROPERTY_CACHE(cx));
JS_ASSERT(!cx->runtime->isHeapBusy());
/*
* Check for overdeep scope and prototype chain. Because resolve, getter,
* and setter hooks can change the prototype chain using JS_SetPrototype
* after LookupPropertyWithFlags has returned, we calculate the protoIndex
* here and not in LookupPropertyWithFlags.
*/
JSObject *tmp = obj;
unsigned protoIndex = 0;
while (tmp != pobj) {
/*
* Don't cache entries across prototype lookups which can mutate in
* arbitrary ways without a shape change.
*/
if (tmp->hasUncacheableProto()) {
PCMETER(noprotos++);
return JS_NO_PROP_CACHE_FILL;
}
tmp = tmp->getProto();
/*
* We cannot cache properties coming from native objects behind
* non-native ones on the prototype chain. The non-natives can
* mutate in arbitrary way without changing any shapes.
*/
if (!tmp || !tmp->isNative()) {
PCMETER(noprotos++);
return JS_NO_PROP_CACHE_FILL;
}
++protoIndex;
}
typedef PropertyCacheEntry Entry;
if (protoIndex > Entry::MaxProtoIndex) {
PCMETER(longchains++);
return JS_NO_PROP_CACHE_FILL;
}
/*
* Optimize the cached vword based on our parameters and the current pc's
* opcode format flags.
*/
jsbytecode *pc;
(void) cx->stack.currentScript(&pc);
JSOp op = JSOp(*pc);
const JSCodeSpec *cs = &js_CodeSpec[op];
if ((cs->format & JOF_SET) && obj->watched())
return JS_NO_PROP_CACHE_FILL;
if (obj == pobj) {
JS_ASSERT(protoIndex == 0);
} else {
JS_ASSERT(protoIndex != 0);
JS_ASSERT((protoIndex == 1) == (obj->getProto() == pobj));
if (protoIndex != 1) {
/*
* Make sure that a later shadowing assignment will enter
* PurgeProtoChain and invalidate this entry, bug 479198.
*/
if (!obj->isDelegate())
return JS_NO_PROP_CACHE_FILL;
}
}
PropertyCacheEntry *entry = &table[hash(pc, obj->lastProperty())];
PCMETER(entry->vword.isNull() || recycles++);
entry->assign(pc, obj->lastProperty(), pobj->lastProperty(), shape, protoIndex);
empty = false;
PCMETER(fills++);
/*
* The modfills counter is not exact. It increases if a getter or setter
* recurse into the interpreter.
*/
PCMETER(entry == pctestentry || modfills++);
PCMETER(pctestentry = NULL);
return entry;
}
示例8: js_NewGenerator
/*
* Called from the JSOP_GENERATOR case in the interpreter, with fp referring
* to the frame by which the generator function was activated. Create a new
* JSGenerator object, which contains its own JSStackFrame that we populate
* from *fp. We know that upon return, the JSOP_GENERATOR opcode will return
* from the activation in fp, so we can steal away fp->callobj and fp->argsobj
* if they are non-null.
*/
JS_REQUIRES_STACK JSObject *
js_NewGenerator(JSContext *cx)
{
JSObject *obj;
uintN argc, nargs, nslots;
JSGenerator *gen;
jsval *slots;
obj = js_NewObject(cx, &js_GeneratorClass, NULL, NULL);
if (!obj)
return NULL;
/* Load and compute stack slot counts. */
JSStackFrame *fp = cx->fp;
argc = fp->argc;
nargs = JS_MAX(argc, fp->fun->nargs);
nslots = 2 + nargs + fp->script->nslots;
/* Allocate obj's private data struct. */
gen = (JSGenerator *)
cx->malloc(sizeof(JSGenerator) + (nslots - 1) * sizeof(jsval));
if (!gen)
return NULL;
gen->obj = obj;
/* Steal away objects reflecting fp and point them at gen->frame. */
gen->frame.callobj = fp->callobj;
if (fp->callobj) {
fp->callobj->setPrivate(&gen->frame);
fp->callobj = NULL;
}
gen->frame.argsobj = fp->argsobj;
if (fp->argsobj) {
JSVAL_TO_OBJECT(fp->argsobj)->setPrivate(&gen->frame);
fp->argsobj = NULL;
}
/* These two references can be shared with fp until it goes away. */
gen->frame.thisv = fp->thisv;
/* Copy call-invariant script and function references. */
gen->frame.script = fp->script;
gen->frame.fun = fp->fun;
/* Use slots to carve space out of gen->slots. */
slots = gen->slots;
gen->arena.next = NULL;
gen->arena.base = (jsuword) slots;
gen->arena.limit = gen->arena.avail = (jsuword) (slots + nslots);
/* Copy rval, argv and vars. */
gen->frame.rval = fp->rval;
memcpy(slots, fp->argv - 2, (2 + nargs) * sizeof(jsval));
gen->frame.argc = fp->argc;
gen->frame.argv = slots + 2;
slots += 2 + nargs;
memcpy(slots, fp->slots, fp->script->nfixed * sizeof(jsval));
/* Initialize or copy virtual machine state. */
gen->frame.down = NULL;
gen->frame.annotation = NULL;
gen->frame.scopeChain = fp->scopeChain;
gen->frame.imacpc = NULL;
gen->frame.slots = slots;
JS_ASSERT(StackBase(fp) == fp->regs->sp);
gen->savedRegs.sp = slots + fp->script->nfixed;
gen->savedRegs.pc = fp->regs->pc;
gen->frame.regs = &gen->savedRegs;
gen->frame.flags = (fp->flags & ~JSFRAME_ROOTED_ARGV) | JSFRAME_GENERATOR;
/* JSOP_GENERATOR appears in the prologue, outside all blocks. */
JS_ASSERT(!fp->blockChain);
gen->frame.blockChain = NULL;
/* Note that gen is newborn. */
gen->state = JSGEN_NEWBORN;
obj->setPrivate(gen);
return obj;
}
示例9: Snapshot
static bool
Snapshot(JSContext *cx, JSObject *obj, uintN flags, AutoIdVector *props)
{
/*
* FIXME: Bug 575997 - We won't need to initialize this hash table if
* (flags & JSITER_OWNONLY) when we eliminate inheritance of
* shared-permanent properties as own properties.
*/
IdSet ht(cx);
if (!ht.init(32))
return NULL;
JSObject *pobj = obj;
do {
Class *clasp = pobj->getClass();
if (pobj->isNative() &&
!pobj->getOps()->enumerate &&
!(clasp->flags & JSCLASS_NEW_ENUMERATE)) {
if (!clasp->enumerate(cx, pobj))
return false;
if (!EnumerateNativeProperties(cx, obj, pobj, flags, ht, props))
return false;
} else if (pobj->isDenseArray()) {
if (!EnumerateDenseArrayProperties(cx, obj, pobj, flags, ht, props))
return false;
} else {
if (pobj->isProxy()) {
AutoIdVector proxyProps(cx);
if (flags & JSITER_OWNONLY) {
if (flags & JSITER_HIDDEN) {
if (!JSProxy::getOwnPropertyNames(cx, pobj, proxyProps))
return false;
} else {
if (!JSProxy::keys(cx, pobj, proxyProps))
return false;
}
} else {
if (!JSProxy::enumerate(cx, pobj, proxyProps))
return false;
}
for (size_t n = 0, len = proxyProps.length(); n < len; n++) {
if (!Enumerate(cx, obj, pobj, proxyProps[n], true, false, flags, ht, props))
return false;
}
/* Proxy objects enumerate the prototype on their own, so we are done here. */
break;
}
Value state;
JSIterateOp op = (flags & JSITER_HIDDEN) ? JSENUMERATE_INIT_ALL : JSENUMERATE_INIT;
if (!pobj->enumerate(cx, op, &state, NULL))
return false;
if (state.isMagic(JS_NATIVE_ENUMERATE)) {
if (!EnumerateNativeProperties(cx, obj, pobj, flags, ht, props))
return false;
} else {
while (true) {
jsid id;
if (!pobj->enumerate(cx, JSENUMERATE_NEXT, &state, &id))
return false;
if (state.isNull())
break;
if (!Enumerate(cx, obj, pobj, id, true, false, flags, ht, props))
return false;
}
}
}
if (JS_UNLIKELY(pobj->isXML()))
break;
} while ((pobj = pobj->getProto()) != NULL);
return true;
}
示例10: setDOMException
void setDOMException(ExecState* exec, ExceptionCode ec)
{
if (ec == 0 || exec->hadException())
return;
const char* type = "DOM";
int code = ec;
const char* const* nameTable;
int nameTableSize;
int nameIndex;
if (code >= RangeExceptionOffset && code <= RangeExceptionMax) {
type = "DOM Range";
code -= RangeExceptionOffset;
nameIndex = code;
nameTable = rangeExceptionNames;
nameTableSize = sizeof(rangeExceptionNames) / sizeof(rangeExceptionNames[0]);
} else if (code >= EventExceptionOffset && code <= EventExceptionMax) {
type = "DOM Events";
code -= EventExceptionOffset;
nameIndex = code;
nameTable = eventExceptionNames;
nameTableSize = sizeof(eventExceptionNames) / sizeof(eventExceptionNames[0]);
} else if (code == XMLHttpRequestExceptionOffset) {
// FIXME: this exception should be replaced with DOM SECURITY_ERR when it finds its way to the spec.
throwError(exec, GeneralError, "Permission denied");
return;
} else if (code > XMLHttpRequestExceptionOffset && code <= XMLHttpRequestExceptionMax) {
type = "XMLHttpRequest";
// XMLHttpRequest exception codes start with 101 and we don't want 100 empty elements in the name array
nameIndex = code - NETWORK_ERR;
code -= XMLHttpRequestExceptionOffset;
nameTable = xmlHttpRequestExceptionNames;
nameTableSize = sizeof(xmlHttpRequestExceptionNames) / sizeof(xmlHttpRequestExceptionNames[0]);
#ifdef XPATH_SUPPORT
} else if (code >= XPathExceptionOffset && code <= XPathExceptionMax) {
type = "DOM XPath";
// XPath exception codes start with 51 and we don't want 51 empty elements in the name array
nameIndex = code - INVALID_EXPRESSION_ERR;
code -= XPathExceptionOffset;
nameTable = xpathExceptionNames;
nameTableSize = sizeof(xpathExceptionNames) / sizeof(xpathExceptionNames[0]);
#endif
#ifdef SVG_SUPPORT
} else if (code >= SVGExceptionOffset && code <= SVGExceptionMax) {
type = "DOM SVG";
code -= SVGExceptionOffset;
nameIndex = code;
nameTable = svgExceptionNames;
nameTableSize = sizeof(svgExceptionNames) / sizeof(svgExceptionNames[0]);
#endif
} else {
nameIndex = code;
nameTable = exceptionNames;
nameTableSize = sizeof(exceptionNames) / sizeof(exceptionNames[0]);
}
const char* name = (nameIndex < nameTableSize && nameIndex >= 0) ? nameTable[nameIndex] : 0;
// 100 characters is a big enough buffer, because there are:
// 13 characters in the message
// 10 characters in the longest type, "DOM Events"
// 27 characters in the longest name, "NO_MODIFICATION_ALLOWED_ERR"
// 20 or so digits in the longest integer's ASCII form (even if int is 64-bit)
// 1 byte for a null character
// That adds up to about 70 bytes.
char buffer[100];
if (name)
sprintf(buffer, "%s: %s Exception %d", name, type, code);
else
sprintf(buffer, "%s Exception %d", type, code);
JSObject* errorObject = throwError(exec, GeneralError, buffer);
errorObject->put(exec, "code", jsNumber(code));
}
示例11: ENABLE
JSValue JSHTMLCanvasElement::getContext(ExecState* exec)
{
HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(impl());
const UString& contextId = exec->argument(0).toString(exec)->value(exec);
RefPtr<CanvasContextAttributes> attrs;
#if ENABLE(WEBGL)
if (contextId == "experimental-webgl" || contextId == "webkit-3d") {
attrs = WebGLContextAttributes::create();
WebGLContextAttributes* webGLAttrs = static_cast<WebGLContextAttributes*>(attrs.get());
if (exec->argumentCount() > 1 && exec->argument(1).isObject()) {
JSObject* jsAttrs = exec->argument(1).getObject();
Identifier alpha(exec, "alpha");
if (jsAttrs->hasProperty(exec, alpha))
webGLAttrs->setAlpha(jsAttrs->get(exec, alpha).toBoolean());
Identifier depth(exec, "depth");
if (jsAttrs->hasProperty(exec, depth))
webGLAttrs->setDepth(jsAttrs->get(exec, depth).toBoolean());
Identifier stencil(exec, "stencil");
if (jsAttrs->hasProperty(exec, stencil))
webGLAttrs->setStencil(jsAttrs->get(exec, stencil).toBoolean());
Identifier antialias(exec, "antialias");
if (jsAttrs->hasProperty(exec, antialias))
webGLAttrs->setAntialias(jsAttrs->get(exec, antialias).toBoolean());
Identifier premultipliedAlpha(exec, "premultipliedAlpha");
if (jsAttrs->hasProperty(exec, premultipliedAlpha))
webGLAttrs->setPremultipliedAlpha(jsAttrs->get(exec, premultipliedAlpha).toBoolean());
Identifier preserveDrawingBuffer(exec, "preserveDrawingBuffer");
if (jsAttrs->hasProperty(exec, preserveDrawingBuffer))
webGLAttrs->setPreserveDrawingBuffer(jsAttrs->get(exec, preserveDrawingBuffer).toBoolean());
}
}
#endif
CanvasRenderingContext* context = canvas->getContext(ustringToString(contextId), attrs.get());
if (!context)
return jsNull();
return toJS(exec, globalObject(), WTF::getPtr(context));
}
示例12:
bool
DirectProxyHandler::isCallable(JSObject* obj) const
{
JSObject * target = obj->as<ProxyObject>().target();
return target->isCallable();
}
示例13: StatsCellCallback
static void
StatsCellCallback(JSRuntime *rt, void *data, void *thing, JSGCTraceKind traceKind,
size_t thingSize)
{
IteratorClosure *closure = static_cast<IteratorClosure *>(data);
RuntimeStats *rtStats = closure->rtStats;
ZoneStats *zStats = rtStats->currZoneStats;
switch (traceKind) {
case JSTRACE_OBJECT: {
JSObject *obj = static_cast<JSObject *>(thing);
CompartmentStats *cStats = GetCompartmentStats(obj->compartment());
if (obj->is<JSFunction>())
cStats->gcHeapObjectsFunction += thingSize;
else if (obj->isArray())
cStats->gcHeapObjectsDenseArray += thingSize;
else if (obj->isCrossCompartmentWrapper())
cStats->gcHeapObjectsCrossCompartmentWrapper += thingSize;
else
cStats->gcHeapObjectsOrdinary += thingSize;
JS::ObjectsExtraSizes objectsExtra;
obj->sizeOfExcludingThis(rtStats->mallocSizeOf_, &objectsExtra);
cStats->objectsExtra.add(objectsExtra);
// JSObject::sizeOfExcludingThis() doesn't measure objectsExtraPrivate,
// so we do it here.
if (ObjectPrivateVisitor *opv = closure->opv) {
nsISupports *iface;
if (opv->getISupports_(obj, &iface) && iface) {
cStats->objectsExtra.private_ += opv->sizeOfIncludingThis(iface);
}
}
break;
}
case JSTRACE_STRING: {
JSString *str = static_cast<JSString *>(thing);
size_t strSize = str->sizeOfExcludingThis(rtStats->mallocSizeOf_);
// If we can't grow hugeStrings, let's just call this string non-huge.
// We're probably about to OOM anyway.
if (strSize >= JS::HugeStringInfo::MinSize() && zStats->hugeStrings.growBy(1)) {
zStats->gcHeapStringsNormal += thingSize;
JS::HugeStringInfo &info = zStats->hugeStrings.back();
info.length = str->length();
info.size = strSize;
PutEscapedString(info.buffer, sizeof(info.buffer), &str->asLinear(), 0);
} else if (str->isShort()) {
MOZ_ASSERT(strSize == 0);
zStats->gcHeapStringsShort += thingSize;
} else {
zStats->gcHeapStringsNormal += thingSize;
zStats->stringCharsNonHuge += strSize;
}
break;
}
case JSTRACE_SHAPE: {
Shape *shape = static_cast<Shape *>(thing);
CompartmentStats *cStats = GetCompartmentStats(shape->compartment());
size_t propTableSize, kidsSize;
shape->sizeOfExcludingThis(rtStats->mallocSizeOf_, &propTableSize, &kidsSize);
if (shape->inDictionary()) {
cStats->gcHeapShapesDict += thingSize;
cStats->shapesExtraDictTables += propTableSize;
JS_ASSERT(kidsSize == 0);
} else {
if (shape->base()->getObjectParent() == shape->compartment()->maybeGlobal()) {
cStats->gcHeapShapesTreeGlobalParented += thingSize;
} else {
cStats->gcHeapShapesTreeNonGlobalParented += thingSize;
}
cStats->shapesExtraTreeTables += propTableSize;
cStats->shapesExtraTreeShapeKids += kidsSize;
}
break;
}
case JSTRACE_BASE_SHAPE: {
BaseShape *base = static_cast<BaseShape *>(thing);
CompartmentStats *cStats = GetCompartmentStats(base->compartment());
cStats->gcHeapShapesBase += thingSize;
break;
}
case JSTRACE_SCRIPT: {
JSScript *script = static_cast<JSScript *>(thing);
CompartmentStats *cStats = GetCompartmentStats(script->compartment());
cStats->gcHeapScripts += thingSize;
cStats->scriptData += script->sizeOfData(rtStats->mallocSizeOf_);
#ifdef JS_ION
size_t baselineData = 0, baselineStubsFallback = 0;
jit::SizeOfBaselineData(script, rtStats->mallocSizeOf_, &baselineData,
&baselineStubsFallback);
cStats->baselineData += baselineData;
cStats->baselineStubsFallback += baselineStubsFallback;
cStats->ionData += jit::SizeOfIonData(script, rtStats->mallocSizeOf_);
#endif
//.........这里部分代码省略.........
示例14: DefineGlobals
bool
DefineGlobals(JSContext *cx, GlobalScope &globalScope, JSScript* script)
{
Root<JSScript*> root(cx, &script);
HandleObject globalObj = globalScope.globalObj;
/* Define and update global properties. */
for (size_t i = 0; i < globalScope.defs.length(); i++) {
GlobalScope::GlobalDef &def = globalScope.defs[i];
/* Names that could be resolved ahead of time can be skipped. */
if (!def.atom)
continue;
jsid id = ATOM_TO_JSID(def.atom);
Value rval;
if (def.funbox) {
JSFunction *fun = def.funbox->function();
/*
* No need to check for redeclarations or anything, global
* optimizations only take place if the property is not defined.
*/
rval.setObject(*fun);
types::AddTypePropertyId(cx, globalObj, id, rval);
} else {
rval.setUndefined();
}
/*
* Don't update the type information when defining the property for the
* global object, per the consistency rules for type properties. If the
* property is only undefined before it is ever written, we can check
* the global directly during compilation and avoid having to emit type
* checks every time it is accessed in the script.
*/
const Shape *shape =
DefineNativeProperty(cx, globalObj, id, rval, JS_PropertyStub, JS_StrictPropertyStub,
JSPROP_ENUMERATE | JSPROP_PERMANENT, 0, 0, DNP_SKIP_TYPE);
if (!shape)
return false;
def.knownSlot = shape->slot();
}
Vector<JSScript *, 16> worklist(cx);
if (!worklist.append(script))
return false;
/*
* Recursively walk through all scripts we just compiled. For each script,
* go through all global uses. Each global use indexes into globalScope->defs.
* Use this information to repoint each use to the correct slot in the global
* object.
*/
while (worklist.length()) {
JSScript *outer = worklist.back();
worklist.popBack();
if (JSScript::isValidOffset(outer->objectsOffset)) {
JSObjectArray *arr = outer->objects();
/*
* If this is an eval script, don't treat the saved caller function
* stored in the first object slot as an inner function.
*/
size_t start = outer->savedCallerFun ? 1 : 0;
for (size_t i = start; i < arr->length; i++) {
JSObject *obj = arr->vector[i];
if (!obj->isFunction())
continue;
JSFunction *fun = obj->toFunction();
JS_ASSERT(fun->isInterpreted());
JSScript *inner = fun->script();
if (outer->function() && outer->function()->isHeavyweight()) {
outer->isOuterFunction = true;
inner->isInnerFunction = true;
}
if (!JSScript::isValidOffset(inner->globalsOffset) &&
!JSScript::isValidOffset(inner->objectsOffset)) {
continue;
}
if (!worklist.append(inner))
return false;
}
}
if (!JSScript::isValidOffset(outer->globalsOffset))
continue;
GlobalSlotArray *globalUses = outer->globals();
uint32_t nGlobalUses = globalUses->length;
for (uint32_t i = 0; i < nGlobalUses; i++) {
uint32_t index = globalUses->vector[i].slot;
JS_ASSERT(index < globalScope.defs.length());
globalUses->vector[i].slot = globalScope.defs[index].knownSlot;
}
}
//.........这里部分代码省略.........
示例15: setDOMException
JSValue JSSQLTransaction::executeSql(ExecState* exec)
{
if (!exec->argumentCount()) {
setDOMException(exec, SYNTAX_ERR);
return jsUndefined();
}
String sqlStatement = ustringToString(exec->argument(0).toString(exec));
if (exec->hadException())
return jsUndefined();
// Now assemble the list of SQL arguments
Vector<SQLValue> sqlValues;
if (!exec->argument(1).isUndefinedOrNull()) {
JSObject* object = exec->argument(1).getObject();
if (!object) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
JSValue lengthValue = object->get(exec, exec->propertyNames().length);
if (exec->hadException())
return jsUndefined();
unsigned length = lengthValue.toUInt32(exec);
if (exec->hadException())
return jsUndefined();
for (unsigned i = 0 ; i < length; ++i) {
JSValue value = object->get(exec, i);
if (exec->hadException())
return jsUndefined();
if (value.isUndefinedOrNull())
sqlValues.append(SQLValue());
else if (value.isNumber())
sqlValues.append(value.uncheckedGetNumber());
else {
// Convert the argument to a string and append it
sqlValues.append(ustringToString(value.toString(exec)));
if (exec->hadException())
return jsUndefined();
}
}
}
RefPtr<SQLStatementCallback> callback;
if (!exec->argument(2).isUndefinedOrNull()) {
JSObject* object = exec->argument(2).getObject();
if (!object) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
callback = JSSQLStatementCallback::create(object, static_cast<JSDOMGlobalObject*>(globalObject()));
}
RefPtr<SQLStatementErrorCallback> errorCallback;
if (!exec->argument(3).isUndefinedOrNull()) {
JSObject* object = exec->argument(3).getObject();
if (!object) {
setDOMException(exec, TYPE_MISMATCH_ERR);
return jsUndefined();
}
errorCallback = JSSQLStatementErrorCallback::create(object, static_cast<JSDOMGlobalObject*>(globalObject()));
}
ExceptionCode ec = 0;
m_impl->executeSQL(sqlStatement, sqlValues, callback.release(), errorCallback.release(), ec);
setDOMException(exec, ec);
return jsUndefined();
}