Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bunch of fixes and compatibility tweaks (fix #275, #263, #229) #280

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/MoonSharp.Interpreter/CoreLib/BasicModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,11 @@ public static DynValue assert(ScriptExecutionContext executionContext, CallbackA

if (!v.CastToBool())
{
var cor = executionContext.GetCallingCoroutine();
if (message.IsNil())
throw new ScriptRuntimeException("assertion failed!"); // { DoNotDecorateMessage = true };
throw new ScriptRuntimeException("assertion failed!") { CallStack = cor.GetStackTrace(0) }; // { DoNotDecorateMessage = true };
else
throw new ScriptRuntimeException(message.ToPrintString()); // { DoNotDecorateMessage = true };
throw new ScriptRuntimeException(message.ToPrintString()) { CallStack = cor.GetStackTrace(0) }; // { DoNotDecorateMessage = true };
}

return DynValue.NewTupleNested(args.GetArray());
Expand Down Expand Up @@ -91,7 +92,7 @@ public static DynValue error(ScriptExecutionContext executionContext, CallbackAr

WatchItem[] stacktrace = cor.GetStackTrace(0, executionContext.CallingLocation);

var e = new ScriptRuntimeException(message.String);
var e = new ScriptRuntimeException(message.String) { CallStack = stacktrace };

if (level.IsNil())
{
Expand Down Expand Up @@ -229,8 +230,13 @@ public static DynValue tonumber(ScriptExecutionContext executionContext, Callbac
if (e.Type != DataType.String)
return DynValue.Nil;

double d;
if (double.TryParse(e.String, NumberStyles.Any, CultureInfo.InvariantCulture, out d))
if (e.String.StartsWith("0x"))
{
if (long.TryParse(e.String.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out long l))
return DynValue.NewNumber(l);
return DynValue.Nil;
}
if (double.TryParse(e.String, NumberStyles.Any, CultureInfo.InvariantCulture, out double d))
{
return DynValue.NewNumber(d);
}
Expand Down
168 changes: 137 additions & 31 deletions src/MoonSharp.Interpreter/CoreLib/DebugModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -297,47 +297,153 @@ public static DynValue traceback(ScriptExecutionContext executionContext, Callba
//}


//[MoonSharpMethod]
//public static DynValue getinfo(ScriptExecutionContext executionContext, CallbackArguments args)
//{
// Coroutine cor = executionContext.GetCallingCoroutine();
// int vfArgIdx = 0;

// if (args[0].Type == DataType.Thread)
// cor = args[0].Coroutine;
[MoonSharpModuleMethod]
public static DynValue getinfo(ScriptExecutionContext executionContext, CallbackArguments args)
{
Coroutine cor = executionContext.GetCallingCoroutine();
int vfArgIdx = 0;

// DynValue vf = args[vfArgIdx+0];
// DynValue vwhat = args[vfArgIdx+1];
if (args[0].Type == DataType.Thread)
cor = args[0].Coroutine;

// args.AsType(vfArgIdx + 1, "getinfo", DataType.String, true);
DynValue vf = args[vfArgIdx+0];
DynValue vwhat = args[vfArgIdx+1];

//args.AsType(vfArgIdx + 1, "getinfo", DataType.String, true);

// string what = vwhat.CastToString() ?? "nfSlu";
string what = vwhat.CastToString() ?? "nfSlu";

// DynValue vt = DynValue.NewTable(executionContext.GetScript());
// Table t = vt.Table;
DynValue vt = DynValue.NewTable(executionContext.GetScript());
Table t = vt.Table;
if (vf.Type == DataType.Function || vf.Type == DataType.ClrFunction)
{
GetInfoAboutFunction(t, vf, what, executionContext);
return vt;
}
else if (vf.Type == DataType.Number)
{
var stackTrace = cor.GetStackTrace((int)vf.Number);
if (stackTrace.Length <= 0)
return DynValue.Nil;
var info = stackTrace[0];
if (what.Contains("S"))
{
var source = executionContext.OwnerScript.GetSourceCode(info.Location.SourceIdx);
if (source != null)
{
t["source"] = source != null ? source.Name : "[C]";
t["short_src"] = source.Name.Substring(0, Math.Min(source.Name.Length, 60));
t["what"] = "Lua";
}
else
{
t["source"] = "[C]";
t["short_src"] = "[C]";
t["what"] = "C";
}
}

// if (vf.Type == DataType.Function)
// {
// Closure f = vf.Function;
// executionContext.GetInfoForFunction
// }
// else if (vf.Type == DataType.ClrFunction)
// {
if (what.Contains("L"))
{

// }
// else if (vf.Type == DataType.Number || vf.Type == DataType.String)
// {
}

// }
// else
// {
// args.AsType(vfArgIdx + 0, "getinfo", DataType.Number, true);
// }
if (what.Contains("n"))
{

// return vt;
}

if (what.Contains("u"))
{

//}
}
t["linedefined"] = info.Location.FromLine;
t["lastlinedefined"] = info.Location.ToLine;
return vt;
}
return DynValue.Nil;
}

private static void GetInfoAboutFunction(Table infoTable, DynValue function, string what, ScriptExecutionContext executionContext)
{
if (function.Type == DataType.Function)
{
Closure f = function.Function;
var sourceRef = executionContext.GetFunctionSourceCodeRef(f);
var source = executionContext.OwnerScript.GetSourceCode(sourceRef.SourceIdx);
if (what.Contains("S"))
{
infoTable["source"] = source.Name;
infoTable["short_src"] = source.Name.Substring(0, Math.Min(source.Name.Length, 60));

infoTable["what"] = "Lua";
}

if (what.Contains("L"))
{
var lines = new Table(executionContext.OwnerScript);
for (int i = sourceRef.FromLine; i <= sourceRef.ToLine; i++)
lines.Append(DynValue.NewString(source.Lines[i]));
infoTable["activelines"] = lines;
}

if (what.Contains("n"))
{
var name = executionContext.GetFunctionName(f);
infoTable["name"] = name;
var symbolRef = executionContext.FindSymbolByName(name);
switch (symbolRef.Type)
{
case SymbolRefType.Global:
infoTable["namewhat"] = "global";
break;
case SymbolRefType.Local:
infoTable["namewhat"] = "local";
break;
case SymbolRefType.DefaultEnv:
infoTable["namewhat"] = "field";
break;
}
}

if (what.Contains("u"))
{
infoTable["nups"] = f.GetUpvaluesCount();
}

infoTable["linedefined"] = sourceRef.FromLine;
infoTable["lastlinedefined"] = sourceRef.ToLine;
}
else if (function.Type == DataType.ClrFunction)
{
CallbackFunction f = function.Callback;
if (what.Contains("S"))
{
infoTable["source"] = "[C]";
infoTable["short_src"] = "[C]";
infoTable["what"] = "C";
}

if (what.Contains("n"))
{
var symbolRef = executionContext.FindSymbolByName(f.Name);
infoTable["name"] = f.Name;
switch (symbolRef.Type)
{
case SymbolRefType.Global:
infoTable["namewhat"] = "global";
break;
case SymbolRefType.Local:
infoTable["namewhat"] = "local";
break;
case SymbolRefType.DefaultEnv:
infoTable["namewhat"] = "field";
break;
}
}
}

}

}
}
4 changes: 2 additions & 2 deletions src/MoonSharp.Interpreter/CoreLib/StringLib/KopiLua_StrLib.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public class capture_
};


public const int MAXCCALLS = 200;
public const int MAXCCALLS = 1000;
public const char L_ESC = '%';
public const string SPECIALS = "^$*+?.([%-";

Expand Down Expand Up @@ -959,7 +959,7 @@ public static int str_format(LuaState L)
case 's':
{
uint l;
CharPtr s = LuaLCheckLString(L, arg, out l);
CharPtr s = LuaLCheckLString(L, arg, out l, true);
if ((strchr(form, '.') == null) && l >= 100)
{
/* no precision and string is too long to be formatted;
Expand Down
2 changes: 2 additions & 0 deletions src/MoonSharp.Interpreter/CoreLib/TableIteratorsModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ public class TableIteratorsModule
public static DynValue ipairs(ScriptExecutionContext executionContext, CallbackArguments args)
{
DynValue table = args[0];
if(table == null || table.Type == DataType.Nil)
throw new System.ApplicationException("attempt to index nil");

DynValue meta = executionContext.GetMetamethodTailCall(table, "__ipairs", args.GetArray());

Expand Down
14 changes: 13 additions & 1 deletion src/MoonSharp.Interpreter/DataTypes/DynValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,12 @@ public override bool Equals(object obj)
return Table == other.Table;
case DataType.Tuple:
case DataType.TailCallRequest:
return Tuple == other.Tuple;
if (Tuple.Length != other.Tuple.Length)
return false;
for(int i = 0; i < Tuple.Length; i++)
if (!Equals(Tuple[i], other.Tuple[i]))
return false;
return true;
case DataType.Thread:
return Coroutine == other.Coroutine;
case DataType.UserData:
Expand Down Expand Up @@ -709,6 +714,13 @@ public string CastToString()
}
else if (rv.Type == DataType.String)
{
if (rv.String.StartsWith("0x"))
{
if (long.TryParse(rv.String, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out long value))
return value;
return null;
}

double num;
if (double.TryParse(rv.String, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
return num;
Expand Down
30 changes: 28 additions & 2 deletions src/MoonSharp.Interpreter/Errors/InterpreterException.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Text;
using MoonSharp.Interpreter.Debugging;

namespace MoonSharp.Interpreter
Expand Down Expand Up @@ -86,11 +87,36 @@ internal void DecorateMessage(Script script, SourceRef sref, int ip = -1)
}
else if (sref != null)
{
this.DecoratedMessage = string.Format("{0}: {1}", sref.FormatLocation(script), this.Message);
var buffer = new StringBuilder($"{sref.FormatLocation(script)}: {this.Message}");
if (CallStack != null)
{
buffer.AppendLine();
foreach (var item in CallStack)
if (item.Location != null)
buffer.AppendLine($"{item.Location.FormatLocation(script)}: {item.Name}");
else
buffer.AppendLine($"unknown: {item.Name}");
}
else
new object();

this.DecoratedMessage = buffer.ToString();
}
else
{
this.DecoratedMessage = string.Format("bytecode:{0}: {1}", ip, this.Message);
var buffer = new StringBuilder($"bytecode:{ip}: {this.Message}");
if (CallStack != null)
{
buffer.AppendLine();
foreach (var item in CallStack)
if (item.Location != null)
buffer.AppendLine($"{item.Location.FormatLocation(script)}: {item.Name}");
else
buffer.AppendLine($"unknown: {item.Name}");
}
else
new object();
this.DecoratedMessage = buffer.ToString();
}
}
}
Expand Down
11 changes: 11 additions & 0 deletions src/MoonSharp.Interpreter/Execution/ScriptExecutionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,17 @@ public object AdditionalData
}
}

public SourceRef GetFunctionSourceCodeRef(Closure fn)
{
var i = fn.EntryPointByteCodeLocation;
return m_Processor.FindMeta(ref i).SourceCodeRef;
}

public string GetFunctionName(Closure fn)
{
var i = fn.EntryPointByteCodeLocation;
return m_Processor.FindMeta(ref i).Name;
}

/// <summary>
/// Gets the metatable associated with the given value.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ namespace MoonSharp.Interpreter.Execution.VM
{
sealed partial class Processor
{
public SourceRef GetCurrentSourceRef()
{
if (m_SavedInstructionPtr >= 0 && m_SavedInstructionPtr < m_RootChunk.Code.Count)
{
return m_RootChunk.Code[m_SavedInstructionPtr].SourceCodeRef;
}

return null;
}
private SourceRef GetCurrentSourceRef(int instructionPtr)
{
if (instructionPtr >= 0 && instructionPtr < m_RootChunk.Code.Count)
Expand Down
9 changes: 7 additions & 2 deletions src/MoonSharp.Interpreter/Interop/LuaStateInterop/CharPtr.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,13 @@ public CharPtr(IntPtr ptr)
public static CharPtr operator +(CharPtr ptr, uint offset) { return new CharPtr(ptr.chars, ptr.index + (int)offset); }
public static CharPtr operator -(CharPtr ptr, uint offset) { return new CharPtr(ptr.chars, ptr.index - (int)offset); }

public void inc() { this.index++; }
public void dec() { this.index--; }
public CharPtr Copy()
{
return new CharPtr(this);
}

public CharPtr inc() { this.index++; return this; }
public CharPtr dec() { this.index--; return this; }
public CharPtr next() { return new CharPtr(this.chars, this.index + 1); }
public CharPtr prev() { return new CharPtr(this.chars, this.index - 1); }
public CharPtr add(int ofs) { return new CharPtr(this.chars, this.index + ofs); }
Expand Down
Loading