Search in sources :

Example 61 with ScriptObject

use of com.github.anba.es6draft.runtime.types.ScriptObject in project es6draft by anba.

the class PropertiesTest method createCustomClass.

@Test
public void createCustomClass() {
    Constructor customClass = Properties.createClass(cx, "CustomClass", CustomClass.ConstructorProperties.class, CustomClass.PrototypeProperties.class);
    ScriptObject object = customClass.construct(cx, customClass);
    assertNotNull(object);
}
Also used : ScriptObject(com.github.anba.es6draft.runtime.types.ScriptObject) Constructor(com.github.anba.es6draft.runtime.types.Constructor) OrdinaryCreateFromConstructor(com.github.anba.es6draft.runtime.types.builtins.OrdinaryObject.OrdinaryCreateFromConstructor) Test(org.junit.Test)

Example 62 with ScriptObject

use of com.github.anba.es6draft.runtime.types.ScriptObject in project es6draft by anba.

the class ModuleDeclarationInstantiationGenerator method generate.

private void generate(Module module, SourceTextModuleRecord moduleRecord, InstructionVisitor mv) {
    Variable<ExecutionContext> context = mv.getParameter(EXECUTION_CONTEXT, ExecutionContext.class);
    Variable<SourceTextModuleRecord> moduleRec = mv.getParameter(MODULE, SourceTextModuleRecord.class);
    Variable<LexicalEnvironment<ModuleEnvironmentRecord>> env = mv.getParameter(MODULE_ENV, LexicalEnvironment.class).uncheckedCast();
    Variable<ModuleEnvironmentRecord> envRec = mv.newVariable("envRec", ModuleEnvironmentRecord.class);
    getEnvironmentRecord(env, envRec, mv);
    Variable<ModuleExport> resolved = mv.newVariable("resolved", ModuleExport.class);
    Variable<ScriptObject> namespace = null;
    Variable<FunctionObject> fo = null;
    Variable<Undefined> undef = mv.newVariable("undef", Undefined.class);
    mv.loadUndefined();
    mv.store(undef);
    /* step 9 */
    for (ExportEntry exportEntry : moduleRecord.getIndirectExportEntries()) {
        mv.lineInfo(exportEntry.getLine());
        mv.load(moduleRec);
        mv.aconst(exportEntry.getExportName());
        mv.invoke(Methods.ScriptRuntime_resolveExportOrThrow);
    }
    /* step 12 */
    for (ImportEntry importEntry : moduleRecord.getImportEntries()) {
        mv.lineInfo(importEntry.getLine());
        if (importEntry.isStarImport()) {
            Name localName = new Name(importEntry.getLocalName());
            BindingOp<ModuleEnvironmentRecord> op = BindingOp.of(envRec, localName);
            op.createImmutableBinding(envRec, localName, true, mv);
            mv.load(context);
            mv.load(moduleRec);
            mv.aconst(importEntry.getModuleRequest());
            mv.invoke(Methods.ScriptRuntime_getModuleNamespace);
            if (namespace == null) {
                namespace = mv.newVariable("namespace", ScriptObject.class);
            }
            mv.store(namespace);
            op.initializeBinding(envRec, localName, namespace, mv);
        } else {
            mv.load(moduleRec);
            mv.aconst(importEntry.getModuleRequest());
            mv.aconst(importEntry.getImportName());
            mv.invoke(Methods.ScriptRuntime_resolveImportOrThrow);
            mv.store(resolved);
            createImportBinding(context, envRec, importEntry.getLocalName(), resolved, mv);
        }
    }
    /* step 13 */
    List<StatementListItem> varDeclarations = VarScopedDeclarations(module);
    HashSet<Name> declaredVarNames = new HashSet<>();
    /* step 14 */
    for (StatementListItem d : varDeclarations) {
        assert d instanceof VariableStatement;
        for (Name dn : BoundNames((VariableStatement) d)) {
            if (declaredVarNames.add(dn)) {
                BindingOp<ModuleEnvironmentRecord> op = BindingOp.of(envRec, dn);
                op.createMutableBinding(envRec, dn, false, mv);
                op.initializeBinding(envRec, dn, undef, mv);
            }
        }
    }
    /* step 15 */
    List<Declaration> lexDeclarations = LexicallyScopedDeclarations(module);
    /* step 16 */
    for (Declaration d : lexDeclarations) {
        for (Name dn : BoundNames(d)) {
            BindingOp<ModuleEnvironmentRecord> op = BindingOp.of(envRec, dn);
            if (d.isConstDeclaration()) {
                op.createImmutableBinding(envRec, dn, true, mv);
            } else {
                op.createMutableBinding(envRec, dn, false, mv);
            }
            if (d instanceof HoistableDeclaration) {
                InstantiateFunctionObject(context, env, d, mv);
                if (fo == null) {
                    fo = mv.newVariable("fo", FunctionObject.class);
                }
                mv.store(fo);
                op.initializeBinding(envRec, dn, fo, mv);
            }
        }
    }
    /* step 17 */
    mv._return();
}
Also used : SourceTextModuleRecord(com.github.anba.es6draft.runtime.modules.SourceTextModuleRecord) ScriptObject(com.github.anba.es6draft.runtime.types.ScriptObject) FunctionObject(com.github.anba.es6draft.runtime.types.builtins.FunctionObject) ModuleName(com.github.anba.es6draft.compiler.CodeGenerator.ModuleName) MethodName(com.github.anba.es6draft.compiler.assembler.MethodName) Name(com.github.anba.es6draft.ast.scope.Name) ModuleExport(com.github.anba.es6draft.runtime.modules.ModuleExport) HoistableDeclaration(com.github.anba.es6draft.ast.HoistableDeclaration) HoistableDeclaration(com.github.anba.es6draft.ast.HoistableDeclaration) Declaration(com.github.anba.es6draft.ast.Declaration) ModuleEnvironmentRecord(com.github.anba.es6draft.runtime.ModuleEnvironmentRecord) HashSet(java.util.HashSet) Undefined(com.github.anba.es6draft.runtime.types.Undefined) ExportEntry(com.github.anba.es6draft.runtime.modules.ExportEntry) ImportEntry(com.github.anba.es6draft.runtime.modules.ImportEntry) ExecutionContext(com.github.anba.es6draft.runtime.ExecutionContext) VariableStatement(com.github.anba.es6draft.ast.VariableStatement) LexicalEnvironment(com.github.anba.es6draft.runtime.LexicalEnvironment) StatementListItem(com.github.anba.es6draft.ast.StatementListItem)

Example 63 with ScriptObject

use of com.github.anba.es6draft.runtime.types.ScriptObject in project es6draft by anba.

the class DefaultCodeGenerator method delegatedYield.

private void delegatedYield(Expression node, BiConsumer<Variable<ScriptObject>, Variable<Object>> iterNext, BiConsumer<Variable<ScriptObject>, Variable<Object>> iterThrow, BiConsumer<Variable<ScriptObject>, Variable<Object>> iterReturn, CodeVisitor mv) {
    Jump iteratorNext = new Jump();
    Jump generatorYield = new Jump();
    Jump generatorYieldOrReturn = new Jump();
    Jump done = new Jump();
    mv.lineInfo(node);
    mv.enterVariableScope();
    Variable<ScriptObject> iterator = mv.newVariable("iterator", ScriptObject.class);
    Variable<ScriptObject> innerResult = mv.newVariable("innerResult", ScriptObject.class);
    Variable<Object> received = mv.newVariable("received", Object.class);
    /* steps 3-4 */
    // stack: [value] -> []
    mv.loadExecutionContext();
    mv.swap();
    mv.invoke(Methods.AbstractOperations_GetIterator);
    mv.store(iterator);
    /* step 5 */
    // stack: [] -> []
    mv.loadUndefined();
    mv.store(received);
    /* step 6.a.i-6.a.ii */
    // stack: [] -> []
    mv.mark(iteratorNext);
    iterNext.accept(iterator, received);
    mv.store(innerResult);
    /* steps 6.a.iii-6.a.v */
    // stack: [] -> []
    IteratorComplete(node, innerResult, mv);
    mv.ifne(done);
    /* step 6.a.vi */
    // stack: [] -> [Object(innerResult)]
    // force stack top to Object-type
    mv.mark(generatorYield);
    mv.load(innerResult);
    mv.checkcast(Types.Object);
    mv.suspend();
    mv.store(received);
    /* step 6.b */
    Jump isException = new Jump();
    mv.load(received);
    mv.instanceOf(Types.ScriptException);
    mv.ifeq(isException);
    {
        /* steps 6.b.iii.1-4, 6.b.iv */
        iterThrow.accept(iterator, received);
        mv.store(innerResult);
        mv.goTo(generatorYieldOrReturn);
    }
    mv.mark(isException);
    /* step 6.c */
    mv.load(received);
    mv.instanceOf(Types.ReturnValue);
    mv.ifeq(iteratorNext);
    {
        /* steps 6.c.i-vii */
        iterReturn.accept(iterator, received);
        mv.store(innerResult);
        mv.load(innerResult);
        mv.ifnonnull(generatorYieldOrReturn);
        {
            /* step 6.c.iv */
            mv.popStack();
            mv.returnCompletion(__ -> {
                mv.load(received);
                mv.checkcast(Types.ReturnValue);
                mv.invoke(Methods.ReturnValue_getValue);
            });
        }
    }
    mv.mark(generatorYieldOrReturn);
    /* steps 6.b.iii.5-6, 6.c.viii-ix */
    IteratorComplete(node, innerResult, mv);
    mv.ifeq(generatorYield);
    /* step 6.b.iii.7, 6.c.x */
    mv.popStack();
    mv.returnCompletion(__ -> {
        IteratorValue(node, innerResult, mv);
    });
    /* step 6.a.v */
    mv.mark(done);
    IteratorValue(node, innerResult, mv);
    mv.exitVariableScope();
}
Also used : ScriptObject(com.github.anba.es6draft.runtime.types.ScriptObject) ScriptObject(com.github.anba.es6draft.runtime.types.ScriptObject) OrdinaryObject(com.github.anba.es6draft.runtime.types.builtins.OrdinaryObject) Jump(com.github.anba.es6draft.compiler.assembler.Jump)

Example 64 with ScriptObject

use of com.github.anba.es6draft.runtime.types.ScriptObject in project es6draft by anba.

the class Repl method newRealm.

private Realm newRealm() {
    ObjectAllocator<? extends ShellGlobalObject> allocator;
    if (options.shellMode == ShellMode.Mozilla) {
        allocator = MozShellGlobalObject::new;
    } else if (options.shellMode == ShellMode.V8) {
        allocator = V8ShellGlobalObject::new;
    } else {
        allocator = SimpleShellGlobalObject::new;
    }
    BiFunction<RuntimeContext, ScriptLoader, ModuleLoader> moduleLoader;
    switch(options.moduleLoaderMode) {
        case Default:
            moduleLoader = FileModuleLoader::new;
            break;
        case Node:
            moduleLoader = NodeModuleLoader::new;
            break;
        case NodeStandard:
            moduleLoader = NodeStandardModuleLoader::new;
            break;
        default:
            throw new AssertionError();
    }
    /* @formatter:off */
    RuntimeContext context = new RuntimeContext.Builder().setBaseDirectory(Paths.get("").toAbsolutePath()).setGlobalAllocator(allocator).setModuleLoader(moduleLoader).setConsole(console).setWorkerErrorReporter(this::errorReporter).setOptions(compatibilityOptions(options)).setParserOptions(parserOptions(options)).setCompilerOptions(compilerOptions(options)).build();
    /* @formatter:on */
    World world = new World(context);
    Realm realm = world.newRealm();
    ExecutionContext cx = realm.defaultContext();
    // Add completion to console
    console.addCompleter(new ShellCompleter(realm));
    // Execute global specific initialization
    enqueueScriptTask(realm, () -> {
        InitializeHostDefinedRealm(realm);
        // Add global "arguments" property
        ScriptObject arguments = CreateArrayFromList(cx, options.arguments);
        CreateMethodProperty(cx, realm.getGlobalObject(), "arguments", arguments);
    });
    if (options.console) {
        enqueueScriptTask(realm, () -> {
            ScriptObject console = ConsoleObject.createConsole(realm);
            CreateMethodProperty(cx, realm.getGlobalObject(), "console", console);
        });
    }
    if (options.moduleLoaderMode == ModuleLoaderMode.Node) {
        // TODO: Add default initialize(Realm) method to ModuleLoader interface?
        enqueueScriptTask(realm, () -> {
            NodeModuleLoader nodeLoader = (NodeModuleLoader) world.getModuleLoader();
            nodeLoader.initialize(realm);
        });
    }
    // Run eval expressions and files
    for (EvalScript evalScript : options.evalScripts) {
        if (options.module) {
            enqueueScriptTask(realm, () -> {
                ModuleSource moduleSource = evalScript.getModuleSource();
                SourceIdentifier moduleName = evalScript.getModuleName();
                try {
                    ModuleEvaluationJob(realm, moduleName, moduleSource);
                } catch (ParserException e) {
                    Source source = moduleSource.toSource();
                    String file = e.getFile();
                    if (file.equals(source.getFileString())) {
                        throw new ParserExceptionWithSource(e, source, moduleSource.sourceCode());
                    }
                    Path filePath = Paths.get(file).toAbsolutePath();
                    Source errorSource = new Source(filePath, file, 1);
                    String code = new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8);
                    throw new ParserExceptionWithSource(e, errorSource, code);
                }
            });
        } else {
            enqueueScriptTask(realm, () -> {
                Source source = evalScript.getSource();
                String sourceCode = evalScript.getSourceCode();
                try {
                    eval(realm, parse(realm, source, sourceCode));
                } catch (ParserException e) {
                    throw new ParserExceptionWithSource(e, source, sourceCode);
                }
            });
        }
    }
    return realm;
}
Also used : Path(java.nio.file.Path) ScriptObject(com.github.anba.es6draft.runtime.types.ScriptObject) ParserException(com.github.anba.es6draft.parser.ParserException) ModuleLoader(com.github.anba.es6draft.runtime.modules.ModuleLoader) NodeStandardModuleLoader(com.github.anba.es6draft.repl.loader.NodeStandardModuleLoader) FileModuleLoader(com.github.anba.es6draft.runtime.modules.loader.FileModuleLoader) NodeModuleLoader(com.github.anba.es6draft.repl.loader.NodeModuleLoader) NodeModuleLoader(com.github.anba.es6draft.repl.loader.NodeModuleLoader) SourceIdentifier(com.github.anba.es6draft.runtime.modules.SourceIdentifier) World(com.github.anba.es6draft.runtime.World) MozShellGlobalObject(com.github.anba.es6draft.repl.global.MozShellGlobalObject) ModuleSource(com.github.anba.es6draft.runtime.modules.ModuleSource) NodeStandardModuleLoader(com.github.anba.es6draft.repl.loader.NodeStandardModuleLoader) ExecutionContext(com.github.anba.es6draft.runtime.ExecutionContext) FileModuleLoader(com.github.anba.es6draft.runtime.modules.loader.FileModuleLoader) InitializeHostDefinedRealm(com.github.anba.es6draft.runtime.Realm.InitializeHostDefinedRealm) Realm(com.github.anba.es6draft.runtime.Realm) ModuleSource(com.github.anba.es6draft.runtime.modules.ModuleSource)

Example 65 with ScriptObject

use of com.github.anba.es6draft.runtime.types.ScriptObject in project es6draft by anba.

the class ShellCompleter method complete.

@Override
public Optional<Completion> complete(String line, int cursor) {
    ExecutionContext cx = realm.defaultContext();
    ScriptObject object = realm.getGlobalThis();
    String leftContext = line.substring(0, cursor);
    if (leftContext.isEmpty()) {
        ArrayList<String> candidates = createCandidates(getPropertyNames(cx, object), "", "");
        return Optional.of(new Completion(line, 0, cursor, candidates));
    }
    Matcher m = hierarchyPattern.matcher(leftContext);
    if (!m.find()) {
        return Optional.empty();
    }
    ArrayList<String> segments = segments(m.group(1));
    StringBuilder prefix = new StringBuilder();
    List<String> properties = segments.subList(0, segments.size() - 1);
    if (!properties.isEmpty() && "this".equals(properties.get(0))) {
        // skip leading `this` segment in property traversal
        properties = properties.subList(1, properties.size());
        prefix.append("this.");
    }
    for (String property : properties) {
        if (!HasProperty(cx, object, property)) {
            return Optional.empty();
        }
        Object value = Get(cx, object, property);
        if (Type.isObject(value)) {
            object = Type.objectValue(value);
        } else if (!Type.isUndefinedOrNull(value)) {
            object = ToObject(cx, value);
        } else {
            return Optional.empty();
        }
        prefix.append(property).append('.');
    }
    String partial = segments.get(segments.size() - 1);
    ArrayList<String> candidates = createCandidates(getPropertyNames(cx, object), partial, prefix.toString());
    return Optional.of(new Completion(line, m.start(1), cursor, candidates));
}
Also used : ScriptObject(com.github.anba.es6draft.runtime.types.ScriptObject) ExecutionContext(com.github.anba.es6draft.runtime.ExecutionContext) Completion(com.github.anba.es6draft.repl.console.ShellConsole.Completion) Matcher(java.util.regex.Matcher) ScriptObject(com.github.anba.es6draft.runtime.types.ScriptObject) ToObject(com.github.anba.es6draft.runtime.AbstractOperations.ToObject)

Aggregations

ScriptObject (com.github.anba.es6draft.runtime.types.ScriptObject)129 Callable (com.github.anba.es6draft.runtime.types.Callable)43 Property (com.github.anba.es6draft.runtime.types.Property)32 OrdinaryObject (com.github.anba.es6draft.runtime.types.builtins.OrdinaryObject)26 ArrayObject (com.github.anba.es6draft.runtime.types.builtins.ArrayObject)21 ExecutionContext (com.github.anba.es6draft.runtime.ExecutionContext)16 Constructor (com.github.anba.es6draft.runtime.types.Constructor)11 Realm (com.github.anba.es6draft.runtime.Realm)9 PropertyDescriptor (com.github.anba.es6draft.runtime.types.PropertyDescriptor)9 ParserException (com.github.anba.es6draft.parser.ParserException)8 CompilationException (com.github.anba.es6draft.compiler.CompilationException)7 Source (com.github.anba.es6draft.runtime.internal.Source)7 ArrayList (java.util.ArrayList)7 FunctionObject (com.github.anba.es6draft.runtime.types.builtins.FunctionObject)6 ImmutablePrototypeObject (com.github.anba.es6draft.runtime.types.builtins.ImmutablePrototypeObject)6 OrdinaryCreateFromConstructor (com.github.anba.es6draft.runtime.types.builtins.OrdinaryObject.OrdinaryCreateFromConstructor)6 Test (org.junit.Test)6 GlobalEnvironmentRecord (com.github.anba.es6draft.runtime.GlobalEnvironmentRecord)5 IsCallable (com.github.anba.es6draft.runtime.AbstractOperations.IsCallable)4 RuntimeInfo (com.github.anba.es6draft.runtime.internal.RuntimeInfo)4