Make print() script function changeable, defaults to Console.WriteLine

This commit is contained in:
Deukhoofd 2019-07-21 12:34:13 +02:00
parent 58da41852d
commit d452a740f0
Signed by: Deukhoofd
GPG Key ID: ADF2E9256009EDCE
4 changed files with 56 additions and 1 deletions

33
PorygonSharp/CoreSetup.cs Normal file
View File

@ -0,0 +1,33 @@
using System;
using System.Runtime.InteropServices;
namespace PorygonSharp
{
internal static class CoreSetup
{
public static Action<string> Print = Console.WriteLine;
private delegate void InternalPrintDelegate(IntPtr ptr);
private static InternalPrintDelegate InternalPrint = PrintFunc;
static CoreSetup()
{
SetPrintFunc();
}
internal static void SetPrintFunc()
{
var funcPtr = Marshal.GetFunctionPointerForDelegate(InternalPrint);
InternalSetPrintFunc(funcPtr);
}
private static void PrintFunc(IntPtr ptr)
{
var message = Marshal.PtrToStringUni(ptr);
Print(message);
}
[DllImport("libPorygonLang", EntryPoint = "SetPrintFunc", CallingConvention = CallingConvention.Cdecl)]
private static extern double InternalSetPrintFunc(IntPtr ptr);
}
}

View File

@ -1,5 +1,6 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using PorygonSharp.DiagnosticHandling; using PorygonSharp.DiagnosticHandling;
@ -40,8 +41,13 @@ namespace PorygonSharp
private Diagnostics _diagnostics; private Diagnostics _diagnostics;
public Diagnostics Diagnostics => _diagnostics ?? (_diagnostics = new Diagnostics(_internalScript.Diagnostics)); public Diagnostics Diagnostics => _diagnostics ?? (_diagnostics = new Diagnostics(_internalScript.Diagnostics));
private static readonly RuntimeTypeHandle _setupHandle = typeof(CoreSetup).TypeHandle;
public Script(string s) public Script(string s)
{ {
// Ensure core setup has been called
RuntimeHelpers.RunClassConstructor(_setupHandle);
_internalScriptHandle = Create(s); _internalScriptHandle = Create(s);
_internalScript = Marshal.PtrToStructure<InternalScript>(_internalScriptHandle); _internalScript = Marshal.PtrToStructure<InternalScript>(_internalScriptHandle);
} }

View File

@ -1,4 +1,5 @@
using System; using System;
using System.IO;
using System.Linq; using System.Linq;
using NUnit.Framework; using NUnit.Framework;
using PorygonSharp; using PorygonSharp;
@ -122,11 +123,26 @@ namespace PorygonSharpTests
} }
} }
[Test]
public void TestPrint()
{
using (var script = new Script("print('test')"))
{
using (var sw = new StringWriter())
{
Console.SetOut(sw);
Assert.False(script.Diagnostics.HasErrors());
script.Evaluate();
var s = sw.ToString();
Assert.AreEqual("test\n", s);
}
}
}
[Test] [Test]
public void TestHash() public void TestHash()
{ {
var hash = HashedString.ScriptHash("Foo"); var hash = "Foo".ScriptHash();
Assert.AreEqual(193501609, hash); Assert.AreEqual(193501609, hash);
} }
} }

Binary file not shown.