Esempio n. 1
0
 public IodineModule(string name)
     : base(ModuleTypeDef)
 {
     Name = name;
     Initializer = new IodineMethod (this, "__init__", false, 0, 0);
     Attributes ["__init__"] = Initializer;
 }
Esempio n. 2
0
 public void SetAttribute(string name, IodineObject value)
 {
     if (value is IodineMethod)
     {
         IodineMethod method = (IodineMethod)value;
         Attributes [name] = new IodineBoundMethod(this, method);
     }
     else if (value is BuiltinMethodCallback)
     {
         BuiltinMethodCallback callback = (BuiltinMethodCallback)value;
         callback.Self     = this;
         Attributes [name] = value;
     }
     else if (value is IodineBoundMethod)
     {
         IodineBoundMethod wrapper = (IodineBoundMethod)value;
         Attributes [name] = new IodineBoundMethod(this, wrapper.Method);
     }
     else if (value is IodineProperty)
     {
         IodineProperty property = (IodineProperty)value;
         Attributes [name] = new IodineProperty(property.Getter, property.Setter, this);
     }
     else
     {
         Attributes [name] = value;
     }
 }
Esempio n. 3
0
        private IodineObject GetBytecode(VirtualMachine vm, IodineObject self, IodineObject[] args)
        {
            if (args.Length == 0)
            {
                vm.RaiseException(new IodineArgumentException(1));
                return(null);
            }

            IodineMethod method = args [0] as IodineMethod;

            if (method == null && args [0] is IodineClosure)
            {
                method = ((IodineClosure)args [0]).Target;
            }

            if (method == null && args [0] is IodineBoundMethod)
            {
                method = ((IodineBoundMethod)args [0]).Method;
            }

            IodineList ret = new IodineList(new IodineObject[] { });

            foreach (Instruction ins in method.Bytecode.Instructions)
            {
                ret.Add(new IodineInstruction(method, ins));
            }

            return(ret);
        }
Esempio n. 4
0
            public IodineInstruction(IodineMethod method, Instruction instruction)
                : base(TypeDefinition)
            {
                Instruction  = instruction;
                parentMethod = method;
                SetAttribute("opcode", new IodineInteger((long)instruction.OperationCode));
                SetAttribute("immediate", new IodineInteger(instruction.Argument));
                if (instruction.Location != null)
                {
                    SetAttribute("line", new IodineInteger(instruction.Location.Line));
                    SetAttribute("col", new IodineInteger(instruction.Location.Column));
                    SetAttribute("file", new IodineString(instruction.Location.File ?? ""));
                }
                else
                {
                    SetAttribute("line", new IodineInteger(0));
                    SetAttribute("col", new IodineInteger(0));
                    SetAttribute("file", new IodineString(""));
                }
                switch (instruction.OperationCode)
                {
                case Opcode.LoadConst:
                case Opcode.StoreGlobal:
                case Opcode.LoadGlobal:
                case Opcode.StoreAttribute:
                case Opcode.LoadAttribute:
                case Opcode.LoadAttributeOrNull:
                    SetAttribute("immediateref", method.Module.ConstantPool [instruction.Argument]);
                    break;

                default:
                    SetAttribute("immediateref", IodineNull.Instance);
                    break;
                }
            }
Esempio n. 5
0
 private void NewFrame(IodineMethod method, IodineObject[] args, IodineObject self)
 {
     frameCount++;
     stackSize++;
     Top = new StackFrame(method.Module, method, args, Top, self);
     frames.Push(Top);
 }
Esempio n. 6
0
 private void NewFrame(IodineMethod method, IodineObject self, int localCount)
 {
     frameCount++;
     stackSize++;
     Top = new StackFrame(method, Top, self, localCount);
     frames.Push(Top);
 }
		private void FindRegion (IodineMethod method, List<ReachableRegion> regions, int start)
		{
			if (IsReachable (regions, start)) {
				return;
			}

			for (int i = start; i < method.Body.Count; i++) {
				Instruction ins = method.Body [i];

				if (ins.OperationCode == Opcode.Jump) {
					regions.Add (new ReachableRegion (start, i));
					FindRegion (method, regions, ins.Argument);
					return;
				} else if (ins.OperationCode == Opcode.JumpIfTrue ||
				           ins.OperationCode == Opcode.JumpIfFalse ||
				           ins.OperationCode == Opcode.PushExceptionHandler) {
					regions.Add (new ReachableRegion (start, i));
					FindRegion (method, regions, i + 1);
					FindRegion (method, regions, ins.Argument);
					return;
				} else if (ins.OperationCode == Opcode.Return) {
					regions.Add (new ReachableRegion (start, i));
					return;
				}
			}
			regions.Add (new ReachableRegion (start, method.Body.Count));
		}
Esempio n. 8
0
 public IodineClass(string name, CodeObject initializer, IodineMethod constructor)
     : base(name)
 {
     Constructor = constructor;
     Initializer = initializer;
     SetAttribute("__doc__", IodineString.Empty);
 }
		private int PerformMethodOptimization (IodineMethod method)
		{
			int removed = 0;
			Instruction[] oldInstructions = method.Body.ToArray ();
			Instruction[] newInstructions = new Instruction[method.Body.Count];
			int next = 0;
			Instruction last = new Instruction ();
			for (int i = 0; i < method.Body.Count; i++) {
				Instruction curr = oldInstructions [i];
				if (i != 0 && curr.OperationCode == Opcode.Pop) {
					if (last.OperationCode == Opcode.LoadLocal || last.OperationCode == Opcode.LoadGlobal
					    || last.OperationCode == Opcode.LoadNull) {
						oldInstructions [i] = new Instruction (curr.Location, Opcode.Nop, 0);
						oldInstructions [i - 1] = new Instruction (curr.Location, Opcode.Nop, 0);
						removed++;
					}
				} else if (curr.OperationCode == Opcode.Jump && curr.Argument == i + 1) {
					oldInstructions [i] = new Instruction (curr.Location, Opcode.Nop, 0);
					removed++;
				}
				last = curr;
			}
			for (int i = 0; i < oldInstructions.Length; i++) {
				Instruction curr = oldInstructions [i];
				if (curr.OperationCode == Opcode.Nop) {
					ShiftLabels (next, newInstructions);
					ShiftLabels (next, oldInstructions);
				} else {
					newInstructions [next++] = curr;
				}
			}
			method.Body.Clear ();
			method.Body.AddRange (newInstructions);
			return removed;
		}
Esempio n. 10
0
 public IodineModule(string name)
     : base(ModuleTypeDef)
 {
     Name                    = name;
     Initializer             = new IodineMethod(this, "__init__", false, 0, 0);
     Attributes ["__init__"] = Initializer;
 }
Esempio n. 11
0
 public void SetAttribute(string name, IodineObject value)
 {
     if (value is IodineMethod)
     {
         IodineMethod method = (IodineMethod)value;
         if (method.InstanceMethod)
         {
             Attributes [name] = new IodineInstanceMethodWrapper(this, method);
         }
         else
         {
             Attributes [name] = value;
         }
     }
     else if (value is IodineInstanceMethodWrapper)
     {
         IodineInstanceMethodWrapper wrapper = (IodineInstanceMethodWrapper)value;
         Attributes [name] = new IodineInstanceMethodWrapper(this, wrapper.Method);
     }
     else if (value is IodineProperty)
     {
         IodineProperty property = (IodineProperty)value;
         Attributes [name] = new IodineProperty(property.Getter, property.Setter, this);
     }
     else
     {
         Attributes [name] = value;
     }
 }
Esempio n. 12
0
		public FunctionCompiler (SymbolTable symbolTable, IodineMethod methodBuilder,
		                         Stack<IodineLabel> breakLabels, Stack<IodineLabel> continueLabels)
		{
			this.symbolTable = symbolTable;
			this.methodBuilder = methodBuilder;
			this.breakLabels = breakLabels;
			this.continueLabels = continueLabels;
		}
Esempio n. 13
0
        public IodineGenerator(StackFrame parentFrame, IodineInstanceMethodWrapper baseMethod,
			IodineObject[] args)
            : base(TypeDef)
        {
            arguments = args;
            self = baseMethod.Self;
            this.baseMethod = baseMethod.Method;
        }
Esempio n. 14
0
 public IodineInstruction(IodineMethod method, Instruction instruction)
     : base(TypeDefinition)
 {
     Instruction  = instruction;
     parentMethod = method;
     SetAttribute("opcode", new IodineInteger((long)instruction.OperationCode));
     SetAttribute("immediate", new IodineInteger(instruction.Argument));
 }
Esempio n. 15
0
 public IodineGenerator(StackFrame parentFrame, IodineInstanceMethodWrapper baseMethod,
                        IodineObject[] args)
     : base(TypeDefinition)
 {
     arguments       = args;
     self            = baseMethod.Self;
     this.baseMethod = baseMethod.Method;
 }
Esempio n. 16
0
			public IodineInstruction (IodineMethod method, Instruction instruction)
				: base (TypeDefinition)
			{
				Instruction = instruction;
				parentMethod = method;
				SetAttribute ("opcode", new IodineInteger ((long)instruction.OperationCode));
				SetAttribute ("immediate", new IodineInteger (instruction.Argument));
			}
Esempio n. 17
0
		public StackFrame (IodineMethod method, StackFrame parent, IodineObject self, int localCount,
		                   IodineObject[] locals) : this (method, parent, self, localCount)
		{
			parentLocals = locals;
			this.locals = new IodineObject[localCount];
			for (int i = 0; i < localCount; i++) {
				this.locals [i] = locals [i]; 
			}
		}
Esempio n. 18
0
		public StackFrame (IodineMethod method, StackFrame parent, IodineObject self, int localCount)
		{
			LocalCount = localCount;
			locals = new IodineObject[localCount];
			parentLocals = locals;
			Method = method;
			Self = self;
			Parent = parent;
		}
Esempio n. 19
0
 public StackFrame(IodineMethod method, StackFrame parent, IodineObject self, int localCount)
 {
     LocalCount   = localCount;
     locals       = new IodineObject[localCount];
     parentLocals = locals;
     Method       = method;
     Self         = self;
     Parent       = parent;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="T:Iodine.Runtime.IodineBoundMethod"/> class.
 /// </summary>
 /// <param name="self">Self.</param>
 /// <param name="method">Method.</param>
 public IodineBoundMethod(IodineObject self, IodineMethod method)
     : base(InstanceTypeDef)
 {
     Method = method;
     SetAttribute("__name__", method.Attributes ["__name__"]);
     SetAttribute("__doc__", method.Attributes ["__doc__"]);
     SetAttribute("__invoke__", method.Attributes ["__invoke__"]);
     Self = self;
 }
Esempio n. 21
0
 public StackFrame(IodineMethod method, StackFrame parent, IodineObject self, int localCount,
                   IodineObject[] locals) : this(method, parent, self, localCount)
 {
     parentLocals = locals;
     this.locals  = new IodineObject[localCount];
     for (int i = 0; i < localCount; i++)
     {
         this.locals [i] = locals [i];
     }
 }
Esempio n. 22
0
		public PatternCompiler (SymbolTable symbolTable,
			IodineMethod methodBuilder,
			int temporary,
			IodineAstVisitor parent)
		{
			parentVisitor = parent;
			this.methodBuilder = methodBuilder;
			this.symbolTable = symbolTable;
			this.temporary = temporary;
		}
Esempio n. 23
0
 public StackFrame(
     IodineModule module,
     IodineMethod method,
     IodineObject[] arguments,
     StackFrame parent,
     IodineObject self,
     AttributeDictionary locals) : this(module, method, arguments, parent, self)
 {
     this.locals = locals;
 }
Esempio n. 24
0
 StackFrame(
     VirtualMachine vm,
     IodineModule module,
     IodineMethod method,
     IodineObject [] arguments,
     StackFrame parent,
     IodineObject self,
     AttributeDictionary locals,
     AttributeDictionary parentLocals) : this(vm, module, method, arguments, parent, self)
 {
     this.parentLocals = parentLocals;
     this.locals       = locals;
 }
Esempio n. 25
0
        /// <summary>
        /// Executes an Iodine method
        /// </summary>
        /// <returns>Value evaluated on return (null if void).</returns>
        /// <param name="method">Method.</param>
        /// <param name="self">self pointer.</param>
        /// <param name="arguments">Arguments.</param>
        public IodineObject InvokeMethod(IodineMethod method, IodineObject self, IodineObject[] arguments)
        {
            int requiredArgs = method.AcceptsKeywordArgs ? method.ParameterCount - 1 : method.ParameterCount;

            if ((method.Variadic && arguments.Length + 1 < requiredArgs) ||
                (!method.Variadic && arguments.Length < requiredArgs))
            {
                RaiseException(new IodineArgumentException(method.ParameterCount));
                return(null);
            }

            NewFrame(method, arguments, self);

            return(Invoke(method, arguments));
        }
Esempio n. 26
0
        public IodineGenerator(StackFrame frame,
                               IodineMethod baseMethod,
                               IodineObject[] args,
                               IodineObject initialValue)
            : base(TypeDefinition)
        {
            arguments       = args;
            value           = initialValue;
            stackFrame      = frame;
            this.baseMethod = baseMethod;

            SetAttribute("__iter__", new BuiltinMethodCallback((VirtualMachine vm, IodineObject self, IodineObject [] arguments) => {
                return(GetIterator(vm));
            }, this));
        }
Esempio n. 27
0
 public StackFrame(
     IodineModule module,
     IodineMethod method,
     IodineObject[] arguments,
     StackFrame parent,
     IodineObject self)
 {
     locals       = new AttributeDictionary();
     parentLocals = locals;
     Method       = method;
     Module       = module;
     Self         = self;
     Arguments    = arguments;
     Parent       = parent;
 }
Esempio n. 28
0
        private IodineObject getBytecode(VirtualMachine vm, IodineObject self, IodineObject[] args)
        {
            IodineMethod method = args [0] as IodineMethod;

            if (method == null && args [0] is IodineClosure)
            {
                method = ((IodineClosure)args [0]).Target;
            }

            IodineList ret = new IodineList(new IodineObject[] { });

            foreach (Instruction ins in method.Body)
            {
                ret.Add(new IodineInstruction(method, ins));
            }
            return(ret);
        }
Esempio n. 29
0
        /// <summary>
        /// Determines whether an object has this trait
        /// </summary>
        /// <returns><c>true</c> if obj has trait; otherwise, <c>false</c>.</returns>
        /// <param name="obj">Object.</param>
        public bool HasTrait(IodineObject obj)
        {
            foreach (IodineMethod method in RequiredMethods)
            {
                if (obj.HasAttribute(method.Name))
                {
                    IodineObject attr = obj.GetAttribute(method.Name);

                    IodineMethod objMethod = attr as IodineMethod;

                    if (objMethod == null)
                    {
                        // HACK: Make builtin methods work
                        if (attr is BuiltinMethodCallback)
                        {
                            continue;
                        }
                        if (attr is IodineBoundMethod)
                        {
                            objMethod = ((IodineBoundMethod)attr).Method;
                        }
                        else
                        {
                            return(false);
                        }
                    }

                    bool match = method.AcceptsKeywordArgs == objMethod.AcceptsKeywordArgs &&
                                 method.Variadic == objMethod.Variadic &&
                                 method.ParameterCount == objMethod.ParameterCount;

                    if (!match)
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
		public void PerformOptimization (IodineMethod method)
		{
			List <ReachableRegion> regions = new List<ReachableRegion> ();
			int reachableSize = 0;
			FindRegion (method, regions, 0);
			foreach (ReachableRegion region in regions) {
				reachableSize += region.Size + 1;
			}
			Instruction[] oldInstructions = method.Body.ToArray ();
			Instruction[] newInstructions = new Instruction[method.Body.Count];
			int next = 0;
			for (int i = 0; i < method.Body.Count; i++) {
				if (IsReachable (regions, i)) {
					newInstructions [next++] = oldInstructions [i];
				} else {
					ShiftLabels (next, oldInstructions);
					ShiftLabels (next, newInstructions);
				}
			}
			method.Body.Clear ();
			method.Body.AddRange (newInstructions);
		}
Esempio n. 31
0
 void StoreNamedParameter(IodineMethod method,
                          IodineObject [] arguments,
                          IodineNamedParameter param,
                          int paramIndex)
 {
     if (param.Name == method.VarargsParameter)
     {
         // Variable list arguments
         IodineObject [] tupleItems = new IodineObject [arguments.Length - paramIndex];
         Array.Copy(arguments, paramIndex, tupleItems, 0, arguments.Length - paramIndex);
         Top.StoreLocalExplicit(param.Name, new IodineTuple(tupleItems));
     }
     else if (param.Name == method.KwargsParameter)
     {
         /*
          * At the moment, keyword arguments are passed to the function as an IodineHashMap,
          */
         if (paramIndex < arguments.Length && arguments [paramIndex] is IodineDictionary)
         {
             Top.StoreLocalExplicit(param.Name, arguments [paramIndex]);
         }
         else
         {
             Top.StoreLocalExplicit(param.Name, new IodineDictionary());
         }
     }
     else
     {
         if (arguments.Length <= paramIndex && method.HasDefaultValues)
         {
             Top.StoreLocalExplicit(param.Name, method.DefaultValues [paramIndex - method.DefaultValuesStartIndex]);
         }
         else
         {
             Top.StoreLocalExplicit(param.Name, arguments [paramIndex++]);
         }
     }
 }
Esempio n. 32
0
        private IodineObject Invoke(IodineMethod method, IodineObject[] arguments)
        {
            if (method.Body.Count > 0)
            {
                currentLocation = method.Body [0].Location;
            }

            int insCount      = method.Body.Count;
            int prevStackSize = stackSize;
            int i             = 0;

            foreach (string param in method.Parameters.Keys)
            {
                if (method.Variadic && (method.AcceptsKeywordArgs ? i == method.Parameters.Keys.Count - 2 :
                                        i == method.Parameters.Keys.Count - 1))
                {
                    IodineObject[] tupleItems = new IodineObject[arguments.Length - i];
                    Array.Copy(arguments, i, tupleItems, 0, arguments.Length - i);
                    Top.StoreLocal(method.Parameters [param], new IodineTuple(tupleItems));
                }
                else if (i == method.Parameters.Keys.Count - 1 && method.AcceptsKeywordArgs)
                {
                    if (i < arguments.Length && arguments [i] is IodineHashMap)
                    {
                        Top.StoreLocal(method.Parameters [param], arguments [i]);
                    }
                    else
                    {
                        Top.StoreLocal(method.Parameters [param], new IodineHashMap());
                    }
                }
                else
                {
                    Top.StoreLocal(method.Parameters [param], arguments [i++]);
                }
            }
            StackFrame top = Top;

            if (traceCallback != null)
            {
                Trace(TraceType.Function, top, currentLocation);
            }

            while (top.InstructionPointer < insCount && !top.AbortExecution && !Top.Yielded)
            {
                instruction = method.Body [Top.InstructionPointer++];
                if (traceCallback != null && instruction.Location.Line != currentLocation.Line)
                {
                    Trace(TraceType.Line, top, instruction.Location);
                }
                ExecuteInstruction();
                top.Location = currentLocation;
            }

            IodineObject retVal = lastObject ?? IodineNull.Instance;

            while (top.DisposableObjects.Count > 0)
            {
                top.DisposableObjects.Pop().Exit(this);
            }

            stackSize = prevStackSize;

            if (top.AbortExecution)
            {
                return(IodineNull.Instance);
            }

            EndFrame();

            return(retVal);
        }
Esempio n. 33
0
 public IodineMethodBuilder(IodineMethod method)
     : base(MethodBuilderTypeDef)
 {
     //this.internalValue = method;
 }
Esempio n. 34
0
		public IodineClosure (StackFrame frame, IodineMethod target)
			: base (TypeDefinition)
		{
			this.frame = frame;
			Target = target;
		}
Esempio n. 35
0
 private IodineMethod compileMethod(FunctionDeclaration funcDecl)
 {
     symbolTable.NextScope ();
     IodineMethod methodBuilder = new IodineMethod (module, funcDecl.Name, funcDecl.InstanceMethod,
                                      funcDecl.Parameters.Count,
                                      symbolTable.CurrentScope.SymbolCount);
     FunctionCompiler compiler = new FunctionCompiler (errorLog, symbolTable,
                                     methodBuilder);
     methodBuilder.Variadic = funcDecl.Variadic;
     methodBuilder.AcceptsKeywordArgs = funcDecl.AcceptsKeywordArgs;
     for (int i = 0; i < funcDecl.Parameters.Count; i++) {
         methodBuilder.Parameters [funcDecl.Parameters [i]] = symbolTable.GetSymbol
             (funcDecl.Parameters [i]).Index;
     }
     funcDecl.Children [0].Visit (compiler);
     methodBuilder.EmitInstruction (Opcode.LoadNull);
     methodBuilder.FinalizeLabels ();
     symbolTable.LeaveScope ();
     return methodBuilder;
 }
Esempio n. 36
0
 public FunctionCompiler(ErrorLog errorLog, SymbolTable symbolTable, IodineMethod methodBuilder)
 {
     this.errorLog = errorLog;
     this.symbolTable = symbolTable;
     this.methodBuilder = methodBuilder;
 }
Esempio n. 37
0
        public IodineObject InvokeMethod(IodineMethod method, StackFrame frame, IodineObject self,
		                                  IodineObject[] arguments)
        {
            int requiredArgs = method.AcceptsKeywordArgs ? method.ParameterCount - 1 :
                method.ParameterCount;
            if ((method.Variadic && arguments.Length + 1 < requiredArgs) ||
                (!method.Variadic && arguments.Length < requiredArgs)) {
                RaiseException (new IodineArgumentException (method.ParameterCount));
                return null;
            }

            NewFrame (frame);
            return Invoke (method, arguments);
        }
Esempio n. 38
0
 public IodineClass(string name, IodineMethod initializer, IodineMethod constructor)
     : base(name)
 {
     Constructor = constructor;
     Initializer = initializer;
 }
Esempio n. 39
0
        private void EvalInstruction()
        {
            if (instruction.Location != null)
            {
                currentLocation = instruction.Location;
            }

            switch (instruction.OperationCode)
            {
            case Opcode.Pop:
            {
                Pop();
                break;
            }

            case Opcode.Dup:
            {
                IodineObject val = Pop();
                Push(val);
                Push(val);
                break;
            }

            case Opcode.LoadConst:
            {
                Push(Top.Module.ConstantPool [instruction.Argument]);
                break;
            }

            case Opcode.LoadNull:
            {
                Push(IodineNull.Instance);
                break;
            }

            case Opcode.LoadSelf:
            {
                Push(Top.Self);
                break;
            }

            case Opcode.LoadTrue:
            {
                Push(IodineBool.True);
                break;
            }

            case Opcode.LoadException:
            {
                Push(lastException);
                break;
            }

            case Opcode.LoadFalse:
            {
                Push(IodineBool.False);
                break;
            }

            case Opcode.StoreLocal:
            {
                string name = ((IodineName)Top.Module.ConstantPool [instruction.Argument]).Value;
                Top.StoreLocal(name, Pop());
                break;
            }

            case Opcode.LoadLocal:
            {
                string name = ((IodineName)Top.Module.ConstantPool [instruction.Argument]).Value;
                Push(Top.LoadLocal(name));
                break;
            }

            case Opcode.StoreGlobal:
            {
                string name = ((IodineName)Top.Module.ConstantPool [instruction.Argument]).Value;
                Top.Module.SetAttribute(this, name, Pop());
                break;
            }

            case Opcode.LoadGlobal:
            {
                string name = ((IodineName)Top.Module.ConstantPool [instruction.Argument]).Value;
                if (name == "_")
                {
                    Push(Top.Module);
                }
                else if (Top.Module.Attributes.ContainsKey(name))
                {
                    Push(Top.Module.GetAttribute(this, name));
                }
                else
                {
                    RaiseException(new IodineAttributeNotFoundException(name));
                }
                break;
            }

            case Opcode.StoreAttribute:
            {
                IodineObject target    = Pop();
                IodineObject value     = Pop();
                string       attribute = ((IodineName)Top.Module.ConstantPool [instruction.Argument]).Value;
                if (target.Attributes.ContainsKey(attribute) &&
                    target.Attributes [attribute] is IIodineProperty)
                {
                    IIodineProperty property = (IIodineProperty)target.Attributes [attribute];
                    property.Set(this, value);
                    break;
                }
                target.SetAttribute(this, attribute, value);
                break;
            }

            case Opcode.LoadAttribute:
            {
                IodineObject target    = Pop();
                string       attribute = ((IodineName)Top.Module.ConstantPool [instruction.Argument]).Value;
                if (target.Attributes.ContainsKey(attribute) &&
                    target.Attributes [attribute] is IIodineProperty)
                {
                    IIodineProperty property = (IIodineProperty)target.Attributes [attribute];
                    Push(property.Get(this));
                    break;
                }
                Push(target.GetAttribute(this, attribute));
                break;
            }

            case Opcode.LoadAttributeOrNull:
            {
                IodineObject target    = Pop();
                string       attribute = ((IodineName)Top.Module.ConstantPool [instruction.Argument]).Value;
                if (target.Attributes.ContainsKey(attribute))
                {
                    Push(target.GetAttribute(this, attribute));
                }
                else
                {
                    Push(IodineNull.Instance);
                }
                break;
            }

            case Opcode.StoreIndex:
            {
                IodineObject index  = Pop();
                IodineObject target = Pop();
                IodineObject value  = Pop();
                target.SetIndex(this, index, value);
                break;
            }

            case Opcode.LoadIndex:
            {
                IodineObject index  = Pop();
                IodineObject target = Pop();
                Push(target.GetIndex(this, index));
                break;
            }

            case Opcode.CastLocal:
            {
                IodineTypeDefinition type = Pop() as IodineTypeDefinition;
                string       name         = ((IodineName)Top.Module.ConstantPool [instruction.Argument]).Value;
                IodineObject o            = Top.LoadLocal(name);
                if (type == null)
                {
                    RaiseException(new IodineTypeException("TypeDef"));
                    break;
                }
                if (o.InstanceOf(type))
                {
                    Push(o);
                }
                else
                {
                    RaiseException(new IodineTypeException(type.Name));
                }
                break;
            }

            case Opcode.BinOp:
            {
                IodineObject op2 = Pop();
                IodineObject op1 = Pop();
                Push(op1.PerformBinaryOperation(this,
                                                (BinaryOperation)instruction.Argument,
                                                op2
                                                ));
                break;
            }

            case Opcode.UnaryOp:
            {
                Push(Pop().PerformUnaryOperation(this,
                                                 (UnaryOperation)instruction.Argument));
                break;
            }

            case Opcode.Invoke:
            {
                IodineObject   target    = Pop();
                IodineObject[] arguments = new IodineObject[instruction.Argument];
                for (int i = 1; i <= instruction.Argument; i++)
                {
                    arguments [instruction.Argument - i] = Pop();
                }
                Push(target.Invoke(this, arguments));
                break;
            }

            case Opcode.InvokeVar:
            {
                IodineObject        target    = Pop();
                List <IodineObject> arguments = new List <IodineObject> ();
                IodineTuple         tuple     = Pop() as IodineTuple;
                if (tuple == null)
                {
                    RaiseException(new IodineTypeException("Tuple"));
                    break;
                }
                for (int i = 0; i < instruction.Argument; i++)
                {
                    arguments.Add(Pop());
                }
                arguments.AddRange(tuple.Objects);
                Push(target.Invoke(this, arguments.ToArray()));
                break;
            }

            case Opcode.InvokeSuper:
            {
                IodineTypeDefinition target    = Pop() as IodineTypeDefinition;
                IodineObject[]       arguments = new IodineObject[instruction.Argument];
                for (int i = 1; i <= instruction.Argument; i++)
                {
                    arguments [instruction.Argument - i] = Pop();
                }

                target.Inherit(this, Top.Self, arguments);
                break;
            }

            case Opcode.Return:
            {
                Top.InstructionPointer = int.MaxValue;
                break;
            }

            case Opcode.Yield:
            {
                Top.Yielded = true;
                break;
            }

            case Opcode.JumpIfTrue:
            {
                if (Pop().IsTrue())
                {
                    Top.InstructionPointer = instruction.Argument;
                }
                break;
            }

            case Opcode.JumpIfFalse:
            {
                if (!Pop().IsTrue())
                {
                    Top.InstructionPointer = instruction.Argument;
                }
                break;
            }

            case Opcode.Jump:
            {
                Top.InstructionPointer = instruction.Argument;
                break;
            }

            case Opcode.BuildClass:
            {
                IodineName   name        = Pop() as IodineName;
                IodineString doc         = Pop() as IodineString;
                IodineMethod constructor = Pop() as IodineMethod;
                //CodeObject initializer = Pop as CodeObject;
                IodineTypeDefinition baseClass  = Pop() as IodineTypeDefinition;
                IodineTuple          interfaces = Pop() as IodineTuple;
                IodineClass          clazz      = new IodineClass(name.ToString(), new CodeObject(), constructor);

                if (baseClass != null)
                {
                    clazz.BaseClass = baseClass;
                    baseClass.BindAttributes(clazz);
                }

                for (int i = 0; i < instruction.Argument; i++)
                {
                    IodineObject val = Pop();
                    IodineObject key = Pop();

                    clazz.Attributes [val.ToString()] = key;
                }

                foreach (IodineObject obj in interfaces.Objects)
                {
                    IodineContract contract = obj as IodineContract;
                    if (!contract.InstanceOf(clazz))
                    {
                        //RaiseException (new IodineTypeException (contract.Name));
                        break;
                    }
                }

                clazz.SetAttribute("__doc__", doc);

                Push(clazz);
                break;
            }

            case Opcode.BuildMixin:
            {
                IodineName name = Pop() as IodineName;

                IodineMixin mixin = new IodineMixin(name.ToString());

                for (int i = 0; i < instruction.Argument; i++)
                {
                    IodineObject val = Pop();
                    IodineObject key = Pop();

                    mixin.Attributes [val.ToString()] = key;
                }

                Push(mixin);
                break;
            }

            case Opcode.BuildEnum:
            {
                IodineName name = Pop() as IodineName;

                IodineEnum ienum = new IodineEnum(name.ToString());
                for (int i = 0; i < instruction.Argument; i++)
                {
                    IodineInteger val = Pop() as IodineInteger;
                    IodineName    key = Pop() as IodineName;
                    ienum.AddItem(key.ToString(), (int)val.Value);
                }

                Push(ienum);
                break;
            }

            case Opcode.BuildContract:
            {
                IodineName name = Pop() as IodineName;

                IodineContract contract = new IodineContract(name.ToString());
                for (int i = 0; i < instruction.Argument; i++)
                {
                    IodineMethod val = Pop() as IodineMethod;
                    contract.AddMethod(val);
                }

                Push(contract);
                break;
            }

            case Opcode.BuildTrait:
            {
                IodineName name = Pop() as IodineName;

                IodineTrait trait = new IodineTrait(name.ToString());
                for (int i = 0; i < instruction.Argument; i++)
                {
                    IodineMethod val = Pop() as IodineMethod;
                    trait.AddMethod(val);
                }

                Push(trait);
                break;
            }

            case Opcode.BuildHash:
            {
                IodineDictionary hash = new IodineDictionary();
                for (int i = 0; i < instruction.Argument; i++)
                {
                    IodineObject val = Pop();
                    IodineObject key = Pop();
                    hash.Set(key, val);
                }
                Push(hash);
                break;
            }

            case Opcode.BuildList:
            {
                IodineObject[] items = new IodineObject[instruction.Argument];
                for (int i = 1; i <= instruction.Argument; i++)
                {
                    items [instruction.Argument - i] = Pop();
                }
                Push(new IodineList(items));
                break;
            }

            case Opcode.BuildTuple:
            {
                IodineObject[] items = new IodineObject[instruction.Argument];
                for (int i = 1; i <= instruction.Argument; i++)
                {
                    items [instruction.Argument - i] = Pop();
                }
                Push(new IodineTuple(items));
                break;
            }

            case Opcode.BuildClosure:
            {
                IodineObject obj    = Pop();
                IodineMethod method = obj as IodineMethod;
                Push(new IodineClosure(Top, method));
                break;
            }

            case Opcode.BuildGenExpr:
            {
                CodeObject method = Pop() as CodeObject;
                Push(new IodineGeneratorExpr(Top, method));
                break;
            }

            case Opcode.Slice:
            {
                IodineObject target = Pop();

                IodineInteger[] arguments = new IodineInteger[3];

                for (int i = 0; i < 3; i++)
                {
                    IodineObject obj = Pop();
                    arguments [i] = obj as IodineInteger;

                    if (obj != IodineNull.Instance && arguments [i] == null)
                    {
                        RaiseException(new IodineTypeException("Int"));
                        break;
                    }
                }

                IodineSlice slice = new IodineSlice(arguments [0], arguments [1], arguments [2]);

                Push(target.Slice(this, slice));

                break;
            }

            case Opcode.MatchPattern:
            {
                IodineObject collection = Pop().GetIterator(this);

                IodineObject[] items = new IodineObject[instruction.Argument];
                for (int i = 1; i <= instruction.Argument; i++)
                {
                    items [instruction.Argument - i] = Pop();
                }


                int index = 0;

                collection.IterReset(this);

                while (collection.IterMoveNext(this) && index < items.Length)
                {
                    IodineObject o = collection.IterGetCurrent(this);

                    if (items [index] is IodineTypeDefinition)
                    {
                        if (!o.InstanceOf(items [index] as IodineTypeDefinition))
                        {
                            Push(IodineBool.False);
                            break;
                        }
                    }
                    else
                    {
                        if (!o.Equals(items [index]))
                        {
                            Push(IodineBool.False);
                            break;
                        }
                    }

                    index++;
                }

                Push(IodineBool.Create(index == items.Length));

                break;
            }

            case Opcode.Unwrap:
            {
                IodineObject container = Pop();

                IodineObject value = container.Unwrap(this);

                if (instruction.Argument > 0)
                {
                    IodineInteger len = value.Len(this) as IodineInteger;

                    if (len == null || len.Value != instruction.Argument)
                    {
                        Push(IodineBool.False);
                        break;
                    }
                }

                Push(value);
                Push(IodineBool.True);

                break;
            }

            case Opcode.Unpack:
            {
                IodineTuple tuple = Pop() as IodineTuple;

                if (tuple == null)
                {
                    RaiseException(new IodineTypeException("Tuple"));
                    break;
                }

                if (tuple.Objects.Length != instruction.Argument)
                {
                    RaiseException(new IodineUnpackException(instruction.Argument));
                    break;
                }
                for (int i = tuple.Objects.Length - 1; i >= 0; i--)
                {
                    Push(tuple.Objects [i]);
                }
                break;
            }

            case Opcode.GetIter:
            {
                Push(Pop().GetIterator(this));
                break;
            }

            case Opcode.IterGetNext:
            {
                Push(Pop().IterGetCurrent(this));
                break;
            }

            case Opcode.IterMoveNext:
            {
                Push(IodineBool.Create(Pop().IterMoveNext(this)));
                break;
            }

            case Opcode.IterReset:
            {
                Pop().IterReset(this);
                break;
            }

            case Opcode.PushExceptionHandler:
            {
                Top.ExceptionHandlers.Push(new IodineExceptionHandler(frameCount, instruction.Argument));
                break;
            }

            case Opcode.PopExceptionHandler:
            {
                Top.ExceptionHandlers.Pop();
                break;
            }

            case Opcode.InstanceOf:
            {
                IodineObject         o    = Pop();
                IodineTypeDefinition type = Pop() as IodineTypeDefinition;
                if (type == null)
                {
                    RaiseException(new IodineTypeException("TypeDef"));
                    break;
                }
                Push(IodineBool.Create(o.InstanceOf(type)));
                break;
            }

            case Opcode.DynamicCast:
            {
                IodineObject         o    = Pop();
                IodineTypeDefinition type = Pop() as IodineTypeDefinition;
                if (type == null)
                {
                    RaiseException(new IodineTypeException("TypeDef"));
                    break;
                }
                if (o.InstanceOf(type))
                {
                    Push(o);
                }
                else
                {
                    Push(IodineNull.Instance);
                }
                break;
            }

            case Opcode.NullCoalesce:
            {
                IodineObject o1 = Pop();
                IodineObject o2 = Pop();
                if (o1 is IodineNull)
                {
                    Push(o2);
                }
                else
                {
                    Push(o1);
                }
                break;
            }

            case Opcode.BeginExcept:
            {
                bool rethrow = true;
                for (int i = 1; i <= instruction.Argument; i++)
                {
                    IodineTypeDefinition type = Pop() as IodineTypeDefinition;
                    if (type == null)
                    {
                        RaiseException(new IodineTypeException("TypeDef"));
                        break;
                    }

                    if (lastException.InstanceOf(type))
                    {
                        rethrow = false;
                        break;
                    }
                }
                if (rethrow)
                {
                    RaiseException(lastException);
                }
                break;
            }

            case Opcode.Raise:
            {
                IodineObject e = Pop();
                if (e.InstanceOf(IodineException.TypeDefinition))
                {
                    RaiseException(e);
                }
                else
                {
                    RaiseException(new IodineTypeException("Exception"));
                }
                break;
            }

            case Opcode.SwitchLookup:
            {
                Dictionary <int, IodineObject> lookup = new Dictionary <int, IodineObject> ();
                int needle = Pop().GetHashCode();
                for (int i = 0; i < instruction.Argument; i++)
                {
                    IodineObject value = Pop();
                    IodineObject key   = Pop();
                    lookup [key.GetHashCode()] = value;
                }
                if (lookup.ContainsKey(needle))
                {
                    lookup [needle].Invoke(this, new IodineObject[] { });
                    Push(IodineBool.True);
                }
                else
                {
                    Push(IodineBool.False);
                }
                break;
            }

            case Opcode.BeginWith:
            {
                IodineObject obj = Pop();
                obj.Enter(this);
                Top.DisposableObjects.Push(obj);
                break;
            }

            case Opcode.EndWith:
            {
                Top.DisposableObjects.Pop().Exit(this);
                break;
            }

            case Opcode.IncludeMixin:
            {
                IodineObject obj  = Pop();
                IodineObject type = Pop();

                foreach (KeyValuePair <string, IodineObject> attr in obj.Attributes)
                {
                    type.SetAttribute(attr.Key, attr.Value);
                }
                break;
            }

            case Opcode.ApplyMixin:
            {
                IodineObject type  = Pop();
                IodineMixin  mixin = Top.Module.ConstantPool [instruction.Argument] as IodineMixin;

                foreach (KeyValuePair <string, IodineObject> attr in mixin.Attributes)
                {
                    type.SetAttribute(attr.Key, attr.Value);
                }
                break;
            }

            case Opcode.BuildFunction:
            {
                MethodFlags flags = (MethodFlags)instruction.Argument;

                IodineString name       = Pop() as IodineString;
                IodineString doc        = Pop() as IodineString;
                CodeObject   bytecode   = Pop() as CodeObject;
                IodineTuple  parameters = Pop() as IodineTuple;

                IodineObject[] defaultValues      = new IodineObject[] { };
                int            defaultValuesStart = 0;

                if (flags.HasFlag(MethodFlags.HasDefaultParameters))
                {
                    IodineTuple   defaultValuesTuple = Pop() as IodineTuple;
                    IodineInteger startInt           = Pop() as IodineInteger;
                    defaultValues      = defaultValuesTuple.Objects;
                    defaultValuesStart = (int)startInt.Value;
                }

                IodineMethod method = new IodineMethod(
                    Top.Module,
                    name,
                    bytecode,
                    parameters,
                    flags,
                    defaultValues,
                    defaultValuesStart
                    );

                method.SetAttribute("__doc__", doc);

                Push(method);

                break;
            }
            }
        }
Esempio n. 40
0
 public void AddInstanceMethod(IodineMethod method)
 {
     SetAttribute(method.Name, method);
 }
Esempio n. 41
0
		public FunctionCompiler (SymbolTable symbolTable, IodineMethod methodBuilder)
		{
			this.symbolTable = symbolTable;
			this.methodBuilder = methodBuilder;
		}
Esempio n. 42
0
 public void AddMethod(IodineMethod method)
 {
     Attributes [method.Name] = method;
 }
Esempio n. 43
0
 public IodineClosure(StackFrame frame, IodineMethod target)
     : base(TypeDefinition)
 {
     this.frame = frame;
     Target     = target;
 }
Esempio n. 44
0
 public void AddInstanceMethod(IodineMethod method)
 {
     SetAttribute (method.Name, method);
 }
Esempio n. 45
0
 public IodineClass(string name, IodineMethod initializer, IodineMethod constructor)
     : base(name)
 {
     Constructor = constructor;
     Initializer = initializer;
 }
Esempio n. 46
0
 public void AddMethod(IodineMethod method)
 {
     RequiredMethods.Add(method);
 }
Esempio n. 47
0
        /*
         * Internal implementation of Invoke
         */
        private IodineObject Invoke(IodineMethod method, IodineObject[] arguments)
        {
            if (method.Bytecode.Instructions.Length > 0)
            {
                currentLocation = method.Bytecode.Instructions [0].Location;
            }

            int insCount      = method.Bytecode.Instructions.Length;
            int prevStackSize = stackSize;
            int i             = 0;

            lastObject = null;

            /*
             * Store function arguments into their respective local variable slots
             */
            foreach (string param in method.Parameters)
            {
                if (param == method.VarargsParameter)
                {
                    // Variable list arguments
                    IodineObject[] tupleItems = new IodineObject[arguments.Length - i];
                    Array.Copy(arguments, i, tupleItems, 0, arguments.Length - i);
                    Top.StoreLocalExplicit(param, new IodineTuple(tupleItems));
                }
                else if (param == method.KwargsParameter)
                {
                    /*
                     * At the moment, keyword arguments are passed to the function as an IodineHashMap,
                     */
                    if (i < arguments.Length && arguments [i] is IodineDictionary)
                    {
                        Top.StoreLocalExplicit(param, arguments [i]);
                    }
                    else
                    {
                        Top.StoreLocalExplicit(param, new IodineDictionary());
                    }
                }
                else
                {
                    if (arguments.Length <= i && method.HasDefaultValues)
                    {
                        Top.StoreLocalExplicit(param, method.DefaultValues [i - method.DefaultValuesStartIndex]);
                    }
                    else
                    {
                        Top.StoreLocalExplicit(param, arguments [i++]);
                    }
                }
            }

            StackFrame top = Top;

            top.Module = method.Module;
            if (traceCallback != null)
            {
                Trace(TraceType.Function, top, currentLocation);
            }

            IodineObject retVal = EvalCode(method.Bytecode);

            if (top.Yielded)
            {
                top.Pop();
            }

            /*
             * Calls __exit__ on any object used in a with statement
             */
            while (!top.Yielded && top.DisposableObjects.Count > 0)
            {
                top.DisposableObjects.Pop().Exit(this);
            }

            stackSize = prevStackSize;

            if (top.AbortExecution)
            {
                /*
                 * If AbortExecution was set, something went wrong and we most likely just
                 * raised an exception. We'll return right here and let what ever catches
                 * the exception clean up the stack
                 */
                return(retVal);
            }

            EndFrame();

            return(retVal);
        }
Esempio n. 48
0
		public override void Accept (FunctionDeclaration funcDecl)
		{
			symbolTable.NextScope ();
			IodineMethod anonMethod = new IodineMethod (methodBuilder, methodBuilder.Module, null, funcDecl.InstanceMethod, 
				                          funcDecl.Parameters.Count, methodBuilder.LocalCount);
			FunctionCompiler compiler = new FunctionCompiler (symbolTable, anonMethod);
			for (int i = 0; i < funcDecl.Parameters.Count; i++) {
				anonMethod.Parameters [funcDecl.Parameters [i]] = symbolTable.GetSymbol
					(funcDecl.Parameters [i]).Index;
			}
			funcDecl.Children [0].Visit (compiler);
			anonMethod.EmitInstruction (funcDecl.Location, Opcode.LoadNull);
			anonMethod.Variadic = funcDecl.Variadic;
			anonMethod.AcceptsKeywordArgs = funcDecl.AcceptsKeywordArgs;
			anonMethod.FinalizeLabels ();
			methodBuilder.EmitInstruction (funcDecl.Location, Opcode.LoadConst,
				methodBuilder.Module.DefineConstant (anonMethod));
			methodBuilder.EmitInstruction (funcDecl.Location, Opcode.BuildClosure);
			methodBuilder.EmitInstruction (funcDecl.Location, Opcode.StoreLocal, symbolTable.GetSymbol (funcDecl.Name).Index);
			symbolTable.LeaveScope ();
		}
Esempio n. 49
0
 private void NewFrame(IodineMethod method, IodineObject self, int localCount)
 {
     frameCount++;
     Top = new StackFrame (method, Top, self, localCount);
     frames.Push (Top);
 }
Esempio n. 50
0
		public override void Accept (LambdaExpression lambda)
		{
			symbolTable.NextScope ();

			int locals = methodBuilder.LocalCount > 0 ? methodBuilder.LocalCount : symbolTable.CurrentScope.SymbolCount;
			IodineMethod anonMethod = new IodineMethod (methodBuilder, methodBuilder.Module, null, lambda.InstanceMethod, 
				                          lambda.Parameters.Count, locals);
			FunctionCompiler compiler = new FunctionCompiler (symbolTable, anonMethod);
			for (int i = 0; i < lambda.Parameters.Count; i++) {
				anonMethod.Parameters [lambda.Parameters [i]] = symbolTable.GetSymbol
					(lambda.Parameters [i]).Index;
			}
			lambda.Children [0].Visit (compiler);
			anonMethod.EmitInstruction (lambda.Location, Opcode.LoadNull);
			anonMethod.Variadic = lambda.Variadic;
			anonMethod.FinalizeLabels ();
			methodBuilder.EmitInstruction (lambda.Location, Opcode.LoadConst,
				methodBuilder.Module.DefineConstant (anonMethod));
			if (methodBuilder.LocalCount > 0) {
				methodBuilder.EmitInstruction (lambda.Location, Opcode.BuildClosure);
			}
			symbolTable.LeaveScope ();
		}
Esempio n. 51
0
        private void ExecuteInstruction()
        {
            currentLocation = instruction.Location;
            switch (instruction.OperationCode)
            {
            case Opcode.Pop:
            {
                Pop();
                break;
            }

            case Opcode.Dup:
            {
                IodineObject val = Pop();
                Push(val);
                Push(val);
                break;
            }

            case Opcode.LoadConst:
            {
                Push(Top.Module.ConstantPool [instruction.Argument]);
                break;
            }

            case Opcode.LoadNull:
            {
                Push(IodineNull.Instance);
                break;
            }

            case Opcode.LoadSelf:
            {
                Push(Top.Self);
                break;
            }

            case Opcode.LoadTrue:
            {
                Push(IodineBool.True);
                break;
            }

            case Opcode.LoadException:
            {
                Push(lastException);
                break;
            }

            case Opcode.LoadFalse:
            {
                Push(IodineBool.False);
                break;
            }

            case Opcode.StoreLocal:
            {
                Top.StoreLocal(instruction.Argument, Pop());
                break;
            }

            case Opcode.LoadLocal:
            {
                Push(Top.LoadLocal(instruction.Argument));
                break;
            }

            case Opcode.StoreGlobal:
            {
                string name = ((IodineName)Top.Module.ConstantPool [instruction.Argument]).Value;
                if (Globals.ContainsKey(name))
                {
                    Globals [name] = Pop();
                }
                else
                {
                    Top.Module.SetAttribute(this, name, Pop());
                }
                break;
            }

            case Opcode.LoadGlobal:
            {
                string name = ((IodineName)Top.Module.ConstantPool [instruction.Argument]).Value;
                if (Top.Module.Attributes.ContainsKey(name))
                {
                    Push(Top.Module.GetAttribute(this, name));
                }
                else if (Globals.ContainsKey(name))
                {
                    Push(Globals [name]);
                }
                else
                {
                    RaiseException(new IodineAttributeNotFoundException(name));
                }
                break;
            }

            case Opcode.StoreAttribute:
            {
                IodineObject target    = Pop();
                IodineObject value     = Pop();
                string       attribute = ((IodineName)Top.Module.ConstantPool [instruction.Argument]).Value;
                if (target.Attributes.ContainsKey(attribute) &&
                    target.Attributes [attribute] is IIodineProperty)
                {
                    IIodineProperty property = (IIodineProperty)target.Attributes [attribute];
                    property.Set(this, value);
                    break;
                }
                target.SetAttribute(this, attribute, value);
                break;
            }

            case Opcode.LoadAttribute:
            {
                IodineObject target    = Pop();
                string       attribute = ((IodineName)Top.Module.ConstantPool [instruction.Argument]).Value;
                if (target.Attributes.ContainsKey(attribute) &&
                    target.Attributes [attribute] is IIodineProperty)
                {
                    IIodineProperty property = (IIodineProperty)target.Attributes [attribute];
                    Push(property.Get(this));
                    break;
                }
                Push(target.GetAttribute(this, attribute));
                break;
            }

            case Opcode.StoreIndex:
            {
                IodineObject index  = Pop();
                IodineObject target = Pop();
                IodineObject value  = Pop();
                target.SetIndex(this, index, value);
                break;
            }

            case Opcode.LoadIndex:
            {
                IodineObject index  = Pop();
                IodineObject target = Pop();
                Push(target.GetIndex(this, index));
                break;
            }

            case Opcode.BinOp:
            {
                IodineObject op2 = Pop();
                IodineObject op1 = Pop();
                Push(op1.PerformBinaryOperation(this,
                                                (BinaryOperation)instruction.Argument,
                                                op2));
                break;
            }

            case Opcode.UnaryOp:
            {
                Push(Pop().PerformUnaryOperation(this,
                                                 (UnaryOperation)instruction.Argument));
                break;
            }

            case Opcode.Invoke:
            {
                IodineObject   target    = Pop();
                IodineObject[] arguments = new IodineObject[instruction.Argument];
                for (int i = 1; i <= instruction.Argument; i++)
                {
                    arguments [instruction.Argument - i] = Pop();
                }
                Push(target.Invoke(this, arguments));
                break;
            }

            case Opcode.InvokeVar:
            {
                IodineObject        target    = Pop();
                List <IodineObject> arguments = new List <IodineObject> ();
                IodineTuple         tuple     = Pop() as IodineTuple;
                if (tuple == null)
                {
                    RaiseException(new IodineTypeException("Tuple"));
                    break;
                }
                for (int i = 0; i < instruction.Argument; i++)
                {
                    arguments.Add(Pop());
                }
                arguments.AddRange(tuple.Objects);
                Push(target.Invoke(this, arguments.ToArray()));
                break;
            }

            case Opcode.InvokeSuper:
            {
                IodineTypeDefinition target    = (IodineTypeDefinition)Pop();
                IodineObject[]       arguments = new IodineObject[instruction.Argument];
                for (int i = 1; i <= instruction.Argument; i++)
                {
                    arguments [instruction.Argument - i] = Pop();
                }
                target.Inherit(this, Top.Self, arguments);
                break;
            }

            case Opcode.Return:
            {
                Top.InstructionPointer = int.MaxValue;
                break;
            }

            case Opcode.Yield:
            {
                Top.Yielded = true;
                break;
            }

            case Opcode.JumpIfTrue:
            {
                if (Pop().IsTrue())
                {
                    Top.InstructionPointer = instruction.Argument;
                }
                break;
            }

            case Opcode.JumpIfFalse:
            {
                if (!Pop().IsTrue())
                {
                    Top.InstructionPointer = instruction.Argument;
                }
                break;
            }

            case Opcode.Jump:
            {
                Top.InstructionPointer = instruction.Argument;
                break;
            }

            case Opcode.BuildHash:
            {
                IodineHashMap hash = new IodineHashMap();
                for (int i = 0; i < instruction.Argument; i++)
                {
                    IodineObject val = Pop();
                    IodineObject key = Pop();
                    hash.Set(key, val);
                }
                Push(hash);
                break;
            }

            case Opcode.BuildList:
            {
                IodineObject[] items = new IodineObject[instruction.Argument];
                for (int i = 1; i <= instruction.Argument; i++)
                {
                    items [instruction.Argument - i] = Pop();
                }
                Push(new IodineList(items));
                break;
            }

            case Opcode.BuildTuple:
            {
                IodineObject[] items = new IodineObject[instruction.Argument];
                for (int i = 1; i <= instruction.Argument; i++)
                {
                    items [instruction.Argument - i] = Pop();
                }
                Push(new IodineTuple(items));
                break;
            }

            case Opcode.BuildClosure:
            {
                IodineMethod method = Pop() as IodineMethod;
                Push(new IodineClosure(Top, method));
                break;
            }

            case Opcode.IterGetNext:
            {
                Push(Pop().IterGetCurrent(this));
                break;
            }

            case Opcode.IterMoveNext:
            {
                Push(IodineBool.Create(Pop().IterMoveNext(this)));
                break;
            }

            case Opcode.IterReset:
            {
                Pop().IterReset(this);
                break;
            }

            case Opcode.PushExceptionHandler:
            {
                Top.ExceptionHandlers.Push(new IodineExceptionHandler(frameCount, instruction.Argument));
                break;
            }

            case Opcode.PopExceptionHandler:
            {
                Top.ExceptionHandlers.Pop();
                break;
            }

            case Opcode.InstanceOf:
            {
                IodineObject         o    = Pop();
                IodineTypeDefinition type = Pop() as IodineTypeDefinition;
                if (type == null)
                {
                    RaiseException(new IodineTypeException("TypeDef"));
                    break;
                }
                Push(IodineBool.Create(o.InstanceOf(type)));
                break;
            }

            case Opcode.DynamicCast:
            {
                IodineObject         o    = Pop();
                IodineTypeDefinition type = Pop() as IodineTypeDefinition;
                if (type == null)
                {
                    RaiseException(new IodineTypeException("TypeDef"));
                    break;
                }
                if (o.InstanceOf(type))
                {
                    Push(o);
                }
                else
                {
                    Push(IodineNull.Instance);
                }
                break;
            }

            case Opcode.NullCoalesce:
            {
                IodineObject o1 = Pop();
                IodineObject o2 = Pop();
                if (o1 is IodineNull)
                {
                    Push(o2);
                }
                else
                {
                    Push(o1);
                }
                break;
            }

            case Opcode.BeginExcept:
            {
                bool rethrow = true;
                for (int i = 1; i <= instruction.Argument; i++)
                {
                    IodineTypeDefinition type = Pop() as IodineTypeDefinition;
                    if (type == null)
                    {
                        RaiseException(new IodineTypeException("TypeDef"));
                        break;
                    }

                    if (lastException.InstanceOf(type))
                    {
                        rethrow = false;
                        break;
                    }
                }
                if (rethrow)
                {
                    RaiseException(lastException);
                }
                break;
            }

            case Opcode.Raise:
            {
                IodineObject e = Pop();
                if (e.InstanceOf(IodineException.TypeDefinition))
                {
                    RaiseException(e);
                }
                else
                {
                    RaiseException(new IodineTypeException("Exception"));
                }
                break;
            }

            case Opcode.SwitchLookup:
            {
                Dictionary <int, IodineObject> lookup = new Dictionary <int, IodineObject> ();
                int needle = Pop().GetHashCode();
                for (int i = 0; i < instruction.Argument; i++)
                {
                    IodineObject value = Pop();
                    IodineObject key   = Pop();
                    lookup [key.GetHashCode()] = value;
                }
                if (lookup.ContainsKey(needle))
                {
                    lookup [needle].Invoke(this, new IodineObject[] { });
                    Push(IodineBool.True);
                }
                else
                {
                    Push(IodineBool.False);
                }
                break;
            }

            case Opcode.BeginWith:
            {
                IodineObject obj = Pop();
                obj.Enter(this);
                Top.DisposableObjects.Push(obj);
                break;
            }

            case Opcode.EndWith:
            {
                Top.DisposableObjects.Pop().Exit(this);
                break;
            }
            }
        }
Esempio n. 52
0
 public IodineGenerator(StackFrame parentFrame, IodineMethod baseMethod, IodineObject[] args)
     : base(TypeDef)
 {
     arguments = args;
     this.baseMethod = baseMethod;
 }
Esempio n. 53
0
		public IodineMethod (IodineMethod parent, IodineModule module, string name, bool isInstance, int parameterCount,
			int localCount) : this (module, name, isInstance, parameterCount, localCount)
		{
			this.parent = parent;
		}
Esempio n. 54
0
        private IodineObject Invoke(IodineMethod method, IodineObject[] arguments)
        {
            if (method.Body.Count > 0) {
                currLoc = method.Body [0].Location;
            }

            int insCount = method.Body.Count;
            int i = 0;
            foreach (string param in method.Parameters.Keys) {
                if (method.Variadic && (method.AcceptsKeywordArgs ? i == method.Parameters.Keys.Count - 2 :
                    i == method.Parameters.Keys.Count - 1)) {
                    IodineObject[] tupleItems = new IodineObject[arguments.Length - i];
                    Array.Copy (arguments, i, tupleItems, 0, arguments.Length - i);
                    Top.StoreLocal (method.Parameters [param], new IodineTuple (tupleItems));
                } else if (i == method.Parameters.Keys.Count - 1 && method.AcceptsKeywordArgs) {
                    if (i < arguments.Length && arguments [i] is IodineHashMap) {
                        Top.StoreLocal (method.Parameters [param], arguments [i]);
                    } else {
                        Top.StoreLocal (method.Parameters [param], new IodineHashMap ());
                    }
                } else {
                    Top.StoreLocal (method.Parameters [param], arguments [i++]);
                }
            }

            StackFrame top = Top;
            while (top.InstructionPointer < insCount && !top.AbortExecution && !Top.Yielded) {
                instruction = method.Body [Top.InstructionPointer++];
                ExecuteInstruction ();
                top.Location = currLoc;
            }

            if (top.AbortExecution) {
                while (top.DisposableObjects.Count > 0) {
                    top.DisposableObjects.Pop ().Exit (this);
                }
                return IodineNull.Instance;
            }

            IodineObject retVal = last ?? IodineNull.Instance;
            EndFrame ();

            while (top.DisposableObjects.Count > 0) {
                top.DisposableObjects.Pop ().Exit (this);
            }

            return retVal;
        }
Esempio n. 55
0
		public IodineInstanceMethodWrapper (IodineObject self, IodineMethod method)
			: base (InstanceTypeDef)
		{
			Method = method;
			Self = self;
		}
		public void PerformOptimization (IodineMethod method)
		{
			while (PerformMethodOptimization (method) > 0)
				;
		}
Esempio n. 57
0
        public IodineClass CompileClass(ClassDeclaration classDecl)
        {
            IodineMethod constructor = compileMethod (classDecl.Constructor);
            if (classDecl.Constructor.Children [0].Children.Count == 0 ||
                !(classDecl.Constructor.Children [0].Children [0] is SuperCallExpression)) {
                if (classDecl.Base.Count > 0) {
                    foreach (string subclass in classDecl.Base) {
                        string[] contract = subclass.Split ('.');
                        constructor.EmitInstruction (classDecl.Location, Opcode.LoadGlobal,
                            constructor.Module.DefineConstant (new IodineName (contract [0])));
                        for (int j = 1; j < contract.Length; j++) {
                            constructor.EmitInstruction (classDecl.Location, Opcode.LoadAttribute,
                                constructor.Module.DefineConstant (new IodineName (contract [0])));
                        }
                        constructor.EmitInstruction (classDecl.Location, Opcode.InvokeSuper, 0);
                    }
                }
            }
            IodineMethod initializer = new IodineMethod (module, "__init__", false, 0, 0);
            IodineClass clazz = new IodineClass (classDecl.Name, initializer, constructor);
            FunctionCompiler compiler = new FunctionCompiler (errorLog, symbolTable,
                clazz.Initializer);

            for (int i = 1; i < classDecl.Children.Count; i++) {
                if (classDecl.Children [i] is FunctionDeclaration) {
                    FunctionDeclaration func = classDecl.Children [i] as FunctionDeclaration;
                    if (func.InstanceMethod)
                        clazz.AddInstanceMethod (compileMethod (func));
                    else {
                        clazz.SetAttribute (func.Name, compileMethod (func));
                    }
                } else if (classDecl.Children [i] is ClassDeclaration) {
                    ClassDeclaration subclass = classDecl.Children [i] as ClassDeclaration;
                    clazz.SetAttribute (subclass.Name, CompileClass (subclass));
                } else if (classDecl.Children [i] is EnumDeclaration) {
                    EnumDeclaration enumeration = classDecl.Children [i] as EnumDeclaration;
                    clazz.SetAttribute (enumeration.Name, CompileEnum (enumeration));
                } else if (classDecl.Children [i] is BinaryExpression) {
                    BinaryExpression expr = classDecl.Children [i] as BinaryExpression;
                    NameExpression name = expr.Left as NameExpression;
                    expr.Right.Visit (compiler);
                    initializer.EmitInstruction (Opcode.LoadGlobal, module.DefineConstant (new
                        IodineName (classDecl.Name)));
                    initializer.EmitInstruction (Opcode.StoreAttribute, module.DefineConstant (new
                        IodineName (name.Value)));
                } else {
                    classDecl.Children [i].Visit (compiler);
                }
            }
            clazz.Initializer.FinalizeLabels ();
            return clazz;
        }
Esempio n. 58
0
		public void AddMethod (IodineMethod method)
		{
			RequiredMethods.Add (method);
		}
Esempio n. 59
0
 public void AddMethod(IodineMethod method)
 {
     Attributes [method.Name] = method;
 }