Browse Source

Source references ok

Xanathar 11 years ago
parent
commit
69f261a3aa
36 changed files with 665 additions and 557 deletions
  1. 100 14
      src/MoonSharp.Debugger/MainForm.Designer.cs
  2. 24 1
      src/MoonSharp.Debugger/MainForm.cs
  3. 50 44
      src/MoonSharp.Debugger/MainForm.resx
  4. 0 3
      src/MoonSharp.Interpreter.Tests/MoonSharp.Interpreter.Tests.csproj
  5. 0 214
      src/MoonSharp.Interpreter.Tests/TestMore/303-package.t
  6. 0 10
      src/MoonSharp.Interpreter.Tests/TestMore/TestMoreTests.cs
  7. 1 1
      src/MoonSharp.Interpreter/Debugging/IDebugger.cs
  8. 53 2
      src/MoonSharp.Interpreter/Debugging/SourceCode.cs
  9. 20 5
      src/MoonSharp.Interpreter/Debugging/SourceRef.cs
  10. 2 2
      src/MoonSharp.Interpreter/Execution/ScriptLoadingContext.cs
  11. 78 38
      src/MoonSharp.Interpreter/Execution/VM/ByteCode.cs
  12. 5 0
      src/MoonSharp.Interpreter/Execution/VM/Instruction.cs
  13. 1 1
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_Debugger.cs
  14. 15 2
      src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_Errors.cs
  15. 10 7
      src/MoonSharp.Interpreter/Grammar/Lua.g4
  16. 2 2
      src/MoonSharp.Interpreter/MoonSharp.Interpreter.csproj
  17. 33 17
      src/MoonSharp.Interpreter/Script.cs
  18. 27 85
      src/MoonSharp.Interpreter/Tree/Antlr_Interface/Loader_Antlr.cs
  19. 31 10
      src/MoonSharp.Interpreter/Tree/Expressions/FunctionDefinitionExpression.cs
  20. 16 0
      src/MoonSharp.Interpreter/Tree/NodeBase.cs
  21. 1 1
      src/MoonSharp.Interpreter/Tree/NodeFactory.cs
  22. 2 1
      src/MoonSharp.Interpreter/Tree/Statement.cs
  23. 17 9
      src/MoonSharp.Interpreter/Tree/Statements/AssignmentStatement.cs
  24. 14 8
      src/MoonSharp.Interpreter/Tree/Statements/BreakStatement.cs
  25. 1 0
      src/MoonSharp.Interpreter/Tree/Statements/ChunkStatement.cs
  26. 12 0
      src/MoonSharp.Interpreter/Tree/Statements/ForEachLoopStatement.cs
  27. 13 0
      src/MoonSharp.Interpreter/Tree/Statements/ForLoopStatement.cs
  28. 8 2
      src/MoonSharp.Interpreter/Tree/Statements/FunctionCallStatement.cs
  29. 23 14
      src/MoonSharp.Interpreter/Tree/Statements/FunctionDefinitionStatement.cs
  30. 36 12
      src/MoonSharp.Interpreter/Tree/Statements/IfStatement.cs
  31. 0 40
      src/MoonSharp.Interpreter/Tree/Statements/LocalAssignmentStatement.cs
  32. 15 1
      src/MoonSharp.Interpreter/Tree/Statements/RepeatStatement.cs
  33. 19 7
      src/MoonSharp.Interpreter/Tree/Statements/ReturnStatement.cs
  34. 12 2
      src/MoonSharp.Interpreter/Tree/Statements/ScopeBlockStatement.cs
  35. 17 1
      src/MoonSharp.Interpreter/Tree/Statements/WhileStatement.cs
  36. 7 1
      src/MoonSharp/Program.cs

+ 100 - 14
src/MoonSharp.Debugger/MainForm.Designer.cs

@@ -102,8 +102,14 @@
 			this.label1 = new System.Windows.Forms.Label();
 			this.label1 = new System.Windows.Forms.Label();
 			this.splitContainer3 = new System.Windows.Forms.SplitContainer();
 			this.splitContainer3 = new System.Windows.Forms.SplitContainer();
 			this.codeView = new MoonSharp.Debugger.SourceCodeDebugControl();
 			this.codeView = new MoonSharp.Debugger.SourceCodeDebugControl();
-			this.txtOutput = new System.Windows.Forms.TextBox();
 			this.timerFollow = new System.Windows.Forms.Timer(this.components);
 			this.timerFollow = new System.Windows.Forms.Timer(this.components);
+			this.tabControl3 = new System.Windows.Forms.TabControl();
+			this.tabPage5 = new System.Windows.Forms.TabPage();
+			this.tabPage6 = new System.Windows.Forms.TabPage();
+			this.txtOutput = new System.Windows.Forms.TextBox();
+			this.toolStrip5 = new System.Windows.Forms.ToolStrip();
+			this.txtCodeView = new System.Windows.Forms.TextBox();
+			this.toolStrip6 = new System.Windows.Forms.ToolStrip();
 			this.menuStrip1.SuspendLayout();
 			this.menuStrip1.SuspendLayout();
 			this.toolStrip1.SuspendLayout();
 			this.toolStrip1.SuspendLayout();
 			this.splitContainer1.Panel1.SuspendLayout();
 			this.splitContainer1.Panel1.SuspendLayout();
@@ -124,6 +130,9 @@
 			this.splitContainer3.Panel1.SuspendLayout();
 			this.splitContainer3.Panel1.SuspendLayout();
 			this.splitContainer3.Panel2.SuspendLayout();
 			this.splitContainer3.Panel2.SuspendLayout();
 			this.splitContainer3.SuspendLayout();
 			this.splitContainer3.SuspendLayout();
+			this.tabControl3.SuspendLayout();
+			this.tabPage5.SuspendLayout();
+			this.tabPage6.SuspendLayout();
 			this.SuspendLayout();
 			this.SuspendLayout();
 			// 
 			// 
 			// menuStrip1
 			// menuStrip1
@@ -189,7 +198,7 @@
 			// scriptCodeToolStripMenuItem
 			// scriptCodeToolStripMenuItem
 			// 
 			// 
 			this.scriptCodeToolStripMenuItem.Name = "scriptCodeToolStripMenuItem";
 			this.scriptCodeToolStripMenuItem.Name = "scriptCodeToolStripMenuItem";
-			this.scriptCodeToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
+			this.scriptCodeToolStripMenuItem.Size = new System.Drawing.Size(133, 22);
 			this.scriptCodeToolStripMenuItem.Text = "Script code";
 			this.scriptCodeToolStripMenuItem.Text = "Script code";
 			// 
 			// 
 			// bytecodeToolStripMenuItem
 			// bytecodeToolStripMenuItem
@@ -197,7 +206,7 @@
 			this.bytecodeToolStripMenuItem.Checked = true;
 			this.bytecodeToolStripMenuItem.Checked = true;
 			this.bytecodeToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
 			this.bytecodeToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
 			this.bytecodeToolStripMenuItem.Name = "bytecodeToolStripMenuItem";
 			this.bytecodeToolStripMenuItem.Name = "bytecodeToolStripMenuItem";
-			this.bytecodeToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
+			this.bytecodeToolStripMenuItem.Size = new System.Drawing.Size(133, 22);
 			this.bytecodeToolStripMenuItem.Text = "Bytecode";
 			this.bytecodeToolStripMenuItem.Text = "Bytecode";
 			// 
 			// 
 			// debugToolStripMenuItem
 			// debugToolStripMenuItem
@@ -790,7 +799,7 @@
 			// 
 			// 
 			// splitContainer3.Panel2
 			// splitContainer3.Panel2
 			// 
 			// 
-			this.splitContainer3.Panel2.Controls.Add(this.txtOutput);
+			this.splitContainer3.Panel2.Controls.Add(this.tabControl3);
 			this.splitContainer3.Size = new System.Drawing.Size(726, 663);
 			this.splitContainer3.Size = new System.Drawing.Size(726, 663);
 			this.splitContainer3.SplitterDistance = 446;
 			this.splitContainer3.SplitterDistance = 446;
 			this.splitContainer3.TabIndex = 0;
 			this.splitContainer3.TabIndex = 0;
@@ -810,23 +819,89 @@
 			this.codeView.SourceCode = null;
 			this.codeView.SourceCode = null;
 			this.codeView.TabIndex = 1;
 			this.codeView.TabIndex = 1;
 			// 
 			// 
+			// timerFollow
+			// 
+			this.timerFollow.Interval = 15;
+			this.timerFollow.Tick += new System.EventHandler(this.timerFollow_Tick);
+			// 
+			// tabControl3
+			// 
+			this.tabControl3.Controls.Add(this.tabPage5);
+			this.tabControl3.Controls.Add(this.tabPage6);
+			this.tabControl3.Dock = System.Windows.Forms.DockStyle.Fill;
+			this.tabControl3.Location = new System.Drawing.Point(0, 0);
+			this.tabControl3.Name = "tabControl3";
+			this.tabControl3.SelectedIndex = 0;
+			this.tabControl3.Size = new System.Drawing.Size(726, 213);
+			this.tabControl3.TabIndex = 0;
+			// 
+			// tabPage5
+			// 
+			this.tabPage5.Controls.Add(this.txtOutput);
+			this.tabPage5.Controls.Add(this.toolStrip5);
+			this.tabPage5.Location = new System.Drawing.Point(4, 22);
+			this.tabPage5.Name = "tabPage5";
+			this.tabPage5.Padding = new System.Windows.Forms.Padding(3);
+			this.tabPage5.Size = new System.Drawing.Size(718, 187);
+			this.tabPage5.TabIndex = 0;
+			this.tabPage5.Text = "Output";
+			this.tabPage5.UseVisualStyleBackColor = true;
+			// 
+			// tabPage6
+			// 
+			this.tabPage6.Controls.Add(this.txtCodeView);
+			this.tabPage6.Controls.Add(this.toolStrip6);
+			this.tabPage6.Location = new System.Drawing.Point(4, 22);
+			this.tabPage6.Name = "tabPage6";
+			this.tabPage6.Padding = new System.Windows.Forms.Padding(3);
+			this.tabPage6.Size = new System.Drawing.Size(718, 187);
+			this.tabPage6.TabIndex = 1;
+			this.tabPage6.Text = "Code View";
+			this.tabPage6.UseVisualStyleBackColor = true;
+			// 
 			// txtOutput
 			// txtOutput
 			// 
 			// 
 			this.txtOutput.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
 			this.txtOutput.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
 			this.txtOutput.Dock = System.Windows.Forms.DockStyle.Fill;
 			this.txtOutput.Dock = System.Windows.Forms.DockStyle.Fill;
 			this.txtOutput.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
 			this.txtOutput.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
 			this.txtOutput.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
 			this.txtOutput.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
-			this.txtOutput.Location = new System.Drawing.Point(0, 0);
+			this.txtOutput.Location = new System.Drawing.Point(3, 28);
 			this.txtOutput.Multiline = true;
 			this.txtOutput.Multiline = true;
 			this.txtOutput.Name = "txtOutput";
 			this.txtOutput.Name = "txtOutput";
 			this.txtOutput.ReadOnly = true;
 			this.txtOutput.ReadOnly = true;
-			this.txtOutput.Size = new System.Drawing.Size(726, 213);
-			this.txtOutput.TabIndex = 0;
-			// 
-			// timerFollow
-			// 
-			this.timerFollow.Interval = 15;
-			this.timerFollow.Tick += new System.EventHandler(this.timerFollow_Tick);
+			this.txtOutput.ScrollBars = System.Windows.Forms.ScrollBars.Both;
+			this.txtOutput.Size = new System.Drawing.Size(712, 156);
+			this.txtOutput.TabIndex = 3;
+			// 
+			// toolStrip5
+			// 
+			this.toolStrip5.Location = new System.Drawing.Point(3, 3);
+			this.toolStrip5.Name = "toolStrip5";
+			this.toolStrip5.Size = new System.Drawing.Size(712, 25);
+			this.toolStrip5.TabIndex = 2;
+			this.toolStrip5.Text = "toolStrip5";
+			// 
+			// txtCodeView
+			// 
+			this.txtCodeView.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
+			this.txtCodeView.Dock = System.Windows.Forms.DockStyle.Fill;
+			this.txtCodeView.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
+			this.txtCodeView.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
+			this.txtCodeView.Location = new System.Drawing.Point(3, 28);
+			this.txtCodeView.Multiline = true;
+			this.txtCodeView.Name = "txtCodeView";
+			this.txtCodeView.ReadOnly = true;
+			this.txtCodeView.ScrollBars = System.Windows.Forms.ScrollBars.Both;
+			this.txtCodeView.Size = new System.Drawing.Size(712, 156);
+			this.txtCodeView.TabIndex = 3;
+			// 
+			// toolStrip6
+			// 
+			this.toolStrip6.Location = new System.Drawing.Point(3, 3);
+			this.toolStrip6.Name = "toolStrip6";
+			this.toolStrip6.Size = new System.Drawing.Size(712, 25);
+			this.toolStrip6.TabIndex = 2;
+			this.toolStrip6.Text = "toolStrip6";
 			// 
 			// 
 			// MainForm
 			// MainForm
 			// 
 			// 
@@ -840,6 +915,7 @@
 			this.MainMenuStrip = this.menuStrip1;
 			this.MainMenuStrip = this.menuStrip1;
 			this.Name = "MainForm";
 			this.Name = "MainForm";
 			this.Text = "MoonSharp Debugger";
 			this.Text = "MoonSharp Debugger";
+			this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
 			this.Load += new System.EventHandler(this.MainForm_Load);
 			this.Load += new System.EventHandler(this.MainForm_Load);
 			this.menuStrip1.ResumeLayout(false);
 			this.menuStrip1.ResumeLayout(false);
 			this.menuStrip1.PerformLayout();
 			this.menuStrip1.PerformLayout();
@@ -868,8 +944,12 @@
 			this.tabPage2.ResumeLayout(false);
 			this.tabPage2.ResumeLayout(false);
 			this.splitContainer3.Panel1.ResumeLayout(false);
 			this.splitContainer3.Panel1.ResumeLayout(false);
 			this.splitContainer3.Panel2.ResumeLayout(false);
 			this.splitContainer3.Panel2.ResumeLayout(false);
-			this.splitContainer3.Panel2.PerformLayout();
 			this.splitContainer3.ResumeLayout(false);
 			this.splitContainer3.ResumeLayout(false);
+			this.tabControl3.ResumeLayout(false);
+			this.tabPage5.ResumeLayout(false);
+			this.tabPage5.PerformLayout();
+			this.tabPage6.ResumeLayout(false);
+			this.tabPage6.PerformLayout();
 			this.ResumeLayout(false);
 			this.ResumeLayout(false);
 			this.PerformLayout();
 			this.PerformLayout();
 
 
@@ -931,7 +1011,6 @@
 		private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
 		private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
 		private System.Windows.Forms.SplitContainer splitContainer3;
 		private System.Windows.Forms.SplitContainer splitContainer3;
 		private SourceCodeDebugControl codeView;
 		private SourceCodeDebugControl codeView;
-		private System.Windows.Forms.TextBox txtOutput;
 		private DoubleBufferedListView lvVStack;
 		private DoubleBufferedListView lvVStack;
 		private System.Windows.Forms.ColumnHeader columnHeader5;
 		private System.Windows.Forms.ColumnHeader columnHeader5;
 		private System.Windows.Forms.ColumnHeader columnHeader6;
 		private System.Windows.Forms.ColumnHeader columnHeader6;
@@ -951,6 +1030,13 @@
 		private System.Windows.Forms.Timer timerFollow;
 		private System.Windows.Forms.Timer timerFollow;
 		private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
 		private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
 		private System.Windows.Forms.ToolStripButton btnFastHack;
 		private System.Windows.Forms.ToolStripButton btnFastHack;
+		private System.Windows.Forms.TabControl tabControl3;
+		private System.Windows.Forms.TabPage tabPage5;
+		private System.Windows.Forms.TextBox txtOutput;
+		private System.Windows.Forms.ToolStrip toolStrip5;
+		private System.Windows.Forms.TabPage tabPage6;
+		private System.Windows.Forms.TextBox txtCodeView;
+		private System.Windows.Forms.ToolStrip toolStrip6;
 
 
 
 
 	}
 	}

+ 24 - 1
src/MoonSharp.Debugger/MainForm.cs

@@ -131,11 +131,12 @@ namespace MoonSharp.Debugger
 		AutoResetEvent m_WaitLock = new AutoResetEvent(false);
 		AutoResetEvent m_WaitLock = new AutoResetEvent(false);
 		AutoResetEvent m_WaitBack = new AutoResetEvent(false);
 		AutoResetEvent m_WaitBack = new AutoResetEvent(false);
 
 
-		DebuggerAction IDebugger.GetAction(int ip)
+		DebuggerAction IDebugger.GetAction(int ip, SourceRef sourceCodeRef)
 		{
 		{
 			m_Ctx.Post(o =>
 			m_Ctx.Post(o =>
 			{
 			{
 				codeView.ActiveLine = ip;
 				codeView.ActiveLine = ip;
+				RefreshCodeView(sourceCodeRef);
 			}, null);
 			}, null);
 
 
 			m_WaitLock.WaitOne();
 			m_WaitLock.WaitOne();
@@ -148,6 +149,28 @@ namespace MoonSharp.Debugger
 			return action;
 			return action;
 		}
 		}
 
 
+		SourceRef m_PrevRef = null;
+
+		private void RefreshCodeView(SourceRef sourceCodeRef)
+		{
+			if (sourceCodeRef == m_PrevRef)
+				return;
+
+			m_PrevRef = sourceCodeRef;
+
+			if (sourceCodeRef == null)
+			{
+				txtCodeView.Text = "!! NULL !!";
+			}
+			else
+			{
+				SourceCode sc = m_Script.GetSourceCode(sourceCodeRef.SourceIdx);
+				//txtCodeView.Text = sc.Lines[sourceCodeRef.FromLine + 1] + "\n" +
+				//	sourceCodeRef.ToString();
+				txtCodeView.Text = sc.GetCodeSnippet(sourceCodeRef) + "\r\n\r\n" + sourceCodeRef.ToString();
+			}
+		}
+
 		void DebugAction(DebuggerAction action)
 		void DebugAction(DebuggerAction action)
 		{
 		{
 			bool savedState = timerFollow.Enabled;
 			bool savedState = timerFollow.Enabled;

+ 50 - 44
src/MoonSharp.Debugger/MainForm.resx

@@ -171,57 +171,57 @@
         AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj0yLjAuMC4w
         AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj0yLjAuMC4w
         LCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAACZTeXN0
         LCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAACZTeXN0
         ZW0uV2luZG93cy5Gb3Jtcy5JbWFnZUxpc3RTdHJlYW1lcgEAAAAERGF0YQcCAgAAAAkDAAAADwMAAACe
         ZW0uV2luZG93cy5Gb3Jtcy5JbWFnZUxpc3RTdHJlYW1lcgEAAAAERGF0YQcCAgAAAAkDAAAADwMAAACe
-        DQAAAk1TRnQBSQFMAgEBBAEAAVgBAQFYAQEBEAEAARABAAT/ASEBAAj/AUIBTQE2BwABNgMAASgDAAFA
+        DQAAAk1TRnQBSQFMAgEBBAEAAWgBAQFoAQEBEAEAARABAAT/ASEBAAj/AUIBTQE2BwABNgMAASgDAAFA
         AwABIAMAAQEBAAEgBgABIP8A/wD/AP8A/wD/AP8A/wD/AP8A/wD/AP8A/wD/AP8AIgADDAEQA1kBvwP2
         AwABIAMAAQEBAAEgBgABIP8A/wD/AP8A/wD/AP8A/wD/AP8A/wD/AP8A/wD/AP8AIgADDAEQA1kBvwP2
         Af8D9gH/A1kBvwMqAUADKgFAAyoBQAMqAUADKgFAAyoBQAMqAUADKgFAAyoBQAMqAUADKgFAEAAD9gH/
         Af8D9gH/A1kBvwMqAUADKgFAAyoBQAMqAUADKgFAAyoBQAMqAUADKgFAAyoBQAMqAUADKgFAEAAD9gH/
-        A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/A/YB/5AAA1kBvwOcAf8DFwH/AxcB/wP2Af8D9gH/A/YB/wP2
-        Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/A/YB/xAAA/YB/wMXAf8DFwH/AxcB/wMXAf8DFwH/
-        AxcB/wP2Af+QAAP2Af8DFwH/AxcB/wMXAf8D9gH/AxcB/wMXAf8DFwH/AxcB/wMXAf8DFwH/AxcB/wMX
-        Af8DFwH/AxcB/wP2Af8QAAP2Af8DFwH/AxcB/wMXAf8DFwH/AxcB/wMXAf8D9gH/FAAD9gH/A/YB/wP2
+        A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/A/YB/5AAA1kBvwOcAf8DFQH/AxUB/wP2Af8D9gH/A/YB/wP2
+        Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/A/YB/xAAA/YB/wMVAf8DFQH/AxUB/wMVAf8DFQH/
+        AxUB/wP2Af+QAAP2Af8DFQH/AxUB/wMVAf8D9gH/AxUB/wMVAf8DFQH/AxUB/wMVAf8DFQH/AxUB/wMV
+        Af8DFQH/AxUB/wP2Af8QAAP2Af8DFQH/AxUB/wMVAf8DFQH/AxUB/wMVAf8D9gH/FAAD9gH/A/YB/wP2
         Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8cAAP2Af8D9gH/A/YB/wP2Af8D9gH/CAADIQEwAyEBMAQA
         Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8cAAP2Af8D9gH/A/YB/wP2Af8D9gH/CAADIQEwAyEBMAQA
-        A/YB/wP2Af8D9gH/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gH/
         Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8IAAP2Af8D9gH/A/YB/wP2Af8D9gH/
         FAAD9gH/A/YB/wP2Af8D9gH/A/YB/wQAA/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/
         FAAD9gH/A/YB/wP2Af8D9gH/A/YB/wQAA/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/
         A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/
         A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/A/YB/wP2Af8D9gH/
@@ -235,6 +235,12 @@
   <metadata name="toolStrip4.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
   <metadata name="toolStrip4.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
     <value>673, 17</value>
     <value>673, 17</value>
   </metadata>
   </metadata>
+  <metadata name="toolStrip5.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
+    <value>999, 17</value>
+  </metadata>
+  <metadata name="toolStrip6.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
+    <value>1104, 17</value>
+  </metadata>
   <metadata name="timerFollow.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
   <metadata name="timerFollow.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
     <value>778, 17</value>
     <value>778, 17</value>
   </metadata>
   </metadata>

+ 0 - 3
src/MoonSharp.Interpreter.Tests/MoonSharp.Interpreter.Tests.csproj

@@ -196,9 +196,6 @@
     <None Include="TestMore\301-basic.t">
     <None Include="TestMore\301-basic.t">
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>
     </None>
     </None>
-    <None Include="TestMore\303-package.t">
-      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
-    </None>
     <None Include="TestMore\304-string.t">
     <None Include="TestMore\304-string.t">
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>
     </None>
     </None>

+ 0 - 214
src/MoonSharp.Interpreter.Tests/TestMore/303-package.t

@@ -1,214 +0,0 @@
-#! /usr/bin/lua
---
--- lua-TestMore : <http://fperrad.github.com/lua-TestMore/>
---
--- Copyright (C) 2009-2013, Perrad Francois
---
--- This code is licensed under the terms of the MIT/X11 license,
--- like Lua itself.
---
-
---[[
-
-=head1 Lua Package Library
-
-=head2 Synopsis
-
-    % prove 303-package.t
-
-=head2 Description
-
-Tests Lua Package Library
-
-See "Lua 5.2 Reference Manual", section 6.3 "Modules",
-L<http://www.lua.org/manual/5.2/manual.html#6.3>.
-
-=cut
-
---]]
-
-require 'Test.More'
-
-plan(33)
-
-ok(package.loaded._G, "table package.loaded")
-ok(package.loaded.coroutine)
-ok(package.loaded.io)
-ok(package.loaded.math)
-ok(package.loaded.os)
-ok(package.loaded.package)
-ok(package.loaded.string)
-ok(package.loaded.table)
-
-type_ok(package.path, 'string')
-
-type_ok(package.preload, 'table', "table package.preload")
-is(# package.preload, 0)
-
-if (platform and platform.compat) or jit then
-    type_ok(package.loaders, 'table', "table package.loaders")
-    if jit then
-        todo("LuaJIT TODO. package.searchers", 1)
-    end
-    is(package.searchers, package.loaders, "alias")
-else
-    type_ok(package.searchers, 'table', "table package.searchers")
-    is(package.loaders, nil)
-end
-
-m = {}
-if (platform and platform.compat) or jit then
-    package.seeall(m)
-    m.pass("function package.seeall")
-else
-    is(package.seeall, nil, "package.seeall (removed)")
-end
-
-local m = require 'Test.More'
-m.ok(true, "function require")
-is(m, package.loaded['Test.More'])
-
-p = package.searchpath('Test.More', package.path)
-type_ok(p, 'string', "searchpath")
-p = package.searchpath('Test.More', 'bad path')
-is(p, nil)
-
-f = io.open('complex.lua', 'w')
-f:write [[
-complex = {}
-
-function complex.new (r, i) return {r=r, i=i} end
-
---defines a constant 'i'
-complex.i = complex.new(0, 1)
-
-function complex.add (c1, c2)
-    return complex.new(c1.r + c2.r, c1.i + c2.i)
-end
-
-function complex.sub (c1, c2)
-    return complex.new(c1.r - c2.r, c1.i - c2.i)
-end
-
-function complex.mul (c1, c2)
-    return complex.new(c1.r*c2.r - c1.i*c2.i,
-                       c1.r*c2.i + c1.i*c2.r)
-end
-
-local function inv (c)
-    local n = c.r^2 + c.i^2
-    return complex.new(c.r/n, -c.i/n)
-end
-
-function complex.div (c1, c2)
-    return complex.mul(c1, inv(c2))
-end
-
-return complex
-]]
-f:close()
-m = require 'complex'
-is(m, complex, "function require")
-is(complex.i.r, 0)
-is(complex.i.i, 1)
-os.remove('complex.lua') -- clean up
-
-error_like(function () require('no_module') end,
-           "^[^:]+:%d+: module 'no_module' not found:",
-           "function require (no module)")
-
-f = io.open('foo.lua', 'w')
-f:write [[?syntax error?]]
-f:close()
-error_like(function () require('foo') end,
-           "^error loading module 'foo' from file '%.[/\\]foo%.lua':",
-           "function require (syntax error)")
-os.remove('foo.lua') -- clean up
-
-foo = {}
-foo.bar = 1234
-function foo_loader ()
-    return foo
-end
-package.preload.foo = foo_loader
-m = require 'foo'
-assert(m == foo)
-is(m.bar, 1234, "function require & package.preload")
-
-f = io.open('bar.lua', 'w')
-f:write [[
-    print("    in bar.lua", ...)
-    a = ...
-]]
-f:close()
-a = nil
-require 'bar'
-is(a, 'bar', "function require (arg)")
-os.remove('bar.lua') -- clean up
-
-f = io.open('cplx.lua', 'w')
-f:write [[
--- print('cplx.lua', ...)
-local _G = _G
-_ENV = nil
-local cplx = {}
-
-local function new (r, i) return {r=r, i=i} end
-cplx.new = new
-
---defines a constant 'i'
-cplx.i = new(0, 1)
-
-function cplx.add (c1, c2)
-    return new(c1.r + c2.r, c1.i + c2.i)
-end
-
-function cplx.sub (c1, c2)
-    return new(c1.r - c2.r, c1.i - c2.i)
-end
-
-function cplx.mul (c1, c2)
-    return new(c1.r*c2.r - c1.i*c2.i,
-               c1.r*c2.i + c1.i*c2.r)
-end
-
-local function inv (c)
-    local n = c.r^2 + c.i^2
-    return new(c.r/n, -c.i/n)
-end
-
-function cplx.div (c1, c2)
-    return mul(c1, inv(c2))
-end
-
-_G.cplx = cplx
-return cplx
-]]
-f:close()
-require 'cplx'
-is(cplx.i.r, 0, "function require & module")
-is(cplx.i.i, 1)
-os.remove('cplx.lua') -- clean up
-
-if (platform and platform.compat) or jit then
-    is(mod, nil, "function module & seeall")
-    module('mod', package.seeall)
-    type_ok(mod, 'table')
-    is(mod, package.loaded.mod)
-
-    is(modz, nil, "function module")
-    local _G = _G
-    module('modz')
-    _G.type_ok(_G.modz, 'table')
-    _G.is(_G.modz, _G.package.loaded.modz)
-else
-    is(module, nil, "module (removed)")
-    skip("module (removed)", 5)
-end
-
--- Local Variables:
---   mode: lua
---   lua-indent-level: 4
---   fill-column: 100
--- End:
--- vim: ft=lua expandtab shiftwidth=4:

+ 0 - 10
src/MoonSharp.Interpreter.Tests/TestMore/TestMoreTests.cs

@@ -222,22 +222,12 @@ namespace MoonSharp.Interpreter.Tests
 			TapRunner.Run(@"TestMore\301-basic.t");
 			TapRunner.Run(@"TestMore\301-basic.t");
 		}
 		}
 
 
-
-		[Test]
-		[Ignore]
-		public void TestMore_303_package()
-		{
-			TapRunner.Run(@"TestMore\303-package.t");
-		}
-
-
 		[Test]
 		[Test]
 		public void TestMore_304_string()
 		public void TestMore_304_string()
 		{
 		{
 			TapRunner.Run(@"TestMore\304-string.t");
 			TapRunner.Run(@"TestMore\304-string.t");
 		}
 		}
 
 
-
 		[Test]
 		[Test]
 		public void TestMore_305_table()
 		public void TestMore_305_table()
 		{
 		{

+ 1 - 1
src/MoonSharp.Interpreter/Debugging/IDebugger.cs

@@ -9,7 +9,7 @@ namespace MoonSharp.Interpreter.Debugging
 	public interface IDebugger
 	public interface IDebugger
 	{
 	{
 		void SetSourceCode(ByteCode byteCode, string[] code);
 		void SetSourceCode(ByteCode byteCode, string[] code);
-		DebuggerAction GetAction(int ip);
+		DebuggerAction GetAction(int ip, SourceRef sourceref);
 		void Update(WatchType watchType, List<WatchItem> items);
 		void Update(WatchType watchType, List<WatchItem> items);
 		List<string> GetWatchItems();
 		List<string> GetWatchItems();
 	}
 	}

+ 53 - 2
src/MoonSharp.Interpreter/Debugging/SourceCode.cs

@@ -5,15 +5,66 @@ using System.Text;
 
 
 namespace MoonSharp.Interpreter.Debugging
 namespace MoonSharp.Interpreter.Debugging
 {
 {
-	public class SourceCode
+	public class SourceCode : IScriptPrivateResource
 	{
 	{
 		public string Name { get; private set; }
 		public string Name { get; private set; }
 		public string Code { get; private set; }
 		public string Code { get; private set; }
+		public string[] Lines { get; private set; }
+		public Script OwnerScript { get; private set; }
+		public int SourceID { get; private set; }
 
 
-		internal SourceCode(string name, string code)
+		internal SourceCode(string name, string code, int sourceID, Script ownerScript)
 		{
 		{
+			List<string> lines = new List<string>();
+
 			Name = name;
 			Name = name;
 			Code = code;
 			Code = code;
+
+			lines.Add(string.Format("-- Begin of chunk : {0} ", name));
+
+			lines.AddRange(Code.Split('\n'));
+
+			Lines = lines.ToArray();
+
+			OwnerScript = ownerScript;
+			SourceID = sourceID;
+		}
+
+		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();
+		}
+
+		private int AdjustStrIndex(string str, int loc)
+		{
+			return Math.Max(Math.Min(str.Length, loc), 0);
 		}
 		}
 	}
 	}
 }
 }

+ 20 - 5
src/MoonSharp.Interpreter/Debugging/SourceRef.cs

@@ -10,16 +10,31 @@ namespace MoonSharp.Interpreter.Debugging
 		public int SourceIdx { get; private set; }
 		public int SourceIdx { get; private set; }
 		public int FromChar { get; private set; }
 		public int FromChar { get; private set; }
 		public int ToChar { get; private set; }
 		public int ToChar { get; private set; }
-		public int Line { get; private set; }
-		public bool IsStatement { get; private set; }
+		public int FromLine { get; private set; }
+		public int ToLine { get; private set; }
+		public bool IsStepStop { get; private set; }
 
 
-		internal SourceRef(int sourceIdx, int from, int to, int line, bool isStatement)
+		internal SourceRef(int sourceIdx, int from, int to, int fromline, int toline, bool isStepStop)
 		{
 		{
 			SourceIdx = sourceIdx;
 			SourceIdx = sourceIdx;
 			FromChar = from;
 			FromChar = from;
 			ToChar = to;
 			ToChar = to;
-			Line = line;
-			IsStatement = isStatement;
+			FromLine = fromline;
+			ToLine = toline;
+			IsStepStop = isStepStop;
+		}
+
+		public SourceRef(int sourceIdx)
+			: this(sourceIdx, 0, int.MaxValue, 0, 0, true)
+		{
+		}
+
+		public override string ToString()
+		{
+			return string.Format("[{0}]{1} ({2}, {3}) -> ({4}, {5})",
+				SourceIdx, IsStepStop ? "*" : " ",
+				FromLine, FromChar,
+				ToLine, ToChar);
 		}
 		}
 	}
 	}
 }
 }

+ 2 - 2
src/MoonSharp.Interpreter/Execution/ScriptLoadingContext.cs

@@ -2,13 +2,13 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using MoonSharp.Interpreter.Debugging;
 
 
 namespace MoonSharp.Interpreter.Execution
 namespace MoonSharp.Interpreter.Execution
 {
 {
 	class ScriptLoadingContext
 	class ScriptLoadingContext
 	{
 	{
 		public BuildTimeScope Scope { get; set; }
 		public BuildTimeScope Scope { get; set; }
-		public string SourceName { get; set; }
-		public int SourceIdx { get; set; }
+		public SourceCode Source { get; set; }
 	}
 	}
 }
 }

+ 78 - 38
src/MoonSharp.Interpreter/Execution/VM/ByteCode.cs

@@ -8,12 +8,16 @@ using System.Linq;
 using System.Text;
 using System.Text;
 using System.Threading;
 using System.Threading;
 using MoonSharp.Interpreter.DataStructs;
 using MoonSharp.Interpreter.DataStructs;
+using MoonSharp.Interpreter.Debugging;
 
 
 namespace MoonSharp.Interpreter.Execution.VM
 namespace MoonSharp.Interpreter.Execution.VM
 {
 {
 	public class ByteCode : ITrackableReference
 	public class ByteCode : ITrackableReference
 	{
 	{
 		public List<Instruction> Code = new List<Instruction>();
 		public List<Instruction> Code = new List<Instruction>();
+		private List<SourceRef> m_SourceRefStack = new List<SourceRef>();
+		private SourceRef m_CurrentSourceRef = null;
+
 		internal LoopTracker LoopTracker = new LoopTracker();
 		internal LoopTracker LoopTracker = new LoopTracker();
 
 
 
 
@@ -25,6 +29,42 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		#endregion
 		#endregion
 
 
+		public IDisposable EnterSource(SourceRef sref)
+		{
+			return new SourceCodeStackGuard(sref, this);
+		}
+
+
+		private class SourceCodeStackGuard : IDisposable
+		{
+			ByteCode m_Bc;
+
+			public SourceCodeStackGuard(SourceRef sref, ByteCode bc)
+			{
+				m_Bc = bc;
+				m_Bc.PushSourceRef(sref);
+			}
+
+			public void Dispose()
+			{
+				m_Bc.PopSourceRef();
+			}
+		}
+
+
+		public void PushSourceRef(SourceRef sref)
+		{
+			m_SourceRefStack.Add(sref);
+			m_CurrentSourceRef = sref;
+		}
+
+		public void PopSourceRef()
+		{
+			m_SourceRefStack.RemoveAt(m_SourceRefStack.Count - 1);
+			m_CurrentSourceRef = (m_SourceRefStack.Count > 0) ? m_SourceRefStack[m_SourceRefStack.Count - 1] : null;
+		}
+
+
 		public void Dump(string file)
 		public void Dump(string file)
 		{
 		{
 			StringBuilder sb = new StringBuilder();
 			StringBuilder sb = new StringBuilder();
@@ -62,53 +102,53 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		public Instruction Emit_Nop(string comment)
 		public Instruction Emit_Nop(string comment)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Nop, Name = comment });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Nop, Name = comment });
 		}
 		}
 
 
 		public Instruction Emit_Invalid(string type)
 		public Instruction Emit_Invalid(string type)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Invalid, Name = type });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Invalid, Name = type });
 		}
 		}
 
 
 		public Instruction Emit_Pop(int num = 1)
 		public Instruction Emit_Pop(int num = 1)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Pop, NumVal = num });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Pop, NumVal = num });
 		}
 		}
 
 
 		public void Emit_Call(int argCount, string debugName)
 		public void Emit_Call(int argCount, string debugName)
 		{
 		{
-			AppendInstruction(new Instruction() { OpCode = OpCode.Call, NumVal = argCount, Name = debugName });
+			AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Call, NumVal = argCount, Name = debugName });
 		}
 		}
 
 
 		public void Emit_ThisCall(int argCount, string debugName)
 		public void Emit_ThisCall(int argCount, string debugName)
 		{
 		{
-			AppendInstruction(new Instruction() { OpCode = OpCode.ThisCall, NumVal = argCount, Name = debugName });
+			AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.ThisCall, NumVal = argCount, Name = debugName });
 		}
 		}
 
 
 		public Instruction Emit_Literal(DynValue value)
 		public Instruction Emit_Literal(DynValue value)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Literal, Value = value });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Literal, Value = value });
 		}
 		}
 
 
 		public Instruction Emit_Jump(OpCode jumpOpCode, int idx, int optPar = 0)
 		public Instruction Emit_Jump(OpCode jumpOpCode, int idx, int optPar = 0)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = jumpOpCode, NumVal = idx, NumVal2 = optPar });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = jumpOpCode, NumVal = idx, NumVal2 = optPar });
 		}
 		}
 
 
 		public Instruction Emit_MkTuple(int cnt)
 		public Instruction Emit_MkTuple(int cnt)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.MkTuple, NumVal = cnt });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.MkTuple, NumVal = cnt });
 		}
 		}
 
 
 		public Instruction Emit_Operator(OpCode opcode)
 		public Instruction Emit_Operator(OpCode opcode)
 		{
 		{
-			var i = AppendInstruction(new Instruction() { OpCode = opcode });
+			var i = AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = opcode });
 
 
 			if (opcode == OpCode.LessEq)
 			if (opcode == OpCode.LessEq)
-				AppendInstruction(new Instruction() { OpCode = OpCode.CNot });
+				AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.CNot });
 
 
 			if (opcode == OpCode.Eq || opcode == OpCode.Less)
 			if (opcode == OpCode.Eq || opcode == OpCode.Less)
-				AppendInstruction(new Instruction() { OpCode = OpCode.ToBool });
+				AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.ToBool });
 
 
 			return i;
 			return i;
 		}
 		}
@@ -117,73 +157,73 @@ namespace MoonSharp.Interpreter.Execution.VM
 		//[Conditional("EMIT_DEBUG_OPS")]
 		//[Conditional("EMIT_DEBUG_OPS")]
 		public void Emit_Debug(string str)
 		public void Emit_Debug(string str)
 		{
 		{
-			AppendInstruction(new Instruction() { OpCode = OpCode.Debug, Name = str.Substring(0, Math.Min(32, str.Length)) });
+			AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Debug, Name = str.Substring(0, Math.Min(32, str.Length)) });
 		}
 		}
 
 
 		public Instruction Emit_Enter(RuntimeScopeBlock runtimeScopeBlock)
 		public Instruction Emit_Enter(RuntimeScopeBlock runtimeScopeBlock)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Enter, NumVal = runtimeScopeBlock.From, NumVal2 = runtimeScopeBlock.ToInclusive });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Enter, NumVal = runtimeScopeBlock.From, NumVal2 = runtimeScopeBlock.ToInclusive });
 		}
 		}
 
 
 		public Instruction Emit_Leave(RuntimeScopeBlock runtimeScopeBlock)
 		public Instruction Emit_Leave(RuntimeScopeBlock runtimeScopeBlock)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Leave, NumVal = runtimeScopeBlock.From, NumVal2 = runtimeScopeBlock.To });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Leave, NumVal = runtimeScopeBlock.From, NumVal2 = runtimeScopeBlock.To });
 		}
 		}
 
 
 		public Instruction Emit_Exit(RuntimeScopeBlock runtimeScopeBlock)
 		public Instruction Emit_Exit(RuntimeScopeBlock runtimeScopeBlock)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Exit, NumVal = runtimeScopeBlock.From, NumVal2 = runtimeScopeBlock.ToInclusive });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Exit, NumVal = runtimeScopeBlock.From, NumVal2 = runtimeScopeBlock.ToInclusive });
 		}
 		}
 
 
 		public Instruction Emit_Closure(SymbolRef[] symbols, int jmpnum)
 		public Instruction Emit_Closure(SymbolRef[] symbols, int jmpnum)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Closure, SymbolList = symbols, NumVal = jmpnum });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Closure, SymbolList = symbols, NumVal = jmpnum });
 		}
 		}
 
 
 		public Instruction Emit_Args(SymbolRef[] symbols)
 		public Instruction Emit_Args(SymbolRef[] symbols)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Args, SymbolList = symbols });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Args, SymbolList = symbols });
 		}
 		}
 
 
 		public Instruction Emit_Ret(int retvals)
 		public Instruction Emit_Ret(int retvals)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Ret, NumVal = retvals });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Ret, NumVal = retvals });
 		}
 		}
 
 
 		public Instruction Emit_ToNum(int stage = 0)
 		public Instruction Emit_ToNum(int stage = 0)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.ToNum, NumVal = stage });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.ToNum, NumVal = stage });
 		}
 		}
 
 
 		public Instruction Emit_Incr(int i)
 		public Instruction Emit_Incr(int i)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Incr, NumVal = i });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Incr, NumVal = i });
 		}
 		}
 
 
 		public Instruction Emit_NewTable()
 		public Instruction Emit_NewTable()
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.NewTable });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.NewTable });
 		}
 		}
 
 
 		public Instruction Emit_IterPrep()
 		public Instruction Emit_IterPrep()
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.IterPrep });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.IterPrep });
 		}
 		}
 
 
 		public Instruction Emit_ExpTuple(int stackOffset)
 		public Instruction Emit_ExpTuple(int stackOffset)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.ExpTuple, NumVal = stackOffset });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.ExpTuple, NumVal = stackOffset });
 		}
 		}
 
 
 		public Instruction Emit_IterUpd()
 		public Instruction Emit_IterUpd()
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.IterUpd });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.IterUpd });
 		}
 		}
 
 
 
 
 		public Instruction Emit_BeginFn(RuntimeScopeFrame m_StackFrame, string funcName)
 		public Instruction Emit_BeginFn(RuntimeScopeFrame m_StackFrame, string funcName)
 		{
 		{
-			return AppendInstruction(new Instruction()
+			return AppendInstruction(new Instruction(m_CurrentSourceRef)
 			{
 			{
 				OpCode = OpCode.BeginFn,
 				OpCode = OpCode.BeginFn,
 				SymbolList = m_StackFrame.DebugSymbols.ToArray(),
 				SymbolList = m_StackFrame.DebugSymbols.ToArray(),
@@ -195,7 +235,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		public Instruction Emit_Scalar()
 		public Instruction Emit_Scalar()
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Scalar });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Scalar });
 		}
 		}
 
 
 		public int Emit_Load(SymbolRef sym)
 		public int Emit_Load(SymbolRef sym)
@@ -204,13 +244,13 @@ namespace MoonSharp.Interpreter.Execution.VM
 			{
 			{
 				case SymbolRefType.Global:
 				case SymbolRefType.Global:
 					Emit_Load(sym.i_Env);
 					Emit_Load(sym.i_Env);
-					AppendInstruction(new Instruction() { OpCode = OpCode.Index, Value = DynValue.NewString(sym.i_Name) });
+					AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Index, Value = DynValue.NewString(sym.i_Name) });
 					return 2;
 					return 2;
 				case SymbolRefType.Local:
 				case SymbolRefType.Local:
-					AppendInstruction(new Instruction() { OpCode = OpCode.Local, Symbol = sym });
+					AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Local, Symbol = sym });
 					return 1;
 					return 1;
 				case SymbolRefType.Upvalue:
 				case SymbolRefType.Upvalue:
-					AppendInstruction(new Instruction() { OpCode = OpCode.Upvalue, Symbol = sym });
+					AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Upvalue, Symbol = sym });
 					return 1;
 					return 1;
 				default:
 				default:
 					throw new InternalErrorException("Unexpected symbol type : {0}", sym);
 					throw new InternalErrorException("Unexpected symbol type : {0}", sym);
@@ -223,13 +263,13 @@ namespace MoonSharp.Interpreter.Execution.VM
 			{
 			{
 				case SymbolRefType.Global:
 				case SymbolRefType.Global:
 					Emit_Load(sym.i_Env);
 					Emit_Load(sym.i_Env);
-					AppendInstruction(new Instruction() { OpCode = OpCode.IndexSet, Symbol = sym, NumVal = stackofs, NumVal2 = tupleidx, Value = DynValue.NewString(sym.i_Name) });
+					AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.IndexSet, Symbol = sym, NumVal = stackofs, NumVal2 = tupleidx, Value = DynValue.NewString(sym.i_Name) });
 					return 2;
 					return 2;
 				case SymbolRefType.Local:
 				case SymbolRefType.Local:
-					AppendInstruction(new Instruction() { OpCode = OpCode.StoreLcl, Symbol = sym, NumVal = stackofs, NumVal2 = tupleidx });
+					AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.StoreLcl, Symbol = sym, NumVal = stackofs, NumVal2 = tupleidx });
 					return 1;
 					return 1;
 				case SymbolRefType.Upvalue:
 				case SymbolRefType.Upvalue:
-					AppendInstruction(new Instruction() { OpCode = OpCode.StoreUpv, Symbol = sym, NumVal = stackofs, NumVal2 = tupleidx });
+					AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.StoreUpv, Symbol = sym, NumVal = stackofs, NumVal2 = tupleidx });
 					return 1;
 					return 1;
 				default:
 				default:
 					throw new InternalErrorException("Unexpected symbol type : {0}", sym);
 					throw new InternalErrorException("Unexpected symbol type : {0}", sym);
@@ -238,32 +278,32 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		public Instruction Emit_TblInitN()
 		public Instruction Emit_TblInitN()
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.TblInitN });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.TblInitN });
 		}
 		}
 
 
 		public Instruction Emit_TblInitI(bool lastpos)
 		public Instruction Emit_TblInitI(bool lastpos)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.TblInitI, NumVal = lastpos ? 1 : 0 });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.TblInitI, NumVal = lastpos ? 1 : 0 });
 		}
 		}
 
 
 		public Instruction Emit_Index(DynValue index = null)
 		public Instruction Emit_Index(DynValue index = null)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Index, Value = index });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Index, Value = index });
 		}
 		}
 
 
 		public Instruction Emit_IndexSet(int stackofs, int tupleidx, DynValue index = null)
 		public Instruction Emit_IndexSet(int stackofs, int tupleidx, DynValue index = null)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.IndexSet, NumVal = stackofs, NumVal2 = tupleidx, Value = index });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.IndexSet, NumVal = stackofs, NumVal2 = tupleidx, Value = index });
 		}
 		}
 
 
 		public Instruction Emit_Copy(int numval)
 		public Instruction Emit_Copy(int numval)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Copy, NumVal = numval });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Copy, NumVal = numval });
 		}
 		}
 
 
 		public Instruction Emit_Swap(int p1, int p2)
 		public Instruction Emit_Swap(int p1, int p2)
 		{
 		{
-			return AppendInstruction(new Instruction() { OpCode = OpCode.Swap, NumVal = p1, NumVal2 = p2 });
+			return AppendInstruction(new Instruction(m_CurrentSourceRef) { OpCode = OpCode.Swap, NumVal = p1, NumVal2 = p2 });
 		}
 		}
 
 
 	}
 	}

+ 5 - 0
src/MoonSharp.Interpreter/Execution/VM/Instruction.cs

@@ -18,6 +18,11 @@ namespace MoonSharp.Interpreter.Execution.VM
 		public bool Breakpoint;
 		public bool Breakpoint;
 		public SourceRef SourceCodeRef;
 		public SourceRef SourceCodeRef;
 
 
+		public Instruction(SourceRef sourceref)
+		{
+			SourceCodeRef = sourceref;
+		}
+
 		public override string ToString()
 		public override string ToString()
 		{
 		{
 			string append = "";
 			string append = "";

+ 1 - 1
src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_Debugger.cs

@@ -35,7 +35,7 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 			while (true)
 			while (true)
 			{
 			{
-				var action = m_Debug.DebuggerAttached.GetAction(instructionPtr);
+				var action = m_Debug.DebuggerAttached.GetAction(instructionPtr, instr.SourceCodeRef);
 
 
 				switch (action.Action)
 				switch (action.Action)
 				{
 				{

+ 15 - 2
src/MoonSharp.Interpreter/Execution/VM/Processor/Processor_Errors.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using MoonSharp.Interpreter.Debugging;
 
 
 namespace MoonSharp.Interpreter.Execution.VM
 namespace MoonSharp.Interpreter.Execution.VM
 {
 {
@@ -38,8 +39,6 @@ namespace MoonSharp.Interpreter.Execution.VM
 
 
 		private void FillDebugData(InterpreterException ex, int ip)
 		private void FillDebugData(InterpreterException ex, int ip)
 		{
 		{
-			ex.DecoratedMessage = "chunk:0: " + ex.Message;
-
 			// adjust IP
 			// adjust IP
 			if (ip == YIELD_SPECIAL_TRAP)
 			if (ip == YIELD_SPECIAL_TRAP)
 				ip = m_SavedInstructionPtr;
 				ip = m_SavedInstructionPtr;
@@ -47,6 +46,20 @@ namespace MoonSharp.Interpreter.Execution.VM
 				ip -= 1;
 				ip -= 1;
 
 
 			ex.InstructionPtr = ip;
 			ex.InstructionPtr = ip;
+
+			if (ip >= 0 && ip < m_RootChunk.Code.Count)
+			{
+				Instruction I = m_RootChunk.Code[ip];
+				SourceRef sref = I.SourceCodeRef;
+				SourceCode sc = m_Script.GetSourceCode(sref.SourceIdx);
+
+				ex.DecoratedMessage = string.Format("{0}:{1}: {2}", sc.Name, sref.FromLine, ex.Message);
+			}
+			else
+			{
+				ex.DecoratedMessage = string.Format("bytecode:{0}: {1}", ip, ex.Message);
+			}
+			
 			ex.CallStack = GetCallStack(ip);
 			ex.CallStack = GetCallStack(ip);
 		}
 		}
 
 

+ 10 - 7
src/MoonSharp.Interpreter/Grammar/Lua.g4

@@ -71,7 +71,7 @@ exp
 	;
 	;
 
 
 var
 var
-    : (NAME | '(' exp ')' varSuffix) varSuffix*
+    : (NAME | PAREN_OPEN exp PAREN_CLOSE varSuffix) varSuffix*
     ;
     ;
 
 
 prefixexp
 prefixexp
@@ -80,7 +80,7 @@ prefixexp
 
 
 //
 //
 varOrExp
 varOrExp
-    : var | '(' exp ')'
+    : var | PAREN_OPEN exp PAREN_CLOSE
     ;
     ;
 
 
 
 
@@ -96,7 +96,7 @@ varSuffix
 
 
 // Possible args to func call : list of expressions, table ctor, string literal
 // Possible args to func call : list of expressions, table ctor, string literal
 args
 args
-    : '(' explist? ')' | tableconstructor | string
+    : PAREN_OPEN explist? PAREN_CLOSE | tableconstructor | string
     ;
     ;
 
 
 
 
@@ -115,7 +115,7 @@ anonfunctiondef
 
 
 // A func body from the parlist to end.
 // A func body from the parlist to end.
 funcbody
 funcbody
-    : '(' parlist? ')' block 'end'
+    : PAREN_OPEN parlist? PAREN_CLOSE block END
     ;
     ;
 
 
 // The list of params in a function def
 // The list of params in a function def
@@ -126,7 +126,7 @@ parlist
 
 
 // A table ctor
 // A table ctor
 tableconstructor
 tableconstructor
-    : '{' fieldlist? '}'
+    : CURLY_OPEN fieldlist? CURLY_CLOSE
     ;
     ;
 
 
 
 
@@ -183,7 +183,10 @@ THEN : 'then';
 TRUE : 'true';
 TRUE : 'true';
 UNTIL : 'until';
 UNTIL : 'until';
 WHILE : 'while';
 WHILE : 'while';
-
+CURLY_OPEN : '{';
+CURLY_CLOSE : '}';
+PAREN_OPEN : '(';
+PAREN_CLOSE: ')';
 
 
 operatorbinary 
 operatorbinary 
 	: OR | AND | '<' | '>' | '<=' | '>=' | '~=' | '==' | '..' | '+' | '-' | '*' | '/' | '%' ;
 	: OR | AND | '<' | '>' | '<=' | '>=' | '~=' | '==' | '..' | '+' | '-' | '*' | '/' | '%' ;
@@ -276,7 +279,7 @@ HexDigit
 
 
 COMMENT
 COMMENT
     : '--[' NESTED_STR ']' -> channel(HIDDEN)
     : '--[' NESTED_STR ']' -> channel(HIDDEN)
-    ;
+    ; 
     
     
 LINE_COMMENT
 LINE_COMMENT
     : '--'
     : '--'

+ 2 - 2
src/MoonSharp.Interpreter/MoonSharp.Interpreter.csproj

@@ -219,6 +219,7 @@
     <Compile Include="Modules\MoonSharpModuleAttribute.cs">
     <Compile Include="Modules\MoonSharpModuleAttribute.cs">
       <SubType>Code</SubType>
       <SubType>Code</SubType>
     </Compile>
     </Compile>
+    <Compile Include="Tree\Antlr_Interface\AntlrErrorListener.cs" />
     <Compile Include="Tree\Expressions\AdjustmentExpression.cs" />
     <Compile Include="Tree\Expressions\AdjustmentExpression.cs" />
     <Compile Include="Tree\Expressions\BinaryOperatorExpression.cs" />
     <Compile Include="Tree\Expressions\BinaryOperatorExpression.cs" />
     <Compile Include="Tree\Expressions\PowerOperatorExpression.cs" />
     <Compile Include="Tree\Expressions\PowerOperatorExpression.cs" />
@@ -234,7 +235,7 @@
     <Compile Include="Tree\Expression.cs" />
     <Compile Include="Tree\Expression.cs" />
     <Compile Include="Tree\Expressions\OperatorExpression.cs" />
     <Compile Include="Tree\Expressions\OperatorExpression.cs" />
     <Compile Include="Tree\Expressions\SymbolRefExpression.cs" />
     <Compile Include="Tree\Expressions\SymbolRefExpression.cs" />
-    <Compile Include="Tree\Loader_Antlr.cs" />
+    <Compile Include="Tree\Antlr_Interface\Loader_Antlr.cs" />
     <Compile Include="Tree\Loop.cs" />
     <Compile Include="Tree\Loop.cs" />
     <Compile Include="Tree\NodeBase.cs" />
     <Compile Include="Tree\NodeBase.cs" />
     <Compile Include="Tree\NodeFactory.cs" />
     <Compile Include="Tree\NodeFactory.cs" />
@@ -251,7 +252,6 @@
     <Compile Include="Tree\Statements\IfStatement.cs" />
     <Compile Include="Tree\Statements\IfStatement.cs" />
     <Compile Include="Tree\Statement.cs" />
     <Compile Include="Tree\Statement.cs" />
     <Compile Include="Tree\Statements\LabelStatement.cs" />
     <Compile Include="Tree\Statements\LabelStatement.cs" />
-    <Compile Include="Tree\Statements\LocalAssignmentStatement.cs" />
     <Compile Include="Tree\Statements\NullStatement.cs" />
     <Compile Include="Tree\Statements\NullStatement.cs" />
     <Compile Include="Tree\Statements\RepeatStatement.cs" />
     <Compile Include="Tree\Statements\RepeatStatement.cs" />
     <Compile Include="Tree\Statements\ReturnStatement.cs" />
     <Compile Include="Tree\Statements\ReturnStatement.cs" />

+ 33 - 17
src/MoonSharp.Interpreter/Script.cs

@@ -29,7 +29,7 @@ namespace MoonSharp.Interpreter
 		IScriptLoader m_ScriptLoader = DefaultScriptLoader;
 		IScriptLoader m_ScriptLoader = DefaultScriptLoader;
 		Table[] m_TypeMetatables = new Table[(int)LuaTypeExtensions.MaxMetaTypes];
 		Table[] m_TypeMetatables = new Table[(int)LuaTypeExtensions.MaxMetaTypes];
 
 
-	
+
 		static Script()
 		static Script()
 		{
 		{
 			DefaultScriptLoader = new ClassicLuaScriptLoader();
 			DefaultScriptLoader = new ClassicLuaScriptLoader();
@@ -104,18 +104,13 @@ namespace MoonSharp.Interpreter
 		/// </returns>
 		/// </returns>
 		public DynValue LoadFunction(string code, Table globalTable = null, string funcFriendlyName = null)
 		public DynValue LoadFunction(string code, Table globalTable = null, string funcFriendlyName = null)
 		{
 		{
-			string chunkName = string.Format("<string:{0:X4}>", m_Sources.Count);
+			string chunkName = string.Format("libfunc_{0}", funcFriendlyName ?? m_Sources.Count.ToString());
 
 
-			SourceCode source = new SourceCode(funcFriendlyName ?? chunkName, code);
+			SourceCode source = new SourceCode(chunkName, code, m_Sources.Count, this);
 
 
-			m_Sources.Add(source);
+			int address = Loader_Antlr.LoadFunction(this, source, m_ByteCode, globalTable ?? m_GlobalTable);
 
 
-			int address = Loader_Antlr.LoadFunction(this, 
-				code,
-				m_ByteCode,
-				funcFriendlyName ?? chunkName,
-				m_Sources.Count - 1,
-				globalTable ?? m_GlobalTable);
+			m_Sources.Add(source);
 
 
 			if (m_Debugger != null)
 			if (m_Debugger != null)
 				m_Debugger.SetSourceCode(m_ByteCode, null);
 				m_Debugger.SetSourceCode(m_ByteCode, null);
@@ -136,19 +131,17 @@ namespace MoonSharp.Interpreter
 		/// </returns>
 		/// </returns>
 		public DynValue LoadString(string code, Table globalTable = null, string codeFriendlyName = null)
 		public DynValue LoadString(string code, Table globalTable = null, string codeFriendlyName = null)
 		{
 		{
-			string chunkName = string.Format("<string:{0:X4}>", m_Sources.Count);
-
-			SourceCode source = new SourceCode(codeFriendlyName ?? chunkName, code);
+			string chunkName = string.Format("{0}", codeFriendlyName ?? "chunk_" + m_Sources.Count.ToString());
 
 
-			m_Sources.Add(source);
+			SourceCode source = new SourceCode(codeFriendlyName ?? chunkName, code, m_Sources.Count, this);
 
 
 			int address = Loader_Antlr.LoadChunk(this,
 			int address = Loader_Antlr.LoadChunk(this,
-				code,
+				source,
 				m_ByteCode,
 				m_ByteCode,
-				codeFriendlyName ?? chunkName,
-				m_Sources.Count - 1,
 				globalTable ?? m_GlobalTable);
 				globalTable ?? m_GlobalTable);
 
 
+			m_Sources.Add(source);
+
 			if (m_Debugger != null)
 			if (m_Debugger != null)
 				m_Debugger.SetSourceCode(m_ByteCode, null);
 				m_Debugger.SetSourceCode(m_ByteCode, null);
 
 
@@ -375,6 +368,29 @@ namespace MoonSharp.Interpreter
 			m_Debugger.SetSourceCode(m_ByteCode, null);
 			m_Debugger.SetSourceCode(m_ByteCode, null);
 		}
 		}
 
 
+		/// <summary>
+		/// Gets the source code.
+		/// </summary>
+		/// <param name="sourceCodeID">The source code identifier.</param>
+		/// <returns></returns>
+		public SourceCode GetSourceCode(int sourceCodeID)
+		{
+			return m_Sources[sourceCodeID];
+		}
+
+
+		/// <summary>
+		/// Gets the source code count.
+		/// </summary>
+		/// <value>
+		/// The source code count.
+		/// </value>
+		public int SourceCodeCount
+		{
+			get { return m_Sources.Count; }
+		}
+
+
 
 
 		/// <summary>
 		/// <summary>
 		/// Loads a module as per the "require" Lua function. http://www.lua.org/pil/8.1.html
 		/// Loads a module as per the "require" Lua function. http://www.lua.org/pil/8.1.html

+ 27 - 85
src/MoonSharp.Interpreter/Tree/Loader_Antlr.cs → src/MoonSharp.Interpreter/Tree/Antlr_Interface/Loader_Antlr.cs

@@ -9,6 +9,7 @@ using Antlr4.Runtime;
 using Antlr4.Runtime.Atn;
 using Antlr4.Runtime.Atn;
 using Antlr4.Runtime.Misc;
 using Antlr4.Runtime.Misc;
 using Antlr4.Runtime.Tree;
 using Antlr4.Runtime.Tree;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Diagnostics;
 using MoonSharp.Interpreter.Diagnostics;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Execution.VM;
@@ -23,81 +24,16 @@ namespace MoonSharp.Interpreter.Tree
 	/// </summary>
 	/// </summary>
 	internal static class Loader_Antlr
 	internal static class Loader_Antlr
 	{
 	{
-		private class StringAccumulatorErrorListener : BaseErrorListener, IAntlrErrorListener<int> 
-		{
-			string m_Msg = null;
-			string m_File;
-			string m_Code = null;
-
-			public StringAccumulatorErrorListener(string filename, string code)
-			{
-				m_File = filename;
-				m_Code = code;
-			}
-
-			public override void SyntaxError(IRecognizer recognizer, IToken offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)
-			{
-				if (m_Msg == null) m_Msg = "";
-
-				m_Msg += string.Format("{0}[{1},{2}] : Syntax error near '{3} : {4}'\n",
-					m_File, line, charPositionInLine, offendingSymbol, msg);
-
-				m_Msg += UnderlineError(offendingSymbol.StartIndex, offendingSymbol.StopIndex, line, charPositionInLine);
-			}
-
-			public string Message { get { return m_Msg; } }
-
-			public override string ToString()
-			{
-				return m_Msg ?? "(null)";
-			}
-
-			public void SyntaxError(IRecognizer recognizer, int offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)
-			{
-				if (m_Msg == null) m_Msg = "";
-
-				m_Msg += string.Format("{0}[{1},{2}] : Syntax error : {3}'\n",
-					m_File, line, charPositionInLine, msg);
-
-				m_Msg += UnderlineError(-1, -1, line, charPositionInLine);
-			}
-
-			protected string UnderlineError(int startIndex, int stopIndex, int line, int charPositionInLine)
-			{
-				string input = m_Code;
-				string[] lines = input.Split('\n');
-				StringBuilder errorMessage = new StringBuilder();
-				errorMessage.AppendLine(lines[line - 1].Replace('\t', ' ').Replace('\r', ' ').Replace('\n', ' '));
 
 
-				for (int i = 0; i < charPositionInLine; i++)
-				{
-					errorMessage.Append(' ');
-				}
-
-				if (startIndex >= 0 && stopIndex >= 0)
-				{
-					for (int i = startIndex; i <= stopIndex; i++)
-						errorMessage.Append('^');
-				}
-				else
-				{
-					errorMessage.Append("^...");
-				}
-
-				errorMessage.AppendLine();
-				return errorMessage.ToString();
-			}
-		}
-
-		internal static int LoadChunk(Script script, string code, ByteCode bytecode, string sourceName, int sourceIdx, Table globalContext)
+		internal static int LoadChunk(Script script, SourceCode source, ByteCode bytecode, Table globalContext)
 		{
 		{
-			StringAccumulatorErrorListener listener = new StringAccumulatorErrorListener(sourceName, code);
+			AntlrErrorListener listener = new AntlrErrorListener(source);
 
 
 			try
 			try
 			{
 			{
-				LuaParser parser = CreateParser(script, new AntlrInputStream(code), sourceIdx, p => p.chunk(), listener);
+				LuaParser parser = CreateParser(script, new AntlrInputStream(source.Code), source.SourceID, p => p.chunk(), listener);
 
 
-				ScriptLoadingContext lcontext = CreateLoadingContext(sourceName, sourceIdx);
+				ScriptLoadingContext lcontext = CreateLoadingContext(source);
 				ChunkStatement stat;
 				ChunkStatement stat;
 
 
 				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.AstCreation))
 				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.AstCreation))
@@ -105,15 +41,18 @@ namespace MoonSharp.Interpreter.Tree
 
 
 				int beginIp = -1;
 				int beginIp = -1;
 
 
+				var srcref = new SourceRef(source.SourceID);
+
 				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.Compilation))
 				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.Compilation))
+				using (bytecode.EnterSource(srcref))
 				{
 				{
-					bytecode.Emit_Nop(string.Format("Begin chunk {0}", sourceName));
+					bytecode.Emit_Nop(string.Format("Begin chunk {0}", source.Name));
 					beginIp = bytecode.GetJumpPointForLastInstruction();
 					beginIp = bytecode.GetJumpPointForLastInstruction();
 					stat.Compile(bytecode);
 					stat.Compile(bytecode);
-					bytecode.Emit_Nop(string.Format("End chunk {0}", sourceName));
+					bytecode.Emit_Nop(string.Format("End chunk {0}", source.Name));
 				}
 				}
 
 
-				Debug_DumpByteCode(bytecode, sourceIdx);
+				Debug_DumpByteCode(bytecode, source.SourceID);
 
 
 				return beginIp;
 				return beginIp;
 			}
 			}
@@ -124,14 +63,14 @@ namespace MoonSharp.Interpreter.Tree
 			}
 			}
 		}
 		}
 
 
-		internal static int LoadFunction(Script script, string code, ByteCode bytecode, string sourceName, int sourceIdx, Table globalContext)
+		internal static int LoadFunction(Script script, SourceCode source, ByteCode bytecode, Table globalContext)
 		{
 		{
-			StringAccumulatorErrorListener listener = new StringAccumulatorErrorListener(sourceName, code);
+			AntlrErrorListener listener = new AntlrErrorListener(source);
 			try
 			try
 			{
 			{
-				LuaParser parser = CreateParser(script, new AntlrInputStream(code), sourceIdx, p => p.anonfunctiondef(), listener);
+				LuaParser parser = CreateParser(script, new AntlrInputStream(source.Code), source.SourceID, p => p.anonfunctiondef(), listener);
 
 
-				ScriptLoadingContext lcontext = CreateLoadingContext(sourceName, sourceIdx);
+				ScriptLoadingContext lcontext = CreateLoadingContext(source);
 				FunctionDefinitionExpression fndef;
 				FunctionDefinitionExpression fndef;
 
 
 				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.AstCreation))
 				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.AstCreation))
@@ -139,13 +78,16 @@ namespace MoonSharp.Interpreter.Tree
 
 
 				int beginIp = -1;
 				int beginIp = -1;
 
 
+				var srcref = new SourceRef(source.SourceID);
+
 				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.Compilation))
 				using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.Compilation))
+				using (bytecode.EnterSource(srcref))
 				{
 				{
-					bytecode.Emit_Nop(string.Format("Begin function {0}", sourceName));
-					beginIp = fndef.CompileBody(bytecode, sourceName);
-					bytecode.Emit_Nop(string.Format("End function {0}", sourceName));
+					bytecode.Emit_Nop(string.Format("Begin function {0}", source.Name));
+					beginIp = fndef.CompileBody(bytecode, source.Name);
+					bytecode.Emit_Nop(string.Format("End function {0}", source.Name));
 
 
-					Debug_DumpByteCode(bytecode, sourceIdx);
+					Debug_DumpByteCode(bytecode, source.SourceID);
 				}
 				}
 
 
 				return beginIp;
 				return beginIp;
@@ -157,7 +99,7 @@ namespace MoonSharp.Interpreter.Tree
 			}
 			}
 		}
 		}
 
 
-		private static void HandleParserError(ParseCanceledException ex, StringAccumulatorErrorListener listener)
+		private static void HandleParserError(ParseCanceledException ex, AntlrErrorListener listener)
 		{
 		{
 			string msg = listener.Message ?? (string.Format("Unknown syntax error. <eof> expected ? : {0}", ex.Message));
 			string msg = listener.Message ?? (string.Format("Unknown syntax error. <eof> expected ? : {0}", ex.Message));
 
 
@@ -185,17 +127,16 @@ namespace MoonSharp.Interpreter.Tree
 		}
 		}
 
 
 
 
-		private static ScriptLoadingContext CreateLoadingContext(string sourceName, int sourceIdx)
+		private static ScriptLoadingContext CreateLoadingContext(SourceCode source)
 		{
 		{
 			return new ScriptLoadingContext()
 			return new ScriptLoadingContext()
 			{
 			{
 				Scope = new BuildTimeScope(),
 				Scope = new BuildTimeScope(),
-				SourceIdx = sourceIdx,
-				SourceName = sourceName,
+				Source = source
 			};
 			};
 		}
 		}
 
 
-		private static LuaParser CreateParser(Script script, ICharStream charStream, int sourceIdx, Func<LuaParser, IParseTree> dumper, StringAccumulatorErrorListener errorListener)
+		private static LuaParser CreateParser(Script script, ICharStream charStream, int sourceIdx, Func<LuaParser, IParseTree> dumper, AntlrErrorListener errorListener)
 		{
 		{
 			LuaLexer lexer;
 			LuaLexer lexer;
 			LuaParser parser;
 			LuaParser parser;
@@ -221,5 +162,6 @@ namespace MoonSharp.Interpreter.Tree
 			return parser;
 			return parser;
 		}
 		}
 
 
+
 	}
 	}
 }
 }

+ 31 - 10
src/MoonSharp.Interpreter/Tree/Expressions/FunctionDefinitionExpression.cs

@@ -2,6 +2,8 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using Antlr4.Runtime;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
@@ -20,13 +22,20 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 		Table m_GlobalEnv;
 		Table m_GlobalEnv;
 		SymbolRef m_Env;
 		SymbolRef m_Env;
 
 
+		SourceRef m_Begin, m_End;
+
 		public FunctionDefinitionExpression(LuaParser.AnonfunctiondefContext context, ScriptLoadingContext lcontext, bool pushSelfParam = false, Table globalContext = null)
 		public FunctionDefinitionExpression(LuaParser.AnonfunctiondefContext context, ScriptLoadingContext lcontext, bool pushSelfParam = false, Table globalContext = null)
-			: this(context.funcbody(), lcontext, pushSelfParam, globalContext)
-		{
-		}
+			: this(context.funcbody(), lcontext, context, pushSelfParam, globalContext)
+		{ }
 
 
 
 
-		public FunctionDefinitionExpression(LuaParser.FuncbodyContext context, ScriptLoadingContext lcontext, bool pushSelfParam = false, Table globalContext = null)
+		public FunctionDefinitionExpression(LuaParser.Exp_anonfuncContext context, ScriptLoadingContext lcontext, bool pushSelfParam = false, Table globalContext = null)
+			: this(context.funcbody(), lcontext, context, pushSelfParam, globalContext)
+		{ }
+
+		public FunctionDefinitionExpression(LuaParser.FuncbodyContext context, ScriptLoadingContext lcontext, 
+			ParserRuleContext declarationContext,
+			bool pushSelfParam = false, Table globalContext = null)
 			: base(context, lcontext)
 			: base(context, lcontext)
 		{
 		{
 			var parlist = context.parlist();
 			var parlist = context.parlist();
@@ -68,6 +77,8 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 
 
 			m_StackFrame = lcontext.Scope.PopFunction();
 			m_StackFrame = lcontext.Scope.PopFunction();
 
 
+			m_Begin = BuildSourceRef(lcontext, declarationContext.Start, context.PAREN_CLOSE().Symbol);
+			m_End = BuildSourceRef(lcontext, context.Stop, context.END());
 		}
 		}
 
 
 		public SymbolRef CreateUpvalue(BuildTimeScope scope, SymbolRef symbol)
 		public SymbolRef CreateUpvalue(BuildTimeScope scope, SymbolRef symbol)
@@ -102,6 +113,8 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 
 
 		public int CompileBody(ByteCode bc, string friendlyName)
 		public int CompileBody(ByteCode bc, string friendlyName)
 		{
 		{
+			bc.PushSourceRef(m_Begin);
+
 			Instruction I = bc.Emit_Jump(OpCode.Jump, -1);
 			Instruction I = bc.Emit_Jump(OpCode.Jump, -1);
 
 
 			bc.Emit_BeginFn(m_StackFrame, friendlyName ?? "<anonymous>");
 			bc.Emit_BeginFn(m_StackFrame, friendlyName ?? "<anonymous>");
@@ -122,6 +135,9 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 
 
 			m_Statement.Compile(bc);
 			m_Statement.Compile(bc);
 
 
+			bc.PopSourceRef();
+			bc.PushSourceRef(m_End);
+
 			if (bc.GetLastInstruction().OpCode != OpCode.Ret)
 			if (bc.GetLastInstruction().OpCode != OpCode.Ret)
 				bc.Emit_Ret(0);
 				bc.Emit_Ret(0);
 
 
@@ -129,19 +145,24 @@ namespace MoonSharp.Interpreter.Tree.Expressions
 
 
 			I.NumVal = bc.GetJumpPointForNextInstruction();
 			I.NumVal = bc.GetJumpPointForNextInstruction();
 
 
+			bc.PopSourceRef();
+
 			return entryPoint;
 			return entryPoint;
 		}
 		}
 
 
 		public int Compile(ByteCode bc, Func<int> afterDecl, string friendlyName)
 		public int Compile(ByteCode bc, Func<int> afterDecl, string friendlyName)
 		{
 		{
-			SymbolRef[] symbs = m_Closure
-				//.Select((s, idx) => s.CloneLocalAndSetFrame(m_ClosureFrames[idx]))
-				.ToArray();
+			using (bc.EnterSource(m_Begin))
+			{
+				SymbolRef[] symbs = m_Closure
+					//.Select((s, idx) => s.CloneLocalAndSetFrame(m_ClosureFrames[idx]))
+					.ToArray();
 
 
-			m_ClosureInstruction = bc.Emit_Closure(symbs, bc.GetJumpPointForNextInstruction());
-			int ops = afterDecl();
+				m_ClosureInstruction = bc.Emit_Closure(symbs, bc.GetJumpPointForNextInstruction());
+				int ops = afterDecl();
 
 
-			m_ClosureInstruction.NumVal += 2 + ops;
+				m_ClosureInstruction.NumVal += 2 + ops;
+			}
 
 
 			return CompileBody(bc, friendlyName);
 			return CompileBody(bc, friendlyName);
 		}
 		}

+ 16 - 0
src/MoonSharp.Interpreter/Tree/NodeBase.cs

@@ -2,7 +2,9 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using Antlr4.Runtime;
 using Antlr4.Runtime.Tree;
 using Antlr4.Runtime.Tree;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Execution.VM;
 
 
@@ -32,7 +34,21 @@ namespace MoonSharp.Interpreter.Tree
 
 
 		public abstract void Compile(ByteCode bc);
 		public abstract void Compile(ByteCode bc);
 
 
+		protected static SourceRef BuildSourceRef(ScriptLoadingContext lcontext, IToken token, ITerminalNode terminalNode)
+		{
+			return new SourceRef(lcontext.Source.SourceID, token.Column, token.Column + terminalNode.GetText().Length, token.Line, token.Line, true);
+		}
 
 
+		protected static SourceRef BuildSourceRef(ScriptLoadingContext lcontext, IToken token1, IToken token2 = null)
+		{
+			token2 = token2 ?? token1;
+			return new SourceRef(lcontext.Source.SourceID, token1.Column, token2.Column + token2.Text.Length, token1.Line, token2.Line, true);
+		}
+
+		protected static SourceRef BuildSourceRef(ScriptLoadingContext lcontext, ITerminalNode terminalNode)
+		{
+			return BuildSourceRef(lcontext, terminalNode.Symbol, terminalNode);
+		}
 
 
 
 
 	}
 	}

+ 1 - 1
src/MoonSharp.Interpreter/Tree/NodeFactory.cs

@@ -136,7 +136,7 @@ namespace MoonSharp.Interpreter.Tree
 			if (tree is LuaParser.Exp_stringContext) tree = ((LuaParser.Exp_stringContext)tree).@string();
 			if (tree is LuaParser.Exp_stringContext) tree = ((LuaParser.Exp_stringContext)tree).@string();
 			if (tree is LuaParser.Exp_varargsContext) tree = ((LuaParser.Exp_varargsContext)tree).vararg();
 			if (tree is LuaParser.Exp_varargsContext) tree = ((LuaParser.Exp_varargsContext)tree).vararg();
 
 
-			if (tree is LuaParser.Exp_anonfuncContext) return new FunctionDefinitionExpression(((LuaParser.Exp_anonfuncContext)tree).funcbody(), lcontext);
+			if (tree is LuaParser.Exp_anonfuncContext) return new FunctionDefinitionExpression(((LuaParser.Exp_anonfuncContext)tree), lcontext);
 			if (tree is LuaParser.Exp_prefixexpContext) tree = ((LuaParser.Exp_prefixexpContext)tree).prefixexp();
 			if (tree is LuaParser.Exp_prefixexpContext) tree = ((LuaParser.Exp_prefixexpContext)tree).prefixexp();
 			if (tree is LuaParser.Exp_tabctorContext) tree = ((LuaParser.Exp_tabctorContext)tree).tableconstructor();
 			if (tree is LuaParser.Exp_tabctorContext) tree = ((LuaParser.Exp_tabctorContext)tree).tableconstructor();
 			if (tree is LuaParser.Exp_powerContext) return new PowerOperatorExpression(tree, lcontext);
 			if (tree is LuaParser.Exp_powerContext) return new PowerOperatorExpression(tree, lcontext);

+ 2 - 1
src/MoonSharp.Interpreter/Tree/Statement.cs

@@ -8,6 +8,8 @@ using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Tree.Statements;
 using MoonSharp.Interpreter.Tree.Statements;
+using MoonSharp.Interpreter.Debugging;
+using Antlr4.Runtime;
 
 
 namespace MoonSharp.Interpreter.Tree
 namespace MoonSharp.Interpreter.Tree
 {
 {
@@ -17,7 +19,6 @@ namespace MoonSharp.Interpreter.Tree
 			: base(tree, lcontext)
 			: base(tree, lcontext)
 		{ }
 		{ }
 
 
-
 	}
 	}
 
 
 
 

+ 17 - 9
src/MoonSharp.Interpreter/Tree/Statements/AssignmentStatement.cs

@@ -2,7 +2,7 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
-
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Tree.Expressions;
 using MoonSharp.Interpreter.Tree.Expressions;
@@ -13,6 +13,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 	{
 	{
 		IVariable[] m_LValues;
 		IVariable[] m_LValues;
 		Expression[] m_RValues;
 		Expression[] m_RValues;
+		SourceRef m_Ref;
 
 
 		public AssignmentStatement(LuaParser.Stat_assignmentContext context, ScriptLoadingContext lcontext)
 		public AssignmentStatement(LuaParser.Stat_assignmentContext context, ScriptLoadingContext lcontext)
 			: base(context, lcontext)
 			: base(context, lcontext)
@@ -26,6 +27,8 @@ namespace MoonSharp.Interpreter.Tree.Statements
 				.exp()
 				.exp()
 				.Select(e => NodeFactory.CreateExpression(e, lcontext))
 				.Select(e => NodeFactory.CreateExpression(e, lcontext))
 				.ToArray();
 				.ToArray();
+
+			m_Ref = BuildSourceRef(lcontext, context.Start, context.Stop);
 		}
 		}
 
 
 		public AssignmentStatement(LuaParser.Stat_localassignmentContext context, ScriptLoadingContext lcontext)
 		public AssignmentStatement(LuaParser.Stat_localassignmentContext context, ScriptLoadingContext lcontext)
@@ -49,22 +52,27 @@ namespace MoonSharp.Interpreter.Tree.Statements
 				.Select(s => new SymbolRefExpression(context, lcontext, s))
 				.Select(s => new SymbolRefExpression(context, lcontext, s))
 				.Cast<IVariable>()
 				.Cast<IVariable>()
 				.ToArray();
 				.ToArray();
+
+			m_Ref = BuildSourceRef(lcontext, context.Start, context.Stop);
 		}
 		}
 
 
 
 
 		public override void Compile(Execution.VM.ByteCode bc)
 		public override void Compile(Execution.VM.ByteCode bc)
 		{
 		{
-			foreach (var exp in m_RValues)
+			using (bc.EnterSource(m_Ref))
 			{
 			{
-				exp.Compile(bc);
-			}
+				foreach (var exp in m_RValues)
+				{
+					exp.Compile(bc);
+				}
 
 
-			for(int i = 0; i < m_LValues.Length; i++)
-				m_LValues[i].CompileAssignment(bc,
-						Math.Max(m_RValues.Length - 1 - i, 0), // index of r-value
-						i - Math.Min(i, m_RValues.Length - 1)); // index in last tuple
+				for (int i = 0; i < m_LValues.Length; i++)
+					m_LValues[i].CompileAssignment(bc,
+							Math.Max(m_RValues.Length - 1 - i, 0), // index of r-value
+							i - Math.Min(i, m_RValues.Length - 1)); // index in last tuple
 
 
-			bc.Emit_Pop(m_RValues.Length);
+				bc.Emit_Pop(m_RValues.Length);
+			}
 		}
 		}
 
 
 	}
 	}

+ 14 - 8
src/MoonSharp.Interpreter/Tree/Statements/BreakStatement.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
@@ -10,25 +11,30 @@ namespace MoonSharp.Interpreter.Tree.Statements
 {
 {
 	class BreakStatement : Statement
 	class BreakStatement : Statement
 	{
 	{
+		SourceRef m_Ref;
+
 		public BreakStatement(LuaParser.Stat_breakContext context, ScriptLoadingContext lcontext)
 		public BreakStatement(LuaParser.Stat_breakContext context, ScriptLoadingContext lcontext)
 			: base(context, lcontext)
 			: base(context, lcontext)
 		{
 		{
-			
+			m_Ref = BuildSourceRef(lcontext, context.Start, context.Stop);
 		}
 		}
 
 
 
 
 
 
 		public override void Compile(ByteCode bc)
 		public override void Compile(ByteCode bc)
 		{
 		{
-			if (bc.LoopTracker.Loops.Count == 0)
-				throw new SyntaxErrorException("<break> not inside a loop");
+			using (bc.EnterSource(m_Ref))
+			{
+				if (bc.LoopTracker.Loops.Count == 0)
+					throw new SyntaxErrorException("<break> not inside a loop");
+
+				ILoop loop = bc.LoopTracker.Loops.Peek();
 
 
-			ILoop loop = bc.LoopTracker.Loops.Peek();
-	
-			if (loop.IsBoundary())
-				throw new SyntaxErrorException("<break> not inside a loop");
+				if (loop.IsBoundary())
+					throw new SyntaxErrorException("<break> not inside a loop");
 
 
-			loop.CompileBreak(bc);
+				loop.CompileBreak(bc);
+			}
 		}
 		}
 	}
 	}
 }
 }

+ 1 - 0
src/MoonSharp.Interpreter/Tree/Statements/ChunkStatement.cs

@@ -4,6 +4,7 @@ using System.Diagnostics;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
 using Antlr4.Runtime;
 using Antlr4.Runtime;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Diagnostics;
 using MoonSharp.Interpreter.Diagnostics;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Execution.VM;

+ 12 - 0
src/MoonSharp.Interpreter/Tree/Statements/ForEachLoopStatement.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
@@ -17,6 +18,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		Expression m_RValues;
 		Expression m_RValues;
 		Statement m_Block;
 		Statement m_Block;
 		string m_DebugText;
 		string m_DebugText;
+		SourceRef m_RefFor, m_RefEnd;
 
 
 
 
 		public ForEachLoopStatement(LuaParser.Stat_foreachloopContext context, ScriptLoadingContext lcontext)
 		public ForEachLoopStatement(LuaParser.Stat_foreachloopContext context, ScriptLoadingContext lcontext)
@@ -45,12 +47,17 @@ namespace MoonSharp.Interpreter.Tree.Statements
 
 
 			m_StackFrame = lcontext.Scope.PopBlock();
 			m_StackFrame = lcontext.Scope.PopBlock();
 			m_DebugText = context.GetText();
 			m_DebugText = context.GetText();
+
+			m_RefFor = BuildSourceRef(lcontext, context.Start, context.FOR());
+			m_RefEnd = BuildSourceRef(lcontext, context.Stop, context.END());
 		}
 		}
 
 
 		public override void Compile(ByteCode bc)
 		public override void Compile(ByteCode bc)
 		{
 		{
 			//for var_1, ···, var_n in explist do block end
 			//for var_1, ···, var_n in explist do block end
 
 
+			bc.PushSourceRef(m_RefFor);
+
 			Loop L = new Loop()
 			Loop L = new Loop()
 			{
 			{
 				Scope = m_StackFrame
 				Scope = m_StackFrame
@@ -92,6 +99,9 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			// executes the stuff - stack : iterator-tuple
 			// executes the stuff - stack : iterator-tuple
 			m_Block.Compile(bc);
 			m_Block.Compile(bc);
 
 
+			bc.PopSourceRef();
+			bc.PushSourceRef(m_RefEnd);
+
 			// loop back again - stack : iterator-tuple
 			// loop back again - stack : iterator-tuple
 			bc.Emit_Leave(m_StackFrame);
 			bc.Emit_Leave(m_StackFrame);
 			bc.Emit_Jump(OpCode.Jump, start);
 			bc.Emit_Jump(OpCode.Jump, start);
@@ -109,6 +119,8 @@ namespace MoonSharp.Interpreter.Tree.Statements
 				i.NumVal = exitpointBreaks;
 				i.NumVal = exitpointBreaks;
 
 
 			endjump.NumVal = exitpointLoopExit;
 			endjump.NumVal = exitpointLoopExit;
+
+			bc.PopSourceRef();
 		}
 		}
 
 
 
 

+ 13 - 0
src/MoonSharp.Interpreter/Tree/Statements/ForLoopStatement.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
@@ -16,6 +17,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		Statement m_InnerBlock;
 		Statement m_InnerBlock;
 		SymbolRef m_VarName;
 		SymbolRef m_VarName;
 		Expression m_Start, m_End, m_Step;
 		Expression m_Start, m_End, m_Step;
+		SourceRef m_RefFor, m_RefEnd;
 
 
 		public ForLoopStatement(LuaParser.Stat_forloopContext context, ScriptLoadingContext lcontext)
 		public ForLoopStatement(LuaParser.Stat_forloopContext context, ScriptLoadingContext lcontext)
 			: base(context, lcontext)
 			: base(context, lcontext)
@@ -34,10 +36,15 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			m_VarName = lcontext.Scope.DefineLocal(context.NAME().GetText());
 			m_VarName = lcontext.Scope.DefineLocal(context.NAME().GetText());
 			m_InnerBlock = NodeFactory.CreateStatement(context.block(), lcontext);
 			m_InnerBlock = NodeFactory.CreateStatement(context.block(), lcontext);
 			m_StackFrame = lcontext.Scope.PopBlock();
 			m_StackFrame = lcontext.Scope.PopBlock();
+
+			m_RefFor = BuildSourceRef(lcontext, context.Start, context.FOR());
+			m_RefEnd = BuildSourceRef(lcontext, context.Stop, context.END());
 		}
 		}
 
 
 		public override void Compile(ByteCode bc)
 		public override void Compile(ByteCode bc)
 		{
 		{
+			bc.PushSourceRef(m_RefFor);
+
 			Loop L = new Loop()
 			Loop L = new Loop()
 			{
 			{
 				Scope = m_StackFrame
 				Scope = m_StackFrame
@@ -60,6 +67,10 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			bc.Emit_Store(m_VarName, 0, 0);
 			bc.Emit_Store(m_VarName, 0, 0);
 
 
 			m_InnerBlock.Compile(bc);
 			m_InnerBlock.Compile(bc);
+
+			bc.PopSourceRef();
+			bc.PushSourceRef(m_RefEnd);
+
 			bc.Emit_Debug("..end");
 			bc.Emit_Debug("..end");
 			bc.Emit_Leave(m_StackFrame);
 			bc.Emit_Leave(m_StackFrame);
 			bc.Emit_Incr(1);
 			bc.Emit_Incr(1);
@@ -74,6 +85,8 @@ namespace MoonSharp.Interpreter.Tree.Statements
 
 
 			jumpend.NumVal = exitpoint;
 			jumpend.NumVal = exitpoint;
 			bc.Emit_Pop(3);
 			bc.Emit_Pop(3);
+
+			bc.PopSourceRef();
 		}
 		}
 
 
 	}
 	}

+ 8 - 2
src/MoonSharp.Interpreter/Tree/Statements/FunctionCallStatement.cs

@@ -3,6 +3,7 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
 using Antlr4.Runtime.Tree;
 using Antlr4.Runtime.Tree;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
@@ -13,18 +14,23 @@ namespace MoonSharp.Interpreter.Tree.Statements
 	class FunctionCallStatement : Statement
 	class FunctionCallStatement : Statement
 	{
 	{
 		FunctionCallChainExpression m_FunctionCallChain;
 		FunctionCallChainExpression m_FunctionCallChain;
+		SourceRef m_SourceRef;
 
 
 		public FunctionCallStatement(LuaParser.Stat_functioncallContext context, ScriptLoadingContext lcontext)
 		public FunctionCallStatement(LuaParser.Stat_functioncallContext context, ScriptLoadingContext lcontext)
 			: base(context, lcontext)
 			: base(context, lcontext)
 		{
 		{
 			m_FunctionCallChain = new FunctionCallChainExpression(context, lcontext);
 			m_FunctionCallChain = new FunctionCallChainExpression(context, lcontext);
+			m_SourceRef = BuildSourceRef(lcontext, context.Start, context.Stop);
 		}
 		}
 
 
 
 
 		public override void Compile(ByteCode bc)
 		public override void Compile(ByteCode bc)
 		{
 		{
-			m_FunctionCallChain.Compile(bc);
-			bc.Emit_Pop();
+			using (bc.EnterSource(m_SourceRef))
+			{
+				m_FunctionCallChain.Compile(bc);
+				bc.Emit_Pop();
+			}
 		}
 		}
 	}
 	}
 }
 }

+ 23 - 14
src/MoonSharp.Interpreter/Tree/Statements/FunctionDefinitionStatement.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Tree.Expressions;
 using MoonSharp.Interpreter.Tree.Expressions;
@@ -14,6 +15,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		List<string> m_TableAccessors;
 		List<string> m_TableAccessors;
 		string m_MethodName;
 		string m_MethodName;
 		string m_FriendlyName;
 		string m_FriendlyName;
+		SourceRef m_SourceRef;
 
 
 		bool m_Local;
 		bool m_Local;
 		FunctionDefinitionExpression m_FuncDef;
 		FunctionDefinitionExpression m_FuncDef;
@@ -23,7 +25,9 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		{
 		{
 			m_Local = true;
 			m_Local = true;
 			m_FuncSymbol = lcontext.Scope.TryDefineLocal(context.NAME().GetText());
 			m_FuncSymbol = lcontext.Scope.TryDefineLocal(context.NAME().GetText());
-			m_FuncDef = new FunctionDefinitionExpression(context.funcbody(), lcontext);
+			m_FuncDef = new FunctionDefinitionExpression(context.funcbody(), lcontext, context);
+
+			m_SourceRef = BuildSourceRef(lcontext, context.Start, context.Stop);
 
 
 			m_FriendlyName = string.Format("{0} (local)", m_FuncSymbol.i_Name);
 			m_FriendlyName = string.Format("{0} (local)", m_FuncSymbol.i_Name);
 		}
 		}
@@ -40,7 +44,9 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			string nameOfMethodAccessor = methodaccessor != null ? methodaccessor.Text : null;
 			string nameOfMethodAccessor = methodaccessor != null ? methodaccessor.Text : null;
 			m_TableAccessors = tableaccessor != null ? tableaccessor.Select(s => s.NAME().GetText()).ToList() : new List<string>();
 			m_TableAccessors = tableaccessor != null ? tableaccessor.Select(s => s.NAME().GetText()).ToList() : new List<string>();
 
 
-			m_FuncDef = new FunctionDefinitionExpression(context.funcbody(), lcontext, nameOfMethodAccessor != null);
+			m_SourceRef = BuildSourceRef(lcontext, context.Start, context.Stop);
+
+			m_FuncDef = new FunctionDefinitionExpression(context.funcbody(), lcontext, context, nameOfMethodAccessor != null);
 
 
 			if (nameOfMethodAccessor != null || m_TableAccessors.Count > 0)
 			if (nameOfMethodAccessor != null || m_TableAccessors.Count > 0)
 			{
 			{
@@ -72,19 +78,22 @@ namespace MoonSharp.Interpreter.Tree.Statements
 
 
 		public override void Compile(Execution.VM.ByteCode bc)
 		public override void Compile(Execution.VM.ByteCode bc)
 		{
 		{
-			if (m_Local)
-			{
-				bc.Emit_Literal(DynValue.Nil);
-				bc.Emit_Store(m_FuncSymbol, 0, 0);
-				m_FuncDef.Compile(bc, () => SetFunction(bc, 2), m_FriendlyName);
-			}
-			else if (m_MethodName == null)
-			{
-				m_FuncDef.Compile(bc, () => SetFunction(bc, 1), m_FriendlyName);
-			}
-			else
+			using (bc.EnterSource(m_SourceRef))
 			{
 			{
-				m_FuncDef.Compile(bc, () => SetMethod(bc), m_FriendlyName);
+				if (m_Local)
+				{
+					bc.Emit_Literal(DynValue.Nil);
+					bc.Emit_Store(m_FuncSymbol, 0, 0);
+					m_FuncDef.Compile(bc, () => SetFunction(bc, 2), m_FriendlyName);
+				}
+				else if (m_MethodName == null)
+				{
+					m_FuncDef.Compile(bc, () => SetFunction(bc, 1), m_FriendlyName);
+				}
+				else
+				{
+					m_FuncDef.Compile(bc, () => SetMethod(bc), m_FriendlyName);
+				}
 			}
 			}
 		}
 		}
 
 

+ 36 - 12
src/MoonSharp.Interpreter/Tree/Statements/IfStatement.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
@@ -16,10 +17,12 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			public Expression Exp;
 			public Expression Exp;
 			public Statement Block;
 			public Statement Block;
 			public RuntimeScopeBlock StackFrame;
 			public RuntimeScopeBlock StackFrame;
+			public SourceRef Source;
 		}
 		}
 
 
 		List<IfBlock> m_Ifs = new List<IfBlock>();
 		List<IfBlock> m_Ifs = new List<IfBlock>();
 		Statement m_Else = null;
 		Statement m_Else = null;
+		SourceRef m_End, m_ElseRef;
 		RuntimeScopeBlock m_ElseStackFrame;
 		RuntimeScopeBlock m_ElseStackFrame;
 
 
 
 
@@ -35,7 +38,14 @@ namespace MoonSharp.Interpreter.Tree.Statements
 				var blk = context.block()[i];
 				var blk = context.block()[i];
 
 
 				lcontext.Scope.PushBlock();
 				lcontext.Scope.PushBlock();
-				var ifblock = new IfBlock() { Exp = NodeFactory.CreateExpression(exp, lcontext), Block = NodeFactory.CreateStatement(blk, lcontext) };
+				var ifblock = new IfBlock() 
+				{ 
+					Exp = NodeFactory.CreateExpression(exp, lcontext), 
+					Block = NodeFactory.CreateStatement(blk, lcontext),
+					Source = BuildSourceRef(lcontext, 
+						i == 0 ? context.IF().Symbol : context.ELSEIF()[i - 1].Symbol 
+						, exp.Stop)
+				};
 				ifblock.StackFrame = lcontext.Scope.PopBlock();
 				ifblock.StackFrame = lcontext.Scope.PopBlock();
 
 
 				m_Ifs.Add(ifblock);
 				m_Ifs.Add(ifblock);
@@ -46,7 +56,10 @@ namespace MoonSharp.Interpreter.Tree.Statements
 				lcontext.Scope.PushBlock();
 				lcontext.Scope.PushBlock();
 				m_Else = NodeFactory.CreateStatement(context.block()[bcount - 1], lcontext);
 				m_Else = NodeFactory.CreateStatement(context.block()[bcount - 1], lcontext);
 				m_ElseStackFrame = lcontext.Scope.PopBlock();
 				m_ElseStackFrame = lcontext.Scope.PopBlock();
+				m_ElseRef = BuildSourceRef(lcontext, context.ELSE()); 
 			}
 			}
+
+			m_End = BuildSourceRef(lcontext, context.Stop, context.END());
 		}
 		}
 
 
 
 
@@ -58,14 +71,20 @@ namespace MoonSharp.Interpreter.Tree.Statements
 
 
 			foreach (var ifblock in m_Ifs)
 			foreach (var ifblock in m_Ifs)
 			{
 			{
-				if (lastIfJmp != null)
-					lastIfJmp.NumVal = bc.GetJumpPointForNextInstruction();
-
-				ifblock.Exp.Compile(bc);
-				lastIfJmp = bc.Emit_Jump(OpCode.Jf, -1);
-				bc.Emit_Enter(ifblock.StackFrame);
-				ifblock.Block.Compile(bc);
-				bc.Emit_Leave(ifblock.StackFrame);
+				using (bc.EnterSource(ifblock.Source))
+				{
+					if (lastIfJmp != null)
+						lastIfJmp.NumVal = bc.GetJumpPointForNextInstruction();
+
+					ifblock.Exp.Compile(bc);
+					lastIfJmp = bc.Emit_Jump(OpCode.Jf, -1);
+					bc.Emit_Enter(ifblock.StackFrame);
+					ifblock.Block.Compile(bc);
+				}
+
+				using (bc.EnterSource(m_End))
+					bc.Emit_Leave(ifblock.StackFrame);
+
 				endJumps.Add(bc.Emit_Jump(OpCode.Jump, -1));
 				endJumps.Add(bc.Emit_Jump(OpCode.Jump, -1));
 			}
 			}
 
 
@@ -73,9 +92,14 @@ namespace MoonSharp.Interpreter.Tree.Statements
 
 
 			if (m_Else != null)
 			if (m_Else != null)
 			{
 			{
-				bc.Emit_Enter(m_ElseStackFrame);
-				m_Else.Compile(bc);
-				bc.Emit_Leave(m_ElseStackFrame);
+				using (bc.EnterSource(m_ElseRef))
+				{
+					bc.Emit_Enter(m_ElseStackFrame);
+					m_Else.Compile(bc);
+				}
+
+				using (bc.EnterSource(m_End))
+					bc.Emit_Leave(m_ElseStackFrame);
 			}
 			}
 
 
 			foreach(var endjmp in endJumps)
 			foreach(var endjmp in endJumps)

+ 0 - 40
src/MoonSharp.Interpreter/Tree/Statements/LocalAssignmentStatement.cs

@@ -1,40 +0,0 @@
-//using System;
-//using System.Collections.Generic;
-//using System.Linq;
-//using System.Text;
-
-//using MoonSharp.Interpreter.Execution;
-//using MoonSharp.Interpreter.Grammar;
-//using MoonSharp.Interpreter.Tree.Expressions;
-
-//namespace MoonSharp.Interpreter.Tree.Statements
-//{
-//	class LocalAssignmentStatement : Statement
-//	{
-//		SymbolRef[] m_Names;
-//		Expression[] m_RValues;
-
-//		public LocalAssignmentStatement(LuaParser.Stat_localassignmentContext context, ScriptLoadingContext lcontext)
-//			: base(context, lcontext)
-//		{
-//			var explist = context.explist();
-
-//			if (explist != null)
-//			{
-//				m_RValues = explist
-//				.exp()
-//				.Select(e => NodeFactory.CreateExpression(e, lcontext))
-//				.ToArray();
-//			}
-//			else
-//				m_RValues = new Expression[0];
-
-//			m_Names = context.namelist().NAME()
-//				.Select(n => n.GetText())
-//				.Select(n => lcontext.Scope.TryDefineLocal(n))
-//				.ToArray();
-//		}
-
-
-//	}
-//}

+ 15 - 1
src/MoonSharp.Interpreter/Tree/Statements/RepeatStatement.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
@@ -13,14 +14,20 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		Expression m_Condition;
 		Expression m_Condition;
 		Statement m_Block;
 		Statement m_Block;
 		RuntimeScopeBlock m_StackFrame;
 		RuntimeScopeBlock m_StackFrame;
+		SourceRef m_Repeat, m_Until;
 
 
 		public RepeatStatement(LuaParser.Stat_repeatuntilloopContext context, ScriptLoadingContext lcontext)
 		public RepeatStatement(LuaParser.Stat_repeatuntilloopContext context, ScriptLoadingContext lcontext)
 			: base(context, lcontext)
 			: base(context, lcontext)
 		{
 		{
 			lcontext.Scope.PushBlock();
 			lcontext.Scope.PushBlock();
+			var exp = context.exp();
+
 			m_Block = NodeFactory.CreateStatement(context.block(), lcontext);
 			m_Block = NodeFactory.CreateStatement(context.block(), lcontext);
-			m_Condition = NodeFactory.CreateExpression(context.exp(), lcontext);
+			m_Condition = NodeFactory.CreateExpression(exp, lcontext);
 			m_StackFrame = lcontext.Scope.PopBlock();
 			m_StackFrame = lcontext.Scope.PopBlock();
+
+			m_Repeat = BuildSourceRef(lcontext, context.Start, context.REPEAT());
+			m_Until = BuildSourceRef(lcontext, exp.Start, exp.Stop);
 		}
 		}
 
 
 
 
@@ -31,12 +38,17 @@ namespace MoonSharp.Interpreter.Tree.Statements
 				Scope = m_StackFrame
 				Scope = m_StackFrame
 			};
 			};
 
 
+			bc.PushSourceRef(m_Repeat);
+
 			bc.LoopTracker.Loops.Push(L);
 			bc.LoopTracker.Loops.Push(L);
 
 
 			int start = bc.GetJumpPointForNextInstruction();
 			int start = bc.GetJumpPointForNextInstruction();
 
 
 			bc.Emit_Enter(m_StackFrame);
 			bc.Emit_Enter(m_StackFrame);
 			m_Block.Compile(bc);
 			m_Block.Compile(bc);
+
+			bc.PopSourceRef();
+			bc.PushSourceRef(m_Until);
 			bc.Emit_Debug("..end");
 			bc.Emit_Debug("..end");
 
 
 			m_Condition.Compile(bc);
 			m_Condition.Compile(bc);
@@ -49,6 +61,8 @@ namespace MoonSharp.Interpreter.Tree.Statements
 
 
 			foreach (Instruction i in L.BreakJumps)
 			foreach (Instruction i in L.BreakJumps)
 				i.NumVal = exitpoint;
 				i.NumVal = exitpoint;
+
+			bc.PopSourceRef();
 		}
 		}
 
 
 
 

+ 19 - 7
src/MoonSharp.Interpreter/Tree/Statements/ReturnStatement.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Tree.Expressions;
 using MoonSharp.Interpreter.Tree.Expressions;
@@ -11,6 +12,7 @@ namespace MoonSharp.Interpreter.Tree.Statements
 	class ReturnStatement: Statement
 	class ReturnStatement: Statement
 	{
 	{
 		Expression m_Expression = null;
 		Expression m_Expression = null;
+		SourceRef m_Ref;
 
 
 		public ReturnStatement(LuaParser.RetstatContext context, ScriptLoadingContext lcontext)
 		public ReturnStatement(LuaParser.RetstatContext context, ScriptLoadingContext lcontext)
 			: base(context, lcontext)
 			: base(context, lcontext)
@@ -18,21 +20,31 @@ namespace MoonSharp.Interpreter.Tree.Statements
 			LuaParser.ExplistContext expr = context.children.FirstOrDefault(t => t is LuaParser.ExplistContext) as LuaParser.ExplistContext;
 			LuaParser.ExplistContext expr = context.children.FirstOrDefault(t => t is LuaParser.ExplistContext) as LuaParser.ExplistContext;
 
 
 			if (expr != null)
 			if (expr != null)
+			{
 				m_Expression = NodeFactory.CreateExpression(expr, lcontext);
 				m_Expression = NodeFactory.CreateExpression(expr, lcontext);
+				m_Ref = BuildSourceRef(lcontext, context.Start, expr.Stop);
+			}
+			else
+			{
+				m_Ref = BuildSourceRef(lcontext, context.Start, context.RETURN());
+			}
 		}
 		}
 
 
 
 
 
 
 		public override void Compile(Execution.VM.ByteCode bc)
 		public override void Compile(Execution.VM.ByteCode bc)
 		{
 		{
-			if (m_Expression != null)
-			{
-				m_Expression.Compile(bc);
-				bc.Emit_Ret(1);
-			}
-			else
+			using (bc.EnterSource(m_Ref))
 			{
 			{
-				bc.Emit_Ret(0);
+				if (m_Expression != null)
+				{
+					m_Expression.Compile(bc);
+					bc.Emit_Ret(1);
+				}
+				else
+				{
+					bc.Emit_Ret(0);
+				}
 			}
 			}
 		}
 		}
 	}
 	}

+ 12 - 2
src/MoonSharp.Interpreter/Tree/Statements/ScopeBlockStatement.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
 
 
@@ -11,20 +12,29 @@ namespace MoonSharp.Interpreter.Tree.Statements
 	{
 	{
 		Statement m_Block;
 		Statement m_Block;
 		RuntimeScopeBlock m_StackFrame;
 		RuntimeScopeBlock m_StackFrame;
+		SourceRef m_Do, m_End;
 
 
 		public ScopeBlockStatement(LuaParser.Stat_doblockContext context, ScriptLoadingContext lcontext)
 		public ScopeBlockStatement(LuaParser.Stat_doblockContext context, ScriptLoadingContext lcontext)
 			: base(context, lcontext)
 			: base(context, lcontext)
 		{
 		{
 			lcontext.Scope.PushBlock();
 			lcontext.Scope.PushBlock();
 			m_Block = NodeFactory.CreateStatement(context.block(), lcontext);
 			m_Block = NodeFactory.CreateStatement(context.block(), lcontext);
+
+			m_Do = BuildSourceRef(lcontext, context.Start, context.DO());
+			m_End = BuildSourceRef(lcontext, context.Stop, context.END());
+
 			m_StackFrame = lcontext.Scope.PopBlock();
 			m_StackFrame = lcontext.Scope.PopBlock();
 		}
 		}
 
 
 		public override void Compile(Execution.VM.ByteCode bc)
 		public override void Compile(Execution.VM.ByteCode bc)
 		{
 		{
-			bc.Emit_Enter(m_StackFrame);
+			using(bc.EnterSource(m_Do))
+				bc.Emit_Enter(m_StackFrame);
+
 			m_Block.Compile(bc);
 			m_Block.Compile(bc);
-			bc.Emit_Leave(m_StackFrame);
+
+			using (bc.EnterSource(m_End))
+				bc.Emit_Leave(m_StackFrame);
 		}
 		}
 
 
 	}
 	}

+ 17 - 1
src/MoonSharp.Interpreter/Tree/Statements/WhileStatement.cs

@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using MoonSharp.Interpreter.Debugging;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Execution.VM;
 using MoonSharp.Interpreter.Grammar;
 using MoonSharp.Interpreter.Grammar;
@@ -13,11 +14,16 @@ namespace MoonSharp.Interpreter.Tree.Statements
 		Expression m_Condition;
 		Expression m_Condition;
 		Statement m_Block;
 		Statement m_Block;
 		RuntimeScopeBlock m_StackFrame;
 		RuntimeScopeBlock m_StackFrame;
+		SourceRef m_Start, m_End;
 
 
 		public WhileStatement(LuaParser.Stat_whiledoloopContext context, ScriptLoadingContext lcontext)
 		public WhileStatement(LuaParser.Stat_whiledoloopContext context, ScriptLoadingContext lcontext)
 			: base(context, lcontext)
 			: base(context, lcontext)
 		{
 		{
-			m_Condition = NodeFactory.CreateExpression(context.exp(), lcontext);
+			var exp = context.exp();
+			m_Condition = NodeFactory.CreateExpression(exp, lcontext);
+
+			m_Start = BuildSourceRef(lcontext, context.Start, exp.Stop);
+			m_End = BuildSourceRef(lcontext, context.Stop, context.END());
 
 
 			lcontext.Scope.PushBlock();
 			lcontext.Scope.PushBlock();
 			m_Block = NodeFactory.CreateStatement(context.block(), lcontext);
 			m_Block = NodeFactory.CreateStatement(context.block(), lcontext);
@@ -32,16 +38,24 @@ namespace MoonSharp.Interpreter.Tree.Statements
 				Scope = m_StackFrame
 				Scope = m_StackFrame
 			};
 			};
 
 
+
 			bc.LoopTracker.Loops.Push(L);
 			bc.LoopTracker.Loops.Push(L);
 
 
+			bc.PushSourceRef(m_Start);
+
 			int start = bc.GetJumpPointForNextInstruction();
 			int start = bc.GetJumpPointForNextInstruction();
 
 
 			m_Condition.Compile(bc);
 			m_Condition.Compile(bc);
 			var jumpend = bc.Emit_Jump(OpCode.Jf, -1);
 			var jumpend = bc.Emit_Jump(OpCode.Jf, -1);
 
 
 			bc.Emit_Enter(m_StackFrame);
 			bc.Emit_Enter(m_StackFrame);
+
 			m_Block.Compile(bc);
 			m_Block.Compile(bc);
+
+			bc.PopSourceRef();
 			bc.Emit_Debug("..end");
 			bc.Emit_Debug("..end");
+			bc.PushSourceRef(m_End);
+	
 			bc.Emit_Leave(m_StackFrame);
 			bc.Emit_Leave(m_StackFrame);
 			bc.Emit_Jump(OpCode.Jump, start);
 			bc.Emit_Jump(OpCode.Jump, start);
 			
 			
@@ -53,6 +67,8 @@ namespace MoonSharp.Interpreter.Tree.Statements
 				i.NumVal = exitpoint;
 				i.NumVal = exitpoint;
 
 
 			jumpend.NumVal = exitpoint;
 			jumpend.NumVal = exitpoint;
+
+			bc.PopSourceRef();
 		}
 		}
 
 
 	}
 	}

+ 7 - 1
src/MoonSharp/Program.cs

@@ -82,7 +82,13 @@ namespace MoonSharp
 
 
 					try
 					try
 					{
 					{
-						Console.WriteLine("={0}", script.DoString(cmd));
+						var v = script.LoadString(cmd, null, "stdin");
+
+						Console.WriteLine("={0}", script.Call(v));
+					}
+					catch (ScriptRuntimeException ex)
+					{
+						Console.WriteLine("{0}", ex.DecoratedMessage);
 					}
 					}
 					catch (Exception ex)
 					catch (Exception ex)
 					{
 					{