示例#1
0
		/// <summary>
		/// Gets the code snippet represented by a source ref
		/// </summary>
		/// <param name="sourceCodeRef">The source code reference.</param>
		/// <returns></returns>
		public string GetCodeSnippet(SourceRef sourceCodeRef)
		{
			if (sourceCodeRef.FromLine == sourceCodeRef.ToLine)
			{
				int from = AdjustStrIndex(Lines[sourceCodeRef.FromLine], sourceCodeRef.FromChar);
				int to = AdjustStrIndex(Lines[sourceCodeRef.FromLine], sourceCodeRef.ToChar);
				return Lines[sourceCodeRef.FromLine].Substring(from, to - from);
			}

			StringBuilder sb = new StringBuilder();

			for (int i = sourceCodeRef.FromLine; i <= sourceCodeRef.ToLine; i++)
			{
				if (i == sourceCodeRef.FromLine)
				{
					int from = AdjustStrIndex(Lines[i], sourceCodeRef.FromChar);
					sb.Append(Lines[i].Substring(from));
				}
				else if (i == sourceCodeRef.ToLine)
				{
					int to = AdjustStrIndex(Lines[i], sourceCodeRef.ToChar);
					sb.Append(Lines[i].Substring(0, to + 1));
				}
				else
				{
					sb.Append(Lines[i]);
				}
			}

			return sb.ToString();
		}
示例#2
0
		public ReturnStatement(ScriptLoadingContext lcontext, Expression e, SourceRef sref)
			: base(lcontext)
		{
			m_Expression = e;
			m_Ref = sref;
			lcontext.Source.Refs.Add(sref);
		}
示例#3
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);
		}		
示例#4
0
		internal ScriptExecutionContext(Processor p, CallbackFunction callBackFunction, SourceRef sourceRef, bool isDynamic = false)
		{
			IsDynamicExecution = isDynamic;
			m_Processor = p;
			m_Callback = callBackFunction;
			CallingLocation = sourceRef;
		}
		DebuggerAction IDebugger.GetAction(int ip, SourceRef sourceref)
		{
			PauseRequested = false;

			lock (m_Lock)
				if (Client != null)
				{
					Client.SendStopEvent();
				}

			while (true)
			{
				lock (m_Lock)
				{
					if (Client == null)
					{
						return new DebuggerAction() { Action = DebuggerAction.ActionType.Run };
					}

					if (m_PendingAction != null)
					{
						var action = m_PendingAction;
						m_PendingAction = null;
						return action;
					}
				}

				Sleep(10);
			}
		}
		public SourceRef(SourceRef src, bool isStepStop)
		{
			SourceIdx = src.SourceIdx;
			FromChar = src.FromChar;
			ToChar = src.ToChar;
			FromLine = src.FromLine;
			ToLine = src.ToLine;
			IsStepStop = isStepStop;
		}
 internal void DecorateMessage(Script script, SourceRef sref, int ip = -1)
 {
     if (sref != null)
     {
         DecoratedMessage = string.Format("{0}: {1}", sref.FormatLocation(script), Message);
     }
     else
     {
         DecoratedMessage = string.Format("bytecode:{0}: {1}", ip, Message);
     }
 }
		public FunctionCallExpression(ScriptLoadingContext lcontext, Expression function, Token thisCallName)
			: base(lcontext)
		{
			Token callToken = thisCallName ?? lcontext.Lexer.Current;

			m_Name = thisCallName != null ? thisCallName.Text : null;
			m_DebugErr = function.GetFriendlyDebugName();
			m_Function = function;

			switch (lcontext.Lexer.Current.Type)
			{
				case TokenType.Brk_Open_Round:
					Token openBrk = lcontext.Lexer.Current;
					lcontext.Lexer.Next();
					Token t = lcontext.Lexer.Current;
					if (t.Type == TokenType.Brk_Close_Round)
					{
						m_Arguments = new List<Expression>();
						SourceRef = callToken.GetSourceRef(t);
						lcontext.Lexer.Next();
					}
					else
					{
						m_Arguments = ExprList(lcontext);
						SourceRef = callToken.GetSourceRef(CheckMatch(lcontext, openBrk, TokenType.Brk_Close_Round, ")"));
					}
					break;
				case TokenType.String:
				case TokenType.String_Long:
					{
						m_Arguments = new List<Expression>();
						Expression le = new LiteralExpression(lcontext, lcontext.Lexer.Current);
						m_Arguments.Add(le);
						SourceRef = callToken.GetSourceRef(lcontext.Lexer.Current);
					}
					break;
				case TokenType.Brk_Open_Curly:
				case TokenType.Brk_Open_Curly_Shared:
					{
						m_Arguments = new List<Expression>();
						m_Arguments.Add(new TableConstructor(lcontext, lcontext.Lexer.Current.Type == TokenType.Brk_Open_Curly_Shared));
						SourceRef = callToken.GetSourceRefUpTo(lcontext.Lexer.Current);
					}
					break;
				default:
					throw new SyntaxErrorException(lcontext.Lexer.Current, "function arguments expected")
					{
						IsPrematureStreamTermination = (lcontext.Lexer.Current.Type == TokenType.Eof)
					};
			}
		}
示例#9
0
		public ScopeBlockStatement(ScriptLoadingContext lcontext)
			: base(lcontext)
		{
			lcontext.Scope.PushBlock();

			m_Do = CheckTokenType(lcontext, TokenType.Do).GetSourceRef();

			m_Block = new CompositeStatement(lcontext);

			m_End = CheckTokenType(lcontext, TokenType.End).GetSourceRef();

			m_StackFrame = lcontext.Scope.PopBlock();
			lcontext.Source.Refs.Add(m_Do);
			lcontext.Source.Refs.Add(m_End);
		}
示例#10
0
文件: X1.cs 项目: cyecp/moonsharp
			public DebuggerAction GetAction(int ip, SourceRef sourceref)
			{
				m_InstructionCounter += 1;

				if ((m_InstructionCounter % 1000) == 0)
					Console.Write(".");

				if (m_InstructionCounter > 50000)
					throw new MyException();

				return new DebuggerAction()
				{
					Action = DebuggerAction.ActionType.StepIn,
				};
			}
示例#11
0
		public IfStatement(ScriptLoadingContext lcontext)
			: base(lcontext)
		{
			while (lcontext.Lexer.Current.Type != TokenType.Else && lcontext.Lexer.Current.Type != TokenType.End)
			{
				m_Ifs.Add(CreateIfBlock(lcontext));
			}

			if (lcontext.Lexer.Current.Type == TokenType.Else)
			{
				m_Else = CreateElseBlock(lcontext);
			}

			m_End = CheckTokenType(lcontext, TokenType.End).GetSourceRef();
			lcontext.Source.Refs.Add(m_End);
		}
示例#12
0
        public RepeatStatement(ScriptLoadingContext lcontext)
            : base(lcontext)
        {
            m_Repeat = CheckTokenType(lcontext, TokenType.Repeat).GetSourceRef();

            lcontext.Scope.PushBlock();
            m_Block = new CompositeStatement(lcontext);

            var until = CheckTokenType(lcontext, TokenType.Until);

            m_Condition = Expression.Expr(lcontext);

            m_Until = until.GetSourceRefUpTo(lcontext.Lexer.Current);

            m_StackFrame = lcontext.Scope.PopBlock();
            lcontext.Source.Refs.Add(m_Repeat);
            lcontext.Source.Refs.Add(m_Until);
        }
示例#13
0
        public AssignmentStatement(ScriptLoadingContext lcontext, Expression firstExpression, Token first)
            : base(lcontext)
        {
            m_LValues.Add(CheckVar(lcontext, firstExpression));

            while (lcontext.Lexer.Current.Type == TokenType.Comma)
            {
                lcontext.Lexer.Next();
                var e = Expression.PrimaryExp(lcontext);
                m_LValues.Add(CheckVar(lcontext, e));
            }

            CheckTokenType(lcontext, TokenType.Op_Assignment);

            m_RValues = Expression.ExprList(lcontext);

            var last = lcontext.Lexer.Current;
            m_Ref = first.GetSourceRefUpTo(last);
            lcontext.Source.Refs.Add(m_Ref);
        }
示例#14
0
		public ForEachLoopStatement(ScriptLoadingContext lcontext, Token firstNameToken, Token forToken)
			: base(lcontext)
		{
			//	for namelist in explist do block end | 		

			List<string> names = new List<string>();
			names.Add(firstNameToken.Text);

			while (lcontext.Lexer.Current.Type == TokenType.Comma)
			{
				lcontext.Lexer.Next();
				Token name = CheckTokenType(lcontext, TokenType.Name);
				names.Add(name.Text);
			}

			CheckTokenType(lcontext, TokenType.In);

			m_RValues = new ExprListExpression(Expression.ExprList(lcontext), lcontext);

			lcontext.Scope.PushBlock();

			m_Names = names
				.Select(n => lcontext.Scope.TryDefineLocal(n))
				.ToArray();

			m_NameExps = m_Names
				.Select(s => new SymbolRefExpression(lcontext, s))
				.Cast<IVariable>()
				.ToArray();

			m_RefFor = forToken.GetSourceRef(CheckTokenType(lcontext, TokenType.Do));

			m_Block = 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);
		}
示例#15
0
		public ReturnStatement(ScriptLoadingContext lcontext)
			: base(lcontext)
		{
			Token ret = lcontext.Lexer.Current;

			lcontext.Lexer.Next();

			Token cur = lcontext.Lexer.Current;

			if (cur.IsEndOfBlock() || cur.Type == TokenType.SemiColon)
			{
				m_Expression = null;
				m_Ref = ret.GetSourceRef();
			}
			else
			{
				m_Expression = new ExprListExpression(Expression.ExprList(lcontext), lcontext);
				m_Ref = ret.GetSourceRefUpTo(lcontext.Lexer.Current);
			}
			lcontext.Source.Refs.Add(m_Ref);
		}
示例#16
0
		public WhileStatement(ScriptLoadingContext lcontext)
			: base(lcontext)
		{
			Token whileTk = CheckTokenType(lcontext, TokenType.While);

			m_Condition = Expression.Expr(lcontext);

			m_Start = whileTk.GetSourceRefUpTo(lcontext.Lexer.Current);

			//m_Start = BuildSourceRef(context.Start, exp.Stop);
			//m_End = BuildSourceRef(context.Stop, context.END());

			lcontext.Scope.PushBlock();
			CheckTokenType(lcontext, TokenType.Do);
			m_Block = new CompositeStatement(lcontext);
			m_End = CheckTokenType(lcontext, TokenType.End).GetSourceRef();
			m_StackFrame = lcontext.Scope.PopBlock();

			lcontext.Source.Refs.Add(m_Start);
			lcontext.Source.Refs.Add(m_End);
		}
示例#17
0
		public AssignmentStatement(ScriptLoadingContext lcontext, Token startToken)
			: base(lcontext)
		{
			List<string> names = new List<string>();

			Token first = startToken;

			while (true)
			{
				Token name = CheckTokenType(lcontext, TokenType.Name);
				names.Add(name.Text);

				if (lcontext.Lexer.Current.Type != TokenType.Comma)
					break;

				lcontext.Lexer.Next();
			}

			if (lcontext.Lexer.Current.Type == TokenType.Op_Assignment)
			{
				CheckTokenType(lcontext, TokenType.Op_Assignment);
				m_RValues = Expression.ExprList(lcontext);
			}
			else
			{
				m_RValues = new List<Expression>();
			}

			foreach (string name in names)
			{
				var localVar = lcontext.Scope.TryDefineLocal(name);
				var symbol = new SymbolRefExpression(lcontext, localVar);
				m_LValues.Add(symbol);
			}

			Token last = lcontext.Lexer.Current;
			m_Ref = first.GetSourceRefUpTo(last);
			lcontext.Source.Refs.Add(m_Ref);

		}
        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);
        }
示例#19
0
 public IDisposable EnterSource(SourceRef sref)
 {
     return new SourceCodeStackGuard(sref, this);
 }
		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;
			}
		}
		internal List<WatchItem> Debugger_GetCallStack(SourceRef startingRef)
		{
			List<WatchItem> wis = new List<WatchItem>();

			for (int i = 0; i < m_ExecutionStack.Count; i++)
			{
				var c = m_ExecutionStack.Peek(i);

				var I = m_RootChunk.Code[c.Debug_EntryPoint];

				string callname = I.OpCode == OpCode.Meta ? I.Name : null;

				if (c.ClrFunction != null)
				{
					wis.Add(new WatchItem()
					{
						Address = -1,
						BasePtr = -1,
						RetAddress = c.ReturnAddress,
						Location = startingRef,
						Name = c.ClrFunction.Name
					});
				}
				else
				{
					wis.Add(new WatchItem()
					{
						Address = c.Debug_EntryPoint,
						BasePtr = c.BasePointer,
						RetAddress = c.ReturnAddress,
						Name = callname,
						Location = startingRef,
					});
				}

				startingRef = c.CallingSourceRef;

				if (c.Continuation != null)
				{
					wis.Add(new WatchItem()
					{
						Name = c.Continuation.Name,
						Location = SourceRef.GetClrLocation()
					});
				}


			}

			return wis;
		}
示例#22
0
		internal Instruction(SourceRef sourceref)
		{
			SourceCodeRef = sourceref;
		}
        private Statement CreateBody(ScriptLoadingContext lcontext)
        {
            Statement s = new CompositeStatement(lcontext);

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

            m_End = lcontext.Lexer.Current.GetSourceRef();

            lcontext.Lexer.Next();
            return s;
        }
		internal SyntaxErrorException(Script script, SourceRef sref, string message)
			: base(message)
		{
			DecorateMessage(script, sref);
		}
		internal SyntaxErrorException(Script script, SourceRef sref, string format, params object[] args)
			: base(format, args)
		{
			DecorateMessage(script, sref);
		}
示例#26
0
 public SourceCodeStackGuard(SourceRef sref, ByteCode bc)
 {
     m_Bc = bc;
     m_Bc.PushSourceRef(sref);
 }
示例#27
0
 public void PushSourceRef(SourceRef sref)
 {
     m_SourceRefStack.Add(sref);
     m_CurrentSourceRef = sref;
 }
示例#28
0
 public void PopSourceRef()
 {
     m_SourceRefStack.RemoveAt(m_SourceRefStack.Count - 1);
     m_CurrentSourceRef = (m_SourceRefStack.Count > 0) ? m_SourceRefStack[m_SourceRefStack.Count - 1] : null;
 }
示例#29
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;
		}
		internal string PerformMessageDecorationBeforeUnwind(DynValue messageHandler, string decoratedMessage, SourceRef sourceRef)
		{
			try
			{
				DynValue[] args = new DynValue[] { DynValue.NewString(decoratedMessage) };
				DynValue ret = DynValue.Nil;

				if (messageHandler.Type == DataType.Function)
				{
					ret = this.Call(messageHandler, args);
				}
				else if (messageHandler.Type == DataType.ClrFunction)
				{
					ScriptExecutionContext ctx = new ScriptExecutionContext(this, messageHandler.Callback, sourceRef);
					ret = messageHandler.Callback.Invoke(ctx, args);
				}
				else
				{
					throw new ScriptRuntimeException("error handler not set to a function");
				}

				string newmsg = ret.ToPrintString();
				if (newmsg != null)
					return newmsg;
			}
			catch (ScriptRuntimeException innerEx)
			{
				return innerEx.Message + "\n" + decoratedMessage;
			}

			return decoratedMessage;
		}
示例#31
0
 public bool Equals(SourceRef other)
 {
     return(Id == other.Id);
 }