コード例 #1
0
        void function(Stmt.Function funStmt, FunctionType type)
        {
            /* clox: funDeclaration */
            byte global = 0;

            if (type == FunctionType.TYPE_FUNCTION)
            {
                global = parseVariable(funStmt.name, "Expect function name.");
                markInitialized();
            }


            /* clox: function */
            Compiler_t compiler = new Compiler_t();

            initCompiler(ref compiler, type, funStmt.name);

            captureToken(funStmt.name);

            beginScope();

            // Compile parameter list.
            if (funStmt.params_.Count > 255)
            {
                errorAtCurrent("Cannot have more than 255 parameters.");
            }
            foreach (Token param in funStmt.params_)
            {
                byte paramConstant = parseVariable(param, "Expect parameter name.");
                defineVariable(paramConstant);
            }
            current.function.arity = funStmt.params_.Count;


            // Compile the function body.
            foreach (Stmt stmt in funStmt.body)
            {
                compile(stmt);
            }

            // Create the function object.
            ObjFunction function = endCompiler();

            emitBytes((byte)OpCode.OP_CLOSURE, makeConstant(Value.OBJ_VAL(function)));

            for (int i = 0; i < function.upvalueCount; i++)
            {
                emitByte((byte)(compiler.upvalues[i].isLocal ? 1 : 0));
                emitByte(compiler.upvalues[i].index);
            }

            /* clox: funDeclaration */
            if (type == FunctionType.TYPE_FUNCTION)
            {
                defineVariable(global);
            }
        }
コード例 #2
0
 private static void printFunction(ObjFunction function)
 {
     if (function.name == null)
     {
         System.Console.Write("<script>");
         return;
     }
     System.Console.Write("<fn {0}>", new string(function.name.chars, function.name._start, function.name.length));
 }
コード例 #3
0
        public static ObjFunction newFunction()
        {
            ObjFunction function = (ObjFunction)ALLOCATE_OBJ(ObjType.OBJ_FUNCTION);

            function.arity        = 0;
            function.upvalueCount = 0;
            function.name         = null;
            Chunk.initChunk(ref function.chunk);
            return(function);
        }
コード例 #4
0
        // Generics, <T>, doesn't seem to work with classes?
        static Obj allocateObject(int size, ObjType type)
        {
            Obj object_ = null;

            switch (type)
            {
            case ObjType.OBJ_STRING:
                object_ = new ObjString();
                break;

            case ObjType.OBJ_FUNCTION:
                object_ = new ObjFunction();
                break;

            case ObjType.OBJ_INSTANCE:
                object_ = new ObjInstance();
                break;

            case ObjType.OBJ_NATIVE:
                object_ = new ObjNative();
                break;

            case ObjType.OBJ_CLOSURE:
                object_ = new ObjClosure();
                break;

            case ObjType.OBJ_UPVALUE:
                object_ = new ObjUpvalue();
                break;

            case ObjType.OBJ_CLASS:
                object_ = new ObjClass();
                break;

            case ObjType.OBJ_BOUND_METHOD:
                object_ = new ObjBoundMethod();
                break;

            default:
                object_ = null;    // clox: (Obj*)reallocate(NULL, 0, size);
                break;
            }

            object_.type     = type;
            object_.isMarked = false;

            object_.next  = VM.vm.objects;
            VM.vm.objects = object_;

#if DEBUG_LOG_GC
            System.Console.WriteLine("{0} allocate {1} for {2}", object_._mem_id.ToString(), size.ToString(), type.ToString());
#endif
            return(object_);
        }
コード例 #5
0
        public static ObjClosure newClosure(ObjFunction function)
        {
            ObjUpvalue[] upvalues = Memory.ALLOCATE <ObjUpvalue>(function.upvalueCount);
            for (int i = 0; i < function.upvalueCount; i++)
            {
                upvalues[i] = null;
            }

            ObjClosure closure = (ObjClosure)ALLOCATE_OBJ(ObjType.OBJ_CLOSURE);

            closure.function     = function;
            closure.upvalues     = upvalues;
            closure.upvalueCount = function.upvalueCount;
            return(closure);
        }
コード例 #6
0
        private static ObjFunction endCompiler()
        {
            emitReturn();
            ObjFunction function = current.function;

#if DEBUG_PRINT_CODE
            if (!hadError)
            {
                Chunk_t _chunk = currentChunk();
                Debug.disassembleChunk(ref _chunk, function.name != null ? function.name.chars : "<script>\0".ToCharArray());
            }
#endif

            current = current.enclosing;
            return(function);
        }
コード例 #7
0
        /***  VISITOR COMPILER  ***/

        public ObjFunction compile()
        {
            Compiler_t compiler = new Compiler_t();
            Token      t        = new Token {
                line = 1
            };

            initCompiler(ref compiler, FunctionType.TYPE_SCRIPT, t);

            captureToken(t);

            foreach (Stmt stmt in statements)
            {
                compile(stmt);
            }

            ObjFunction function = endCompiler();

            return(hadError ? null : function);
        }
コード例 #8
0
ファイル: cloxVM.cs プロジェクト: marcelomelofreitas/jcloxcs
        static void runtimeError(string format, params string[] args)
        {
            System.Console.Write(format, args);
            System.Console.WriteLine();

            for (int i = vm.frameCount - 1; i >= 0; i--)
            {
                CallFrame   frame       = vm.frames[i];
                ObjFunction function    = frame.closure.function;
                int         instruction = frame._ip_index - 1;

                // hack fix for undefined variable crash
                if (instruction < 0 || instruction >= function.chunk.lines.Length)
                {
                    System.Console.Write("in ");
                }
                else
                {
                    System.Console.Write("[line {0}] in ", function.chunk.lines[instruction].ToString());
                }

                if (function.name == null)
                {
                    System.Console.WriteLine("script");
                }
                else
                {
                    System.Console.WriteLine("{0}()", new string(function.name.chars, 0, function.name.chars.Length - 1));
                }
            }

#if DEBUG
            System.Console.ReadKey(); // convenience pause
#endif
            resetStack();
        }
コード例 #9
0
ファイル: cloxVM.cs プロジェクト: marcelomelofreitas/jcloxcs
        public static InterpretResult run()
        {
            CallFrame frame = vm.frames[vm.frameCount - 1];

            frame._slot_offset = 0;

            for (;;)
            {
#if DEBUG_TRACE_EXECUTION
                System.Console.Write("          ");
                for (int slot = 0; slot < vm.stackTop; slot++)
                {
                    System.Console.Write("[ ");
                    Value.printValue(vm.stack[slot]);
                    System.Console.Write(" ]");
                }
                System.Console.WriteLine();

                Debug.disassembleInstruction(ref frame.closure.function.chunk, frame._ip_index);
#endif

                OpCode instruction;
                switch (instruction = (OpCode)READ_BYTE(ref frame))
                {
                case OpCode.OP_CONSTANT:
                {
                    Value_t constant = READ_CONSTANT(ref frame);
                    push(constant);
                    break;
                }

                case OpCode.OP_NIL:
                    push(Value.NIL_VAL());
                    break;

                case OpCode.OP_TRUE:
                    push(Value.BOOL_VAL(true));
                    break;

                case OpCode.OP_FALSE:
                    push(Value.BOOL_VAL(false));
                    break;

                case OpCode.OP_POP:
                    pop();
                    break;

                case OpCode.OP_GET_LOCAL:
                {
                    byte slot = READ_BYTE(ref frame);
                    push(frame.slots[frame._slot_offset + slot]);
                    break;
                }

                case OpCode.OP_SET_LOCAL:
                {
                    byte slot = READ_BYTE(ref frame);
                    frame.slots[frame._slot_offset + slot] = peek(0);
                    break;
                }

                case OpCode.OP_GET_GLOBAL:
                {
                    ObjString name  = READ_STRING(ref frame);
                    Value_t   value = new Value_t();
                    if (!Table.tableGet(ref vm.globals, name, ref value))
                    {
                        runtimeError("Undefined variable '{0}'.", new string(name.chars, 0, name.chars.Length - 1));
                        return(InterpretResult.INTERPRET_RUNTIME_ERROR);
                    }
                    push(value);
                    break;
                }

                case OpCode.OP_DEFINE_GLOBAL:
                {
                    ObjString name = READ_STRING(ref frame);
                    Table.tableSet(ref vm.globals, name, peek(0));
                    pop();
                    break;
                }

                case OpCode.OP_SET_GLOBAL:
                {
                    ObjString name = READ_STRING(ref frame);
                    if (Table.tableSet(ref vm.globals, name, peek(0)))
                    {
                        Table.tableDelete(ref vm.globals, name);
                        runtimeError("Undefined variable '{0}'.", new string(name.chars, 0, name.chars.Length - 1));
                        return(InterpretResult.INTERPRET_RUNTIME_ERROR);
                    }
                    break;
                }

                case OpCode.OP_GET_UPVALUE:
                {
                    byte slot = READ_BYTE(ref frame);
                    push(frame.closure.upvalues[slot]._value_src[frame.closure.upvalues[slot].location]);
                    break;
                }

                case OpCode.OP_SET_UPVALUE:
                {
                    byte slot = READ_BYTE(ref frame);
                    frame.closure.upvalues[slot]._value_src[frame.closure.upvalues[slot].location] = peek(0);
                    break;
                }

                case OpCode.OP_GET_PROPERTY:
                {
                    if (!Object.IS_INSTANCE(peek(0)))
                    {
                        runtimeError("Only instances have properties.");
                        return(InterpretResult.INTERPRET_RUNTIME_ERROR);
                    }

                    ObjInstance instance = Object.AS_INSTANCE(peek(0));
                    ObjString   name     = READ_STRING(ref frame);

                    Value_t value = new Value_t();
                    if (Table.tableGet(ref instance.fields, name, ref value))
                    {
                        pop();         // Instance.
                        push(value);
                        break;
                    }

                    if (!bindMethod(instance.klass, name))
                    {
                        return(InterpretResult.INTERPRET_RUNTIME_ERROR);
                    }
                    break;
                }

                case OpCode.OP_SET_PROPERTY:
                {
                    if (!Object.IS_INSTANCE(peek(1)))
                    {
                        runtimeError("Only instances have fields.");
                        return(InterpretResult.INTERPRET_RUNTIME_ERROR);
                    }

                    ObjInstance instance = Object.AS_INSTANCE(peek(1));
                    Table.tableSet(ref instance.fields, READ_STRING(ref frame), peek(0));

                    Value_t value = pop();
                    pop();
                    push(value);
                    break;
                }

                case OpCode.OP_GET_SUPER:
                {
                    ObjString name       = READ_STRING(ref frame);
                    ObjClass  superclass = Object.AS_CLASS(pop());
                    if (!bindMethod(superclass, name))
                    {
                        return(InterpretResult.INTERPRET_RUNTIME_ERROR);
                    }
                    break;
                }

                case OpCode.OP_EQUAL:
                {
                    Value_t b = pop();
                    Value_t a = pop();
                    push(Value.BOOL_VAL(Value.valuesEqual(a, b)));
                    break;
                }

                case OpCode.OP_ADD:
                {
                    if (Object.IS_STRING(peek(0)) && Object.IS_STRING(peek(1)))
                    {
                        concatenate();
                    }
                    else if (Value.IS_NUMBER(peek(0)) && Value.IS_NUMBER(peek(1)))
                    {
                        BINARY_OP(instruction);
                    }
                    else
                    {
                        runtimeError("Operands must be two numbers or two strings.");
                        return(InterpretResult.INTERPRET_RUNTIME_ERROR);
                    }
                }
                break;

                case OpCode.OP_GREATER:
                case OpCode.OP_LESS:
                case OpCode.OP_SUBTRACT:
                case OpCode.OP_MULTIPLY:
                case OpCode.OP_DIVIDE:
                    if (!BINARY_OP(instruction))
                    {
                        return(InterpretResult.INTERPRET_RUNTIME_ERROR);
                    }
                    break;

                case OpCode.OP_NOT:
                    push(Value.BOOL_VAL(isFalsey(pop())));
                    break;

                case OpCode.OP_NEGATE:
                    if (!Value.IS_NUMBER(peek(0)))
                    {
                        runtimeError("Operand must be a number.");
                        return(InterpretResult.INTERPRET_RUNTIME_ERROR);
                    }

                    push(Value.NUMBER_VAL(-Value.AS_NUMBER(pop())));
                    break;

                case OpCode.OP_PRINT:
                {
                    Value.printValue(pop());
                    System.Console.WriteLine();
                    break;
                }

                case OpCode.OP_JUMP:
                {
                    ushort offset = READ_SHORT(ref frame);
                    frame._ip_index += offset;
                    break;
                }

                case OpCode.OP_JUMP_IF_FALSE:
                {
                    ushort offset = READ_SHORT(ref frame);
                    if (isFalsey(peek(0)))
                    {
                        frame._ip_index += offset;
                    }
                    break;
                }

                case OpCode.OP_LOOP:
                {
                    ushort offset = READ_SHORT(ref frame);
                    frame._ip_index -= offset;
                    break;
                }

                case OpCode.OP_CALL:
                {
                    int argCount = READ_BYTE(ref frame);
                    _caller_ip_index = frame._ip_index;
                    if (!callValue(peek(argCount), argCount))
                    {
                        return(InterpretResult.INTERPRET_RUNTIME_ERROR);
                    }
                    frame = vm.frames[vm.frameCount - 1];
                    break;
                }

                case OpCode.OP_INVOKE:
                {
                    ObjString method   = READ_STRING(ref frame);
                    int       argCount = READ_BYTE(ref frame);

                    _caller_ip_index = frame._ip_index;
                    if (!invoke(method, argCount))
                    {
                        return(InterpretResult.INTERPRET_RUNTIME_ERROR);
                    }
                    frame = vm.frames[vm.frameCount - 1];
                    break;
                }

                case OpCode.OP_SUPER_INVOKE:
                {
                    ObjString method     = READ_STRING(ref frame);
                    int       argCount   = READ_BYTE(ref frame);
                    ObjClass  superclass = Object.AS_CLASS(pop());

                    _caller_ip_index = frame._ip_index;
                    if (!invokeFromClass(superclass, method, argCount))
                    {
                        return(InterpretResult.INTERPRET_RUNTIME_ERROR);
                    }
                    frame = vm.frames[vm.frameCount - 1];
                    break;
                }

                case OpCode.OP_CLOSURE:
                {
                    ObjFunction function = Object.AS_FUNCTION(READ_CONSTANT(ref frame));
                    ObjClosure  closure  = Object.newClosure(function);

                    for (int i = 0; i < closure.upvalueCount; i++)
                    {
                        byte isLocal = READ_BYTE(ref frame);
                        byte index   = READ_BYTE(ref frame);
                        if (isLocal != 0)
                        {
                            closure.upvalues[i] = captureUpvalue(frame._slot_offset + index);
                        }
                        else
                        {
                            closure.upvalues[i] = frame.closure.upvalues[index];
                        }
                    }

                    push(Value.OBJ_VAL(closure));         // cs push after modify?

                    break;
                }

                case OpCode.OP_CLOSE_UPVALUE:
                    closeUpvalues(vm.stackTop - 1);
                    pop();
                    break;

                case OpCode.OP_RETURN:
                {
                    Value_t result = pop();
                    closeUpvalues(frame._slot_offset);

                    vm.frameCount--;
                    if (vm.frameCount == 0)
                    {
                        pop();
                        return(InterpretResult.INTERPRET_OK);
                    }

                    vm.stackTop = frame._slot_offset;
                    push(result);

                    frame = vm.frames[vm.frameCount - 1];
                    break;
                }

                case OpCode.OP_CLASS:
                    push(Value.OBJ_VAL(Object.newClass(READ_STRING(ref frame))));
                    break;

                case OpCode.OP_INHERIT:
                {
                    Value_t superclass = peek(1);
                    if (!Object.IS_CLASS(superclass))
                    {
                        runtimeError("Superclass must be a class.");
                        return(InterpretResult.INTERPRET_RUNTIME_ERROR);
                    }

                    ObjClass subclass = Object.AS_CLASS(peek(0));
                    Table.tableAddAll(ref Object.AS_CLASS(superclass).methods, ref subclass.methods);
                    pop();         // Subclass.
                    break;
                }

                case OpCode.OP_METHOD:
                    defineMethod(READ_STRING(ref frame));
                    break;
                }

                vm.frames[vm.frameCount - 1]._ip_index = frame._ip_index; //Csharp reference updating workaround
            }
        }
コード例 #10
0
        private static void freeObject(ref Obj object_)
        {
#if DEBUG_LOG_GC
            System.Console.WriteLine("{0} free type {1}", object_._mem_id.ToString(), object_.type.ToString());
#endif
            switch (object_.type)
            {
            case ObjType.OBJ_BOUND_METHOD:
                object_._free();
                object_ = null;
                break;

            case ObjType.OBJ_CLASS:
            {
                ObjClass klass = (ObjClass)object_;
                Table.freeTable(ref klass.methods);
                //FREE<ObjClass>(ref object_);
                object_._free();
                object_ = null;
                break;
            }

            case ObjType.OBJ_CLOSURE:
            {
                ObjClosure closure = (ObjClosure)object_;
                FREE_ARRAY <ObjUpvalue>(typeof(ObjUpvalue), ref closure.upvalues, closure.upvalueCount);
                object_._free();
                object_ = null;
                break;
            }

            case ObjType.OBJ_FUNCTION:
            {
                ObjFunction function = (ObjFunction)object_;
                Chunk.freeChunk(ref function.chunk);         // the function's byte code
                object_._free();
                object_ = null;
                break;
            }

            case ObjType.OBJ_INSTANCE:
            {
                ObjInstance instance = (ObjInstance)object_;
                Table.freeTable(ref instance.fields);
                object_._free();
                object_ = null;
                break;
            }

            case ObjType.OBJ_NATIVE:
            {
                object_._free();
                object_ = null;
                break;
            }

            case ObjType.OBJ_STRING:
            {
                ObjString string_ = (ObjString)object_;
                FREE_ARRAY <char>(typeof(char), ref string_.chars, string_.length + 1);
                object_._free();
                object_ = null;
                break;
            }

            case ObjType.OBJ_UPVALUE:
                util.cHeap.values.remove(((ObjUpvalue)object_).location);
                object_._free();
                object_ = null;
                break;
            }
        }
コード例 #11
0
        private static void blackenObject(Obj object_)
        {
#if DEBUG_LOG_GC
            System.Console.Write("{0} blacken ", object_._mem_id.ToString());
            Value.printValue(Value.OBJ_VAL(object_));
            System.Console.WriteLine();
#endif

            switch (object_.type)
            {
            case ObjType.OBJ_BOUND_METHOD:
            {
                ObjBoundMethod bound = (ObjBoundMethod)object_;
                markValue(ref bound.receiver);
                markObject((Obj)bound.method);
                break;
            }

            case ObjType.OBJ_CLASS:
            {
                ObjClass klass = (ObjClass)object_;
                markObject((Obj)klass.name);
                Table.markTable(ref klass.methods);
                break;
            }

            case ObjType.OBJ_CLOSURE:
            {
                ObjClosure closure = (ObjClosure)object_;
                markObject((Obj)closure.function);
                for (int i = 0; i < closure.upvalueCount; i++)
                {
                    markObject((Obj)closure.upvalues[i]);
                }
                break;
            }

            case ObjType.OBJ_FUNCTION:
            {
                ObjFunction function = (ObjFunction)object_;
                markObject((Obj)function.name);
                markArray(ref function.chunk.constants);
                break;
            }

            case ObjType.OBJ_INSTANCE:
            {
                ObjInstance instance = (ObjInstance)object_;
                markObject((Obj)(instance.klass));
                Table.markTable(ref instance.fields);
                break;
            }

            case ObjType.OBJ_UPVALUE:
                markValue(ref ((ObjUpvalue)object_).closed);
                break;

            case ObjType.OBJ_NATIVE:
            case ObjType.OBJ_STRING:
                break;
            }
        }