private void AddSymbolToMap(Dictionary <SymbolRef, int> symbolMap, SymbolRef s)
 {
     if (!symbolMap.ContainsKey(s))
     {
         symbolMap.Add(s, symbolMap.Count);
     }
 }
Esempio n. 2
0
        public int Emit_Load(SymbolRef sym)
        {
            switch (sym.Type)
            {
            case SymbolRefType.Global:
                Emit_Load(sym.i_Env);
                AppendInstruction(new Instruction()
                {
                    OpCode = OpCode.Index, String = sym.i_Name
                });
                return(2);

            case SymbolRefType.Local:
                AppendInstruction(new Instruction()
                {
                    OpCode = OpCode.Local, NumVal = sym.i_Index
                });
                return(1);

            case SymbolRefType.Upvalue:
                AppendInstruction(new Instruction()
                {
                    OpCode = OpCode.Upvalue, NumVal = sym.i_Index
                });
                return(1);

            default:
                throw new InternalErrorException("Unexpected symbol type : {0}", sym);
            }
        }
Esempio n. 3
0
        private WatchItem Debugger_RefreshWatch(ScriptExecutionContext context, DynamicExpression dynExpr)
        {
            try
            {
                SymbolRef L = dynExpr.FindSymbol(context);
                DynValue  v = dynExpr.Evaluate(context);

                return(new WatchItem()
                {
                    IsError = dynExpr.IsConstant(),
                    LValue = L,
                    Value = v,
                    Name = dynExpr.ExpressionCode
                });
            }
            catch (Exception ex)
            {
                return(new WatchItem()
                {
                    IsError = true,
                    Value = DynValue.NewString(ex.Message),
                    Name = dynExpr.ExpressionCode
                });
            }
        }
        public ForLoopStatement(ScriptLoadingContext lcontext, Token nameToken, Token forToken)
            : base(lcontext)
        {
            //	for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end |

            // lexer already at the '=' ! [due to dispatching vs for-each]
            CheckTokenType(lcontext, TokenType.Op_Assignment);

            m_Start = Expression.Expr(lcontext);
            CheckTokenType(lcontext, TokenType.Comma);
            m_End = Expression.Expr(lcontext);

            if (lcontext.Lexer.Current.Type == TokenType.Comma)
            {
                lcontext.Lexer.Next();
                m_Step = Expression.Expr(lcontext);
            }
            else
            {
                m_Step = new LiteralExpression(lcontext, DynValue.NewNumber(1));
            }

            lcontext.Scope.PushBlock();
            m_VarName    = lcontext.Scope.DefineLocal(nameToken.Text);
            m_RefFor     = forToken.GetSourceRef(CheckTokenType(lcontext, TokenType.Do));
            m_InnerBlock = new CompositeStatement(lcontext);
            m_RefEnd     = CheckTokenType(lcontext, TokenType.End).GetSourceRef();
            m_StackFrame = lcontext.Scope.PopBlock();

            lcontext.Source.Refs.Add(m_RefFor);
            lcontext.Source.Refs.Add(m_RefEnd);
        }
Esempio n. 5
0
        public SymbolRef Find(string name)
        {
            SymbolRef local = m_Frames.Last().Find(name);

            if (local != null)
            {
                return(local);
            }

            for (int i = m_Frames.Count - 2; i >= 0; i--)
            {
                SymbolRef symb = m_Frames[i].Find(name);

                if (symb != null)
                {
                    symb = CreateUpValue(this, symb, i, m_Frames.Count - 2);

                    if (symb != null)
                    {
                        return(symb);
                    }
                }
            }

            return(CreateGlobalReference(name));
        }
Esempio n. 6
0
        internal void Rename(string name)
        {
            SymbolRef sref = m_DefinedNames[name];

            m_DefinedNames.Remove(name);
            m_DefinedNames.Add(string.Format("@{0}_{1}", name, Guid.NewGuid().ToString("N")), sref);
        }
        internal SymbolRef Define(string name)
        {
            SymbolRef l = SymbolRef.Local(name, -1);

            m_DefinedNames.Add(name, l);
            return(l);
        }
Esempio n. 8
0
        public void AssignGenericSymbol(SymbolRef symref, DynValue value)
        {
            switch (symref.i_Type)
            {
            case SymbolRefType.Global:
                SetGlobalSymbol(GetGenericSymbol(symref.i_Env), symref.i_Name, value);
                break;

            case SymbolRefType.Local:
            {
                CallStackItem stackframe;
                GetTopNonClrFunction(out stackframe);
                stackframe.LocalScope[symref.i_Index] = value;
            }
            break;

            case SymbolRefType.Upvalue:
            {
                CallStackItem stackframe;
                GetTopNonClrFunction(out stackframe);

                stackframe.ClosureScope[symref.i_Index].Set(ref value);
            }
            break;

            case SymbolRefType.DefaultEnv:
            {
                throw new ArgumentException("Can't AssignGenericSymbol on a DefaultEnv symbol");
            }

            default:
                throw new InternalErrorException("Unexpected {0} LRef at resolution: {1}", symref.i_Type, symref.i_Name);
            }
        }
Esempio n. 9
0
		public ForLoopStatement(ScriptLoadingContext lcontext, Token nameToken, Token forToken)
			: base(lcontext)
		{
			//	for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end | 

			// lexer already at the '=' ! [due to dispatching vs for-each]
			CheckTokenType(lcontext, TokenType.Op_Assignment);

			m_Start = Expression.Expr(lcontext);
			CheckTokenType(lcontext, TokenType.Comma);
			m_End = Expression.Expr(lcontext);

			if (lcontext.Lexer.Current.Type == TokenType.Comma)
			{
				lcontext.Lexer.Next();
				m_Step = Expression.Expr(lcontext);
			}
			else
			{
				m_Step = new LiteralExpression(lcontext, DynValue.NewNumber(1));
			}

			lcontext.Scope.PushBlock();
			m_VarName = lcontext.Scope.DefineLocal(nameToken.Text);
			m_RefFor = forToken.GetSourceRef(CheckTokenType(lcontext, TokenType.Do));
			m_InnerBlock = new CompositeStatement(lcontext);
			m_RefEnd = CheckTokenType(lcontext, TokenType.End).GetSourceRef();
			m_StackFrame = lcontext.Scope.PopBlock();

			lcontext.Source.Refs.Add(m_RefFor);
			lcontext.Source.Refs.Add(m_RefEnd);
		}		
        private void ExecStoreLcl(Instruction i)
        {
            DynValue  value  = GetStoreValue(i);
            SymbolRef symref = i.Symbol;

            AssignLocal(symref, value);
        }
Esempio n. 11
0
        public int Emit_Store(SymbolRef sym, int stackofs, int tupleidx)
        {
            switch (sym.Type)
            {
            case SymbolRefType.Global:
                Emit_Load(sym.i_Env);
                AppendInstruction(new Instruction(m_CurrentSourceRef)
                {
                    OpCode = OpCode.IndexSet, Symbol = sym, NumVal = stackofs, NumVal2 = tupleidx, Value = DynValue.NewString(sym.i_Name)
                });
                return(2);

            case SymbolRefType.Local:
                AppendInstruction(new Instruction(m_CurrentSourceRef)
                {
                    OpCode = OpCode.StoreLcl, Symbol = sym, NumVal = stackofs, NumVal2 = tupleidx
                });
                return(1);

            case SymbolRefType.Upvalue:
                AppendInstruction(new Instruction(m_CurrentSourceRef)
                {
                    OpCode = OpCode.StoreUpv, Symbol = sym, NumVal = stackofs, NumVal2 = tupleidx
                });
                return(1);

            default:
                throw new InternalErrorException("Unexpected symbol type : {0}", sym);
            }
        }
Esempio n. 12
0
        public SymbolRefExpression(Token T, ScriptLoadingContext lcontext)
            : base(lcontext)
        {
            m_VarName = T.Text;

            if (T.Type == TokenType.VarArgs)
            {
                m_Ref = lcontext.Scope.TryDefineLocal(WellKnownSymbols.VARARGS);

                if (!lcontext.Scope.CurrentFunctionHasVarArgs())
                {
                    throw new SyntaxErrorException(T, "cannot use '...' outside a vararg function");
                }

                if (lcontext.IsDynamicExpression)
                {
                    throw new DynamicExpressionException("cannot use '...' in a dynamic expression.");
                }
            }
            else
            {
                if (!lcontext.IsDynamicExpression)
                {
                    m_Ref = lcontext.Scope.Find(m_VarName);
                }
            }

            lcontext.Lexer.Next();
        }
Esempio n. 13
0
        public int Emit_Load(SymbolRef sym)
        {
            switch (sym.Type)
            {
            case SymbolRefType.Global:
                Emit_Load(sym.i_Env);
                AppendInstruction(new Instruction(m_CurrentSourceRef)
                {
                    OpCode = OpCode.Index, Value = DynValue.NewString(sym.i_Name)
                });
                return(2);

            case SymbolRefType.Local:
                AppendInstruction(new Instruction(m_CurrentSourceRef)
                {
                    OpCode = OpCode.Local, Symbol = sym
                });
                return(1);

            case SymbolRefType.Upvalue:
                AppendInstruction(new Instruction(m_CurrentSourceRef)
                {
                    OpCode = OpCode.Upvalue, Symbol = sym
                });
                return(1);

            default:
                throw new InternalErrorException("Unexpected symbol type : {0}", sym);
            }
        }
Esempio n. 14
0
        public ForLoopStatement(LuaParser.Stat_forloopContext context, ScriptLoadingContext lcontext)
            : base(context, lcontext)
        {
            var exps = context.exp();

            m_Start = NodeFactory.CreateExpression(exps[0], lcontext);
            m_End   = NodeFactory.CreateExpression(exps[1], lcontext);

            if (exps.Length > 2)
            {
                m_Step = NodeFactory.CreateExpression(exps[2], lcontext);
            }
            else
            {
                m_Step = new LiteralExpression(context, lcontext, DynValue.NewNumber(1));
            }

            lcontext.Scope.PushBlock();
            m_VarName    = lcontext.Scope.DefineLocal(context.NAME().GetText());
            m_InnerBlock = NodeFactory.CreateStatement(context.block(), lcontext);
            m_StackFrame = lcontext.Scope.PopBlock();

            m_RefFor = BuildSourceRef(context.Start, context.FOR());
            m_RefEnd = BuildSourceRef(context.Stop, context.END());
        }
        internal SymbolRef Define(string name)
        {
            var l = SymbolRef.Local(name, -1);

            _definedNames.Add(name, l);
            _lastDefinedName = name;
            return(l);
        }
		internal int Dump(Stream stream, int baseAddress, bool hasUpvalues)
		{
			using (BinaryWriter bw = new BinDumpBinaryWriter(stream, Encoding.UTF8))
			{
				Dictionary<SymbolRef, int> symbolMap = new Dictionary<SymbolRef, int>();

				Instruction meta = FindMeta(ref baseAddress);

				if (meta == null)
					throw new ArgumentException("baseAddress");

				bw.Write(DUMP_CHUNK_MAGIC);
				bw.Write(DUMP_CHUNK_VERSION);
				bw.Write(hasUpvalues);
				bw.Write(meta.NumVal);

				for (int i = 0; i <= meta.NumVal; i++)
				{
					SymbolRef[] symbolList;
					SymbolRef symbol;

					m_RootChunk.Code[baseAddress + i].GetSymbolReferences(out symbolList, out symbol);

					if (symbol != null)
						AddSymbolToMap(symbolMap, symbol);

					if (symbolList != null)
						foreach (var s in symbolList)
							AddSymbolToMap(symbolMap, s);
				}

				foreach (SymbolRef sr in symbolMap.Keys.ToArray())
				{
					if (sr.i_Env != null)
						AddSymbolToMap(symbolMap, sr.i_Env);
				}

				SymbolRef[] allSymbols = new SymbolRef[symbolMap.Count];

				foreach (KeyValuePair<SymbolRef, int> pair in symbolMap)
				{
					allSymbols[pair.Value] = pair.Key;
				}

				bw.Write(symbolMap.Count);

				foreach (SymbolRef sym in allSymbols)
					sym.WriteBinary(bw);

				foreach (SymbolRef sym in allSymbols)
					sym.WriteBinaryEnv(bw, symbolMap);

				for (int i = 0; i <= meta.NumVal; i++)
					m_RootChunk.Code[baseAddress + i].WriteBinary(bw, baseAddress, symbolMap);

				return meta.NumVal + baseAddress + 1;
			}
		}
Esempio n. 17
0
        /// <summary>
        /// Tries to get the reference of a symbol in the current execution state
        /// </summary>
        public DynValue EvaluateSymbol(SymbolRef symref)
        {
            if (symref == null)
            {
                return(DynValue.Nil);
            }

            return(m_Processor.GetGenericSymbol(symref));
        }
Esempio n. 18
0
        public SymbolRefExpression(ScriptLoadingContext lcontext, SymbolRef refr) : base(lcontext)
        {
            _ref = refr;

            if (lcontext.IsDynamicExpression)
            {
                throw new DynamicExpressionException("Unsupported symbol reference expression detected.");
            }
        }
Esempio n. 19
0
		private SymbolRef CreateUpValue(BuildTimeScope buildTimeScope, SymbolRef symb, int closuredFrame, int currentFrame)
		{
			// it's a 0-level upvalue. Just create it and we're done.
			if (closuredFrame == currentFrame)
				return m_ClosureBuilders[currentFrame + 1].CreateUpvalue(this, symb);

			SymbolRef upvalue = CreateUpValue(buildTimeScope, symb, closuredFrame, currentFrame - 1);

			return m_ClosureBuilders[currentFrame + 1].CreateUpvalue(this, upvalue);
		}
Esempio n. 20
0
		public SymbolRefExpression(ScriptLoadingContext lcontext, SymbolRef refr)
			: base(lcontext)
		{
			m_Ref = refr;

			if (lcontext.IsDynamicExpression)
			{
				throw new DynamicExpressionException("Unsupported symbol reference expression detected.");
			}
		}
Esempio n. 21
0
        public SymbolRefExpression(ITerminalNode terminalNode, ScriptLoadingContext lcontext)
            : base(terminalNode, lcontext)
        {
            m_VarName = terminalNode.GetText();

            if (!lcontext.IsDynamicExpression)
            {
                m_Ref = lcontext.Scope.Find(m_VarName);
            }
        }
		public FunctionDefinitionStatement(LuaParser.Stat_localfuncdefContext context, ScriptLoadingContext lcontext)
			: base(context, lcontext)
		{
			m_Local = true;
			m_FuncSymbol = lcontext.Scope.TryDefineLocal(context.NAME().GetText());
			m_FuncDef = new FunctionDefinitionExpression(context.funcbody(), lcontext, context);

			m_SourceRef = BuildSourceRef(context.Start, context.Stop);

			m_FriendlyName = string.Format("{0} (local)", m_FuncSymbol.i_Name);
		}
Esempio n. 23
0
        public SymbolRef CreateGlobalReference(string name)
        {
            if (name == WellKnownSymbols.ENV)
            {
                throw new InternalErrorException("_ENV passed in CreateGlobalReference");
            }

            SymbolRef env = Find(WellKnownSymbols.ENV);

            return(SymbolRef.Global(name, env));
        }
        public FunctionDefinitionExpression(LuaParser.FuncbodyContext context, ScriptLoadingContext lcontext,
                                            ParserRuleContext declarationContext,
                                            bool pushSelfParam = false, Table globalContext = null)
            : base(context, lcontext)
        {
            var           parlist    = context.parlist();
            List <string> paramnames = new List <string>();

            if (pushSelfParam)
            {
                paramnames.Add("self");
            }


            if (parlist != null)
            {
                var namelist = parlist.namelist();

                if (namelist != null)
                {
                    paramnames.AddRange(namelist.NAME()
                                        .Select(t => t.GetText()));
                }
            }

            m_HasVarArgs = (parlist != null && parlist.vararg() != null);

            if (m_HasVarArgs)
            {
                paramnames.Add(WellKnownSymbols.VARARGS);
            }

            lcontext.Scope.PushFunction(this, m_HasVarArgs);

            if (globalContext != null)
            {
                m_GlobalEnv = globalContext;
                m_Env       = lcontext.Scope.TryDefineLocal(WellKnownSymbols.ENV);
            }
            else
            {
                lcontext.Scope.ForceEnvUpValue();
            }

            m_ParamNames = DefineArguments(paramnames, lcontext);

            m_Statement = NodeFactory.CreateStatement(context.block(), lcontext);

            m_StackFrame = lcontext.Scope.PopFunction();

            m_Begin = BuildSourceRef(declarationContext.Start, context.PAREN_CLOSE().Symbol);
            m_End   = BuildSourceRef(context.Stop, context.END());
        }
Esempio n. 25
0
        public ChunkStatement(LuaParser.ChunkContext context, ScriptLoadingContext lcontext, Table globalEnv)
            : base(context, lcontext)
        {
            lcontext.Scope.PushFunction(this, true);
            m_Env     = lcontext.Scope.DefineLocal(WellKnownSymbols.ENV);
            m_VarArgs = lcontext.Scope.DefineLocal(WellKnownSymbols.VARARGS);

            m_GlobalEnv = globalEnv;

            m_Block      = NodeFactory.CreateStatement(context.block(), lcontext);
            m_StackFrame = lcontext.Scope.PopFunction();
        }
Esempio n. 26
0
        private SymbolRef CreateUpValue(BuildTimeScope buildTimeScope, SymbolRef symb, int closuredFrame, int currentFrame)
        {
            // it's a 0-level upvalue. Just create it and we're done.
            if (closuredFrame == currentFrame)
            {
                return(m_ClosureBuilders[currentFrame + 1].CreateUpvalue(this, symb));
            }

            SymbolRef upvalue = CreateUpValue(buildTimeScope, symb, closuredFrame, currentFrame - 1);

            return(m_ClosureBuilders[currentFrame + 1].CreateUpvalue(this, upvalue));
        }
Esempio n. 27
0
        public override Symbol CreateModel()
        {
            var sym = new Symbol()
            {
                LastModificationDate = DateTime.UtcNow,
                CreationDate         = DateTime.UtcNow,
                Path = Path,
                Type = new Data.Models.Symbols.Type()
                {
                    Name = Type
                },
                Import = Import != null ? new Data.Models.Symbols.Import()
                {
                    Name = Import
                } : null
            };

            foreach (var proto in Prototypes)
            {
                var p = new Data.Models.Symbols.Prototype
                {
                    Data        = proto.Proto,
                    Description = proto.Description,
                    Symbol      = sym
                };
                foreach (var par in proto.Parameters)
                {
                    var param = new PrototypeParam()
                    {
                        Data        = par.Proto,
                        Description = par.Description,
                        SymbolRef   = par.Ref != null ? new PrototypeParamSymbolRef()
                        {
                            RefPath = par.Ref
                        } : null,
                        Prototype = p
                    };
                    p.Parameters.Add(param);
                }
                sym.Prototypes.Add(p);
            }
            foreach (var sref in Symbols)
            {
                var symRef = new SymbolRef()
                {
                    RefPath = sref,
                    Symbol  = sym
                };
                sym.Symbols.Add(symRef);
            }
            return(sym);
        }
Esempio n. 28
0
        public ForLoopStatement(ScriptLoadingContext lcontext, Token nameToken, Token forToken) : base(lcontext)
        {
            //	for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end |

            // lexer already at the '=' ! [due to dispatching vs for-each]
            CheckTokenType(lcontext, TokenType.Op_Assignment);

            m_Start = Expression.Expr(lcontext);
            CheckTokenType(lcontext, TokenType.Comma, TokenType.SemiColon);

            if (CheckTokenTypeAndDiscardIfMatch(lcontext, TokenType.Name, nameToken.Text))
            {
                CheckTokenTypeAndDiscardIfNot(lcontext, TokenTypeUtils.operators);
            }

            m_End = Expression.Expr(lcontext);

            if (lcontext.Lexer.Current.Type == TokenType.Comma || lcontext.Lexer.Current.Type == TokenType.SemiColon)
            {
                lcontext.Lexer.Next();

                if (CheckTokenTypeAndDiscardIfMatch(lcontext, TokenType.Name, nameToken.Text))
                {
                    Token stepToken  = CheckTokenTypeAndDiscard(lcontext, TokenTypeUtils.operators);
                    Token stepToken2 = CheckTokenTypeAndDiscardIfNot(lcontext, TokenTypeUtils.operators);

                    if (stepToken != null && TokenTypeUtils.IsOpToken(stepToken.Type))
                    {
                        stepOp = stepToken.Type;
                    }
                }

                m_Step = Expression.Expr(lcontext);
            }
            else
            {
                m_Step = new LiteralExpression(lcontext, DynValue.NewNumber(1));
            }

            lcontext.Scope.PushBlock();
            m_VarName = lcontext.Scope.DefineLocal(nameToken.Text);

            forToken.GetSourceRef(CheckTokenTypeAndDiscard(lcontext, TokenType.Brk_Close_Round));

            m_RefFor     = forToken.GetSourceRef(CheckTokenType(lcontext, TokenType.Do));
            m_InnerBlock = new CompositeStatement(lcontext);
            m_RefEnd     = CheckTokenType(lcontext, TokenType.End).GetSourceRef();
            m_StackFrame = lcontext.Scope.PopBlock();

            lcontext.Source.Refs.Add(m_RefFor);
            lcontext.Source.Refs.Add(m_RefEnd);
        }
Esempio n. 29
0
        public override int GetHashCode()
        {
            int hashCode = 0;

            if (SymbolRef != null)
            {
                hashCode = SymbolRef.GetHashCode();
            }
            hashCode ^= Length;
            hashCode ^= (int)FormatType;
            hashCode ^= (int)FormatSubType;
            return(hashCode);
        }
        private void AssignLocal(SymbolRef symref, DynValue value)
        {
            var stackframe = m_ExecutionStack.Peek();

            DynValue v = stackframe.LocalScope[symref.i_Index];

            if (v == null)
            {
                stackframe.LocalScope[symref.i_Index] = v = DynValue.NewNil();
            }

            v.Assign(value);
        }
Esempio n. 31
0
		public ChunkStatement(ScriptLoadingContext lcontext)
			: base(lcontext)
		{
			lcontext.Scope.PushFunction(this, true);
			m_Env = lcontext.Scope.DefineLocal(WellKnownSymbols.ENV);
			m_VarArgs = lcontext.Scope.DefineLocal(WellKnownSymbols.VARARGS);

			m_Block = new CompositeStatement(lcontext);

			if (lcontext.Lexer.Current.Type != TokenType.Eof)
				throw new SyntaxErrorException(lcontext.Lexer.Current, "<eof> expected near '{0}'", lcontext.Lexer.Current.Text);

			m_StackFrame = lcontext.Scope.PopFunction();
		}
Esempio n. 32
0
        internal SymbolRef Find(string name)
        {
            for (var tree = m_ScopeTreeHead; tree != null; tree = tree.Parent)
            {
                SymbolRef l = tree.Find(name);

                if (l != null)
                {
                    return(l);
                }
            }

            return(null);
        }
Esempio n. 33
0
        private VariableRef GetVariable(string name)
        {
            SymbolRef ret = GetScope()[name];

            if (ret == null)
            {
                Error(string.Format("Unknown variable: \"{0}\"", name));
            }
            if (!(ret is VariableRef))
            {
                Error(string.Format("{0} is a function, but is used like a variable", name));
            }

            return(ret as VariableRef);
        }
Esempio n. 34
0
        public SymbolRefExpression(LuaParser.VarargContext context, ScriptLoadingContext lcontext)
            : base(context, lcontext)
        {
            m_Ref = lcontext.Scope.TryDefineLocal(WellKnownSymbols.VARARGS);

            if (!lcontext.Scope.CurrentFunctionHasVarArgs())
            {
                throw new SyntaxErrorException("error:0: cannot use '...' outside a vararg function");
            }

            if (lcontext.IsDynamicExpression)
            {
                throw new DynamicExpressionException("Cannot use '...' in a dynamic expression.");
            }
        }
Esempio n. 35
0
        private FunctionRef GetFunction(string name)
        {
            SymbolRef ret = GetScope()[name];

            if (ret == null)
            {
                Error(string.Format("Unknown function: \"{0}\"", name));
            }
            if (!(ret is FunctionRef))
            {
                Error(string.Format("{0} is a variable, but is used like a function", name));
            }

            return(ret as FunctionRef);
        }
Esempio n. 36
0
		public DynValue GetGenericSymbol(SymbolRef symref)
		{
			switch (symref.i_Type)
			{
				case  SymbolRefType.DefaultEnv:
					return DynValue.NewTable(this.GetScript().Globals);
				case SymbolRefType.Global:
					return GetGlobalSymbol(GetGenericSymbol(symref.i_Env), symref.i_Name);
				case SymbolRefType.Local:
					return GetTopNonClrFunction().LocalScope[symref.i_Index];
				case SymbolRefType.Upvalue:
					return GetTopNonClrFunction().ClosureScope[symref.i_Index];
				default:
					throw new InternalErrorException("Unexpected {0} LRef at resolution: {1}", symref.i_Type, symref.i_Name);
			}
		}
        public SymbolRef CreateUpvalue(BuildTimeScope scope, SymbolRef symbol)
        {
            for (var i = 0; i < m_Closure.Count; i++)
            {
                if (m_Closure[i].i_Name == symbol.i_Name)
                {
                    return SymbolRef.Upvalue(symbol.i_Name, i);
                }
            }

            m_Closure.Add(symbol);

            if (m_ClosureInstruction != null)
            {
                m_ClosureInstruction.SymbolList = m_Closure.ToArray();
            }

            return SymbolRef.Upvalue(symbol.i_Name, m_Closure.Count - 1);
        }
        private FunctionDefinitionExpression(ScriptLoadingContext lcontext, bool pushSelfParam, Table globalContext,
            bool isLambda)
            : base(lcontext)
        {
            if (globalContext != null)
                CheckTokenType(lcontext, TokenType.Function);

            // here lexer should be at the '(' or at the '|'
            var openRound = CheckTokenType(lcontext, isLambda ? TokenType.Lambda : TokenType.Brk_Open_Round);

            var paramnames = BuildParamList(lcontext, pushSelfParam, openRound, isLambda);
            // here lexer is at first token of body

            m_Begin = openRound.GetSourceRefUpTo(lcontext.Lexer.Current);

            // create scope
            lcontext.Scope.PushFunction(this, m_HasVarArgs);

            if (globalContext != null)
            {
                m_GlobalEnv = globalContext;
                m_Env = lcontext.Scope.TryDefineLocal(WellKnownSymbols.ENV);
            }
            else
            {
                lcontext.Scope.ForceEnvUpValue();
            }

            m_ParamNames = DefineArguments(paramnames, lcontext);

            if (isLambda)
                m_Statement = CreateLambdaBody(lcontext);
            else
                m_Statement = CreateBody(lcontext);

            m_StackFrame = lcontext.Scope.PopFunction();

            lcontext.Source.Refs.Add(m_Begin);
            lcontext.Source.Refs.Add(m_End);
        }
Esempio n. 39
0
        public void AssignGenericSymbol(SymbolRef symref, DynValue value)
        {
            switch (symref.i_Type)
            {
                case SymbolRefType.Global:
                    SetGlobalSymbol(GetGenericSymbol(symref.i_Env), symref.i_Name, value);
                    break;
                case SymbolRefType.Local:
                {
                    var stackframe = GetTopNonClrFunction();

                    var v = stackframe.LocalScope[symref.i_Index];
                    if (v == null)
                        stackframe.LocalScope[symref.i_Index] = v = DynValue.NewNil();

                    v.Assign(value);
                }
                    break;
                case SymbolRefType.Upvalue:
                {
                    var stackframe = GetTopNonClrFunction();

                    var v = stackframe.ClosureScope[symref.i_Index];
                    if (v == null)
                        stackframe.ClosureScope[symref.i_Index] = v = DynValue.NewNil();

                    v.Assign(value);
                }
                    break;
                case SymbolRefType.DefaultEnv:
                {
                    throw new ArgumentException("Can't AssignGenericSymbol on a DefaultEnv symbol");
                }
                default:
                    throw new InternalErrorException("Unexpected {0} LRef at resolution: {1}", symref.i_Type,
                        symref.i_Name);
            }
        }
Esempio n. 40
0
		public SymbolRefExpression(Token T, ScriptLoadingContext lcontext)
			: base(lcontext)
		{
			m_VarName = T.Text;

			if (T.Type == TokenType.VarArgs)
			{
				m_Ref = lcontext.Scope.Find(WellKnownSymbols.VARARGS);

				if (!lcontext.Scope.CurrentFunctionHasVarArgs())
					throw new SyntaxErrorException(T, "cannot use '...' outside a vararg function");

				if (lcontext.IsDynamicExpression)
					throw new DynamicExpressionException("cannot use '...' in a dynamic expression.");
			}
			else
			{
				if (!lcontext.IsDynamicExpression)
					m_Ref = lcontext.Scope.Find(m_VarName);
			}

			lcontext.Lexer.Next();
		}
Esempio n. 41
0
        internal int Dump(Stream stream, int baseAddress, bool hasUpvalues)
        {
            using (BinaryWriter bw = new BinDumpBinaryWriter(stream, Encoding.UTF8))
            {
                var symbolMap = new Dictionary<SymbolRef, int>();

                var meta = m_RootChunk.Code[baseAddress];

                // skip nops
                while (meta.OpCode == OpCode.Nop)
                {
                    baseAddress++;
                    meta = m_RootChunk.Code[baseAddress];
                }

                if (meta.OpCode != OpCode.FuncMeta)
                    throw new ArgumentException("baseAddress");

                bw.Write(DUMP_CHUNK_MAGIC);
                bw.Write(DUMP_CHUNK_VERSION);
                bw.Write(hasUpvalues);
                bw.Write(meta.NumVal);

                for (var i = 0; i <= meta.NumVal; i++)
                {
                    SymbolRef[] symbolList;
                    SymbolRef symbol;

                    m_RootChunk.Code[baseAddress + i].GetSymbolReferences(out symbolList, out symbol);

                    if (symbol != null)
                        AddSymbolToMap(symbolMap, symbol);

                    if (symbolList != null)
                        foreach (var s in symbolList)
                            AddSymbolToMap(symbolMap, s);
                }

                foreach (var sr in symbolMap.Keys.ToArray())
                {
                    if (sr.i_Env != null)
                        AddSymbolToMap(symbolMap, sr.i_Env);
                }

                var allSymbols = new SymbolRef[symbolMap.Count];

                foreach (var pair in symbolMap)
                {
                    allSymbols[pair.Value] = pair.Key;
                }

                bw.Write(symbolMap.Count);

                foreach (var sym in allSymbols)
                    sym.WriteBinary(bw);

                foreach (var sym in allSymbols)
                    sym.WriteBinaryEnv(bw, symbolMap);

                for (var i = 0; i <= meta.NumVal; i++)
                    m_RootChunk.Code[baseAddress + i].WriteBinary(bw, baseAddress, symbolMap);

                return meta.NumVal + baseAddress + 1;
            }
        }
		private DynValue GetUpvalueSymbol(SymbolRef s)
		{
			if (s.Type == SymbolRefType.Local)
				return m_ExecutionStack.Peek().LocalScope[s.i_Index];
			else if (s.Type == SymbolRefType.Upvalue)
				return m_ExecutionStack.Peek().ClosureScope[s.i_Index];
			else
				throw new Exception("unsupported symbol type");
		}
Esempio n. 43
0
		private static void WriteSymbol(BinaryWriter wr, SymbolRef symbolRef, Dictionary<SymbolRef, int> symbolMap)
		{
			int id = (symbolRef == null) ? -1 : symbolMap[symbolRef];
			wr.Write(id);
		}
Esempio n. 44
0
		private static SymbolRef ReadSymbol(BinaryReader rd, SymbolRef[] deserializedSymbols)
		{
			int id = rd.ReadInt32();

			if (id < 0) return null;
			return deserializedSymbols[id];
		}
Esempio n. 45
0
 internal int AllocVar(SymbolRef var)
 {
     var.i_Index = m_ScopeFrame.DebugSymbols.Count;
     m_ScopeFrame.DebugSymbols.Add(var);
     return var.i_Index;
 }
Esempio n. 46
0
		internal static Instruction ReadBinary(SourceRef chunkRef, BinaryReader rd, int baseAddress, Table envTable, SymbolRef[] deserializedSymbols)
		{
			Instruction that = new Instruction(chunkRef);

			that.OpCode = (OpCode)rd.ReadByte();

			int usage = (int)that.OpCode.GetFieldUsage();

			if ((usage & ((int)InstructionFieldUsage.NumValAsCodeAddress)) == (int)InstructionFieldUsage.NumValAsCodeAddress)
				that.NumVal = rd.ReadInt32() + baseAddress;
			else if ((usage & ((int)InstructionFieldUsage.NumVal)) != 0)
				that.NumVal = rd.ReadInt32();

			if ((usage & ((int)InstructionFieldUsage.NumVal2)) != 0)
				that.NumVal2 = rd.ReadInt32();

			if ((usage & ((int)InstructionFieldUsage.Name)) != 0)
				that.Name = rd.ReadString();

			if ((usage & ((int)InstructionFieldUsage.Value)) != 0)
				that.Value = ReadValue(rd, envTable);

			if ((usage & ((int)InstructionFieldUsage.Symbol)) != 0)
				that.Symbol = ReadSymbol(rd, deserializedSymbols);

			if ((usage & ((int)InstructionFieldUsage.SymbolList)) != 0)
			{
				int len = rd.ReadInt32();
				that.SymbolList = new SymbolRef[len];

				for (int i = 0; i < that.SymbolList.Length; i++)
					that.SymbolList[i] = ReadSymbol(rd, deserializedSymbols);
			}

			return that;
		}
		public FunctionDefinitionStatement(ScriptLoadingContext lcontext, bool local, Token localToken)
			: base(lcontext)
		{
			// here lexer must be at the 'function' keyword
			Token funcKeyword = CheckTokenType(lcontext, TokenType.Function);
			funcKeyword = localToken ?? funcKeyword; // for debugger purposes
			
			m_Local = local;

			if (m_Local)
			{
				Token name = CheckTokenType(lcontext, TokenType.Name);
				m_FuncSymbol = lcontext.Scope.TryDefineLocal(name.Text);
				m_FriendlyName = string.Format("{0} (local)", name.Text);
				m_SourceRef = funcKeyword.GetSourceRef(name);
			}
			else
			{
				Token name = CheckTokenType(lcontext, TokenType.Name);
				string firstName = name.Text;

				m_SourceRef = funcKeyword.GetSourceRef(name);

				m_FuncSymbol = lcontext.Scope.Find(firstName);
				m_FriendlyName = firstName;

				if (lcontext.Lexer.Current.Type != TokenType.Brk_Open_Round)
				{
					m_TableAccessors = new List<string>();

					while (lcontext.Lexer.Current.Type != TokenType.Brk_Open_Round)
					{
						Token separator = lcontext.Lexer.Current;

						if (separator.Type != TokenType.Colon && separator.Type != TokenType.Dot)
							UnexpectedTokenType(separator);
						
						lcontext.Lexer.Next();

						Token field = CheckTokenType(lcontext, TokenType.Name);

						m_FriendlyName += separator.Text + field.Text;
						m_SourceRef = funcKeyword.GetSourceRef(field);

						if (separator.Type == TokenType.Colon)
						{
							m_MethodName = field.Text;
							m_IsMethodCallingConvention = true;
							break;
						}
						else
						{
							m_TableAccessors.Add(field.Text);
						}
					}

					if (m_MethodName == null && m_TableAccessors.Count > 0)
					{
						m_MethodName = m_TableAccessors[m_TableAccessors.Count - 1];
						m_TableAccessors.RemoveAt(m_TableAccessors.Count - 1);
					}
				}
			}

			m_FuncDef = new FunctionDefinitionExpression(lcontext, m_IsMethodCallingConvention, false);
			lcontext.Source.Refs.Add(m_SourceRef);
		}
Esempio n. 48
0
 public int Emit_Load(SymbolRef sym)
 {
     switch (sym.Type)
     {
         case SymbolRefType.Global:
             Emit_Load(sym.i_Env);
             AppendInstruction(new Instruction(m_CurrentSourceRef)
             {
                 OpCode = OpCode.Index,
                 Value = DynValue.NewString(sym.i_Name)
             });
             return 2;
         case SymbolRefType.Local:
             AppendInstruction(new Instruction(m_CurrentSourceRef) {OpCode = OpCode.Local, Symbol = sym});
             return 1;
         case SymbolRefType.Upvalue:
             AppendInstruction(new Instruction(m_CurrentSourceRef) {OpCode = OpCode.Upvalue, Symbol = sym});
             return 1;
         default:
             throw new InternalErrorException("Unexpected symbol type : {0}", sym);
     }
 }
		private void AssignLocal(SymbolRef symref, DynValue value)
		{
			var stackframe = m_ExecutionStack.Peek();

			DynValue v = stackframe.LocalScope[symref.i_Index];
			if (v == null)
				stackframe.LocalScope[symref.i_Index] = v = DynValue.NewNil();

			v.Assign(value);
		}
Esempio n. 50
0
		internal void GetSymbolReferences(out SymbolRef[] symbolList, out SymbolRef symbol)
		{
			int usage = (int)OpCode.GetFieldUsage();

			symbol = null;
			symbolList = null;

			if ((usage & ((int)InstructionFieldUsage.Symbol)) != 0)
				symbol = this.Symbol;

			if ((usage & ((int)InstructionFieldUsage.SymbolList)) != 0)
				symbolList = this.SymbolList;

		}
Esempio n. 51
0
 public Instruction Emit_Closure(SymbolRef[] symbols, int jmpnum)
 {
     return
         AppendInstruction(new Instruction(m_CurrentSourceRef)
         {
             OpCode = OpCode.Closure,
             SymbolList = symbols,
             NumVal = jmpnum
         });
 }
		private void AddSymbolToMap(Dictionary<SymbolRef, int> symbolMap, SymbolRef s)
		{
			if (!symbolMap.ContainsKey(s))
				symbolMap.Add(s, symbolMap.Count);
		}
Esempio n. 53
0
 public int Emit_Store(SymbolRef sym, int stackofs, int tupleidx)
 {
     switch (sym.Type)
     {
         case SymbolRefType.Global:
             Emit_Load(sym.i_Env);
             AppendInstruction(new Instruction(m_CurrentSourceRef)
             {
                 OpCode = OpCode.IndexSet,
                 Symbol = sym,
                 NumVal = stackofs,
                 NumVal2 = tupleidx,
                 Value = DynValue.NewString(sym.i_Name)
             });
             return 2;
         case SymbolRefType.Local:
             AppendInstruction(new Instruction(m_CurrentSourceRef)
             {
                 OpCode = OpCode.StoreLcl,
                 Symbol = sym,
                 NumVal = stackofs,
                 NumVal2 = tupleidx
             });
             return 1;
         case SymbolRefType.Upvalue:
             AppendInstruction(new Instruction(m_CurrentSourceRef)
             {
                 OpCode = OpCode.StoreUpv,
                 Symbol = sym,
                 NumVal = stackofs,
                 NumVal2 = tupleidx
             });
             return 1;
         default:
             throw new InternalErrorException("Unexpected symbol type : {0}", sym);
     }
 }
		internal int Undump(Stream stream, int sourceID, Table envTable, out bool hasUpvalues)
		{
			int baseAddress = m_RootChunk.Code.Count;
			SourceRef sourceRef = new SourceRef(sourceID, 0, 0, 0, 0, false);

			using (BinaryReader br = new BinDumpBinaryReader(stream, Encoding.UTF8))
			{
				ulong headerMark = br.ReadUInt64();

				if (headerMark != DUMP_CHUNK_MAGIC)
					throw new ArgumentException("Not a MoonSharp chunk");

				int version = br.ReadInt32();

				if (version != DUMP_CHUNK_VERSION)
					throw new ArgumentException("Invalid version");

				hasUpvalues = br.ReadBoolean();

				int len = br.ReadInt32();

				int numSymbs = br.ReadInt32();
				SymbolRef[] allSymbs = new SymbolRef[numSymbs];

				for (int i = 0; i < numSymbs; i++)
					allSymbs[i] = SymbolRef.ReadBinary(br);

				for (int i = 0; i < numSymbs; i++)
					allSymbs[i].ReadBinaryEnv(br, allSymbs);

				for (int i = 0; i <= len; i++)
				{
					Instruction I = Instruction.ReadBinary(sourceRef, br, baseAddress, envTable, allSymbs);
					m_RootChunk.Code.Add(I);
				}

				return baseAddress;
			}
		}
Esempio n. 55
0
		public SymbolRef CreateUpvalue(BuildTimeScope scope, SymbolRef symbol)
		{
			return null;
		}
        private SymbolRef[] DefineArguments(List<string> paramnames, ScriptLoadingContext lcontext)
        {
            var names = new HashSet<string>();

            var ret = new SymbolRef[paramnames.Count];

            for (var i = paramnames.Count - 1; i >= 0; i--)
            {
                if (!names.Add(paramnames[i]))
                    paramnames[i] = paramnames[i] + "@" + i;

                ret[i] = lcontext.Scope.DefineLocal(paramnames[i]);
            }

            return ret;
        }