diff --git a/PdVm.Compiler/PdVmDotNetSourceCompiler.cs b/PdVm.Compiler/PdVmDotNetSourceCompiler.cs index edffb07a..824d9bc0 100644 --- a/PdVm.Compiler/PdVmDotNetSourceCompiler.cs +++ b/PdVm.Compiler/PdVmDotNetSourceCompiler.cs @@ -481,7 +481,7 @@ private static IEnumerable ScanMetadataBindings(Type type) property.Name, [property.PropertyType], [new Parameter("handle", "int"), new Parameter("value", setSchema)], - "null")); + "()")); } } @@ -536,7 +536,7 @@ private static bool TryBuildParameters( private static bool TryGetSchema(Type type, out string schema) { - if (type == typeof(void)) { schema = "null"; return true; } + if (type == typeof(void)) { schema = "()"; return true; } if (type == typeof(string) || type == typeof(char) || type.IsEnum) { schema = "string"; return true; } if (type == typeof(bool)) { schema = "bool"; return true; } if (type == typeof(byte[])) { schema = "bytes"; return true; } diff --git a/PdVm.Compiler/PdVmModel.cs b/PdVm.Compiler/PdVmModel.cs index 1ad4f0ca..db4c9470 100644 --- a/PdVm.Compiler/PdVmModel.cs +++ b/PdVm.Compiler/PdVmModel.cs @@ -65,6 +65,9 @@ public enum PdVmTypeSchemaKind : byte Object = 14, Callable = 15, Optional = 16, + Result = 18, + Option = 19, + Unit = 20, } public sealed record PdVmTypeSchema @@ -198,6 +201,9 @@ public enum PdVmHostTypeSchemaKind : byte Callable = 11, Resource = 12, Named = 13, + Result = 14, + Option = 15, + Unit = 16, } public sealed record PdVmHostImportParam( diff --git a/PdVm.Compiler/PdVmVmbcReader.cs b/PdVm.Compiler/PdVmVmbcReader.cs index c9cbd486..3369ae46 100644 --- a/PdVm.Compiler/PdVmVmbcReader.cs +++ b/PdVm.Compiler/PdVmVmbcReader.cs @@ -8,7 +8,7 @@ public static class PdVmVmbcReader private const int MaximumConstantDepth = 64; private static readonly byte[] Magic = "VMBC"u8.ToArray(); - private const ushort Version = 13; + private const ushort Version = 14; private const ushort Flags = 0; public static PdVmProgramModel ReadFile(string path) @@ -84,6 +84,10 @@ public static PdVmProgramModel ReadBytes(byte[] bytes) SkipDebugInfo(ref cursor); var callableMetadata = ReadCallableMetadata(ref cursor); var namedStructDecls = ReadNamedStructDecls(ref cursor); + if (cursor.ReadUInt32() != 0) + { + throw new PdVmCompilerException("non-empty return cleanup metadata is not supported"); + } if (!cursor.IsEof) { @@ -462,6 +466,11 @@ private static PdVmTypeSchema ReadSchema(ref Cursor cursor) items: ReadSchemaList(ref cursor), result: ReadSchema(ref cursor)), 16 => new PdVmTypeSchema(PdVmTypeSchemaKind.Optional, element: ReadSchema(ref cursor)), + 18 => new PdVmTypeSchema( + PdVmTypeSchemaKind.Result, + items: [ReadSchema(ref cursor), ReadSchema(ref cursor)]), + 19 => new PdVmTypeSchema(PdVmTypeSchemaKind.Option, element: ReadSchema(ref cursor)), + 20 => new PdVmTypeSchema(PdVmTypeSchemaKind.Unit), _ => throw new PdVmCompilerException($"invalid schema tag {kind} in VMBC payload"), }; } @@ -697,6 +706,13 @@ private static PdVmHostTypeSchema ReadHostTypeSchema(ref Cursor cursor, int dept 11 => ReadHostCallableSchema(ref cursor, depth), 12 => new PdVmHostTypeSchema(PdVmHostTypeSchemaKind.Resource, name: cursor.ReadString()), 13 => ReadHostNamedSchema(ref cursor, depth), + 14 => new PdVmHostTypeSchema( + PdVmHostTypeSchemaKind.Result, + items: [ReadHostTypeSchema(ref cursor, depth + 1), ReadHostTypeSchema(ref cursor, depth + 1)]), + 15 => new PdVmHostTypeSchema( + PdVmHostTypeSchemaKind.Option, + element: ReadHostTypeSchema(ref cursor, depth + 1)), + 16 => new PdVmHostTypeSchema(PdVmHostTypeSchemaKind.Unit), var tag => throw new PdVmCompilerException($"invalid host schema tag {tag}"), }; } diff --git a/PdVm.Runner/Program.cs b/PdVm.Runner/Program.cs index 5327d1b9..decbcfc6 100644 --- a/PdVm.Runner/Program.cs +++ b/PdVm.Runner/Program.cs @@ -162,7 +162,7 @@ private static async Task RunProgramAssemblyAsync( { var callableProgram = program as IPdVmCallableProgram ?? throw new InvalidOperationException( - "the Windows Forms profile requires a callable VMBC v13 program"); + "the Windows Forms profile requires a callable VMBC v14 program"); callableProgram.CallbackErrorObserver = exception => Console.Error.WriteLine(exception); using var application = PdVmWinFormsApplication.Attach(callableProgram, host); var winFormsResult = PdVmExecution.Run(program, host, maxSteps); diff --git a/PdVm.Runtime/PdVmBuiltins.cs b/PdVm.Runtime/PdVmBuiltins.cs index 3aaa7c69..511c2823 100644 --- a/PdVm.Runtime/PdVmBuiltins.cs +++ b/PdVm.Runtime/PdVmBuiltins.cs @@ -111,6 +111,7 @@ public enum PdVmBuiltin MapIterClose, BindCallable, DetachLocal, + MapEdit, } public static class PdVmBuiltins @@ -139,6 +140,24 @@ public static PdVmValue ArrayPushValue(PdVmValue array, PdVmValue value) => public static PdVmValue SetValue(PdVmValue container, PdVmValue key, PdVmValue value) => DispatchSet(new[] { container, key, value }); + public static PdVmValue MapEditValue(PdVmValue container, PdVmValue key, PdVmValue value, PdVmValue remove) + { + if (key.Kind == PdVmValueKind.Callable) + { + throw new InvalidOperationException("callable values are not supported as map keys"); + } + var output = container.AsMap().CloneMap(); + if (remove.AsBool()) + { + output.Remove(key); + } + else + { + output.Set(key, value); + } + return PdVmValue.FromMap(output); + } + public static PdVmValue VacateMovedField(PdVmValue container, PdVmValue key, PdVmValue movedValue) { // ABI 25 lowers MoveField to Get + set-null. Copyable scalars must stay @@ -330,6 +349,7 @@ public static ushort GetCallIndex(PdVmBuiltin builtin) PdVmBuiltin.MapIterClose => (ushort)(BuiltinCallBase - 13), PdVmBuiltin.BindCallable => (ushort)(BuiltinCallBase - 14), PdVmBuiltin.DetachLocal => (ushort)(BuiltinCallBase - 15), + PdVmBuiltin.MapEdit => 0xFF8F, _ when builtin <= PdVmBuiltin.Count => (ushort)(BuiltinCallBase + (ushort)builtin), _ => throw new ArgumentOutOfRangeException(nameof(builtin)), }; @@ -443,13 +463,14 @@ or PdVmBuiltin.JitSetConfig or PdVmBuiltin.MathClamp or PdVmBuiltin.MathMulAdd or PdVmBuiltin.StringReplaceLiteral => 3, + PdVmBuiltin.MapEdit => 4, _ => throw new ArgumentOutOfRangeException(nameof(builtin)), }; } public static bool IsBuiltinIndex(ushort callIndex) { - var specialStart = BuiltinCallBase - 15; + var specialStart = 0xFF8C; var mainEnd = BuiltinCallBase + BuiltinCallCount - 1; return callIndex >= specialStart && callIndex <= mainEnd; } @@ -458,6 +479,9 @@ public static bool TryGetBuiltin(ushort callIndex, out PdVmBuiltin builtin) { switch (callIndex) { + case 0xFF8F: + builtin = PdVmBuiltin.MapEdit; + return true; case var index when index == BuiltinCallBase - 4: builtin = PdVmBuiltin.FormatTemplate; return true; @@ -536,6 +560,7 @@ public static PdVmCallOutcome Dispatch(ushort callIndex, IReadOnlyList ReturnOne(GetValue(GetArg(args, 0), GetArg(args, 1))), PdVmBuiltin.Has => ReturnOne(HasValue(GetArg(args, 0), GetArg(args, 1))), PdVmBuiltin.Set => ReturnOne(SetValue(GetArg(args, 0), GetArg(args, 1), GetArg(args, 2))), + PdVmBuiltin.MapEdit => ReturnOne(MapEditValue(GetArg(args, 0), GetArg(args, 1), GetArg(args, 2), GetArg(args, 3))), PdVmBuiltin.Keys => ReturnOne(KeysValue(GetArg(args, 0))), PdVmBuiltin.BytesFromUtf8 => ReturnOne(BytesFromUtf8Value(GetArg(args, 0))), PdVmBuiltin.BytesToUtf8 => ReturnOne(BytesToUtf8Value(GetArg(args, 0))), @@ -582,7 +607,7 @@ or PdVmBuiltin.MapIterTakeValue or PdVmBuiltin.MapIterClose or PdVmBuiltin.BindCallable or PdVmBuiltin.DetachLocal => throw new NotSupportedException( - $"builtin {builtin} requires the VMBC v13 callable runtime"), + $"builtin {builtin} requires the VMBC v14 callable runtime"), PdVmBuiltin.JitSetConfig or PdVmBuiltin.JitGetConfig or PdVmBuiltin.JitSetEnabled diff --git a/PdVm.Runtime/PdVmCallableRuntime.cs b/PdVm.Runtime/PdVmCallableRuntime.cs index 6b4cec75..2e7118db 100644 --- a/PdVm.Runtime/PdVmCallableRuntime.cs +++ b/PdVm.Runtime/PdVmCallableRuntime.cs @@ -43,6 +43,9 @@ public enum PdVmRuntimeTypeSchemaKind : byte Object = 14, Callable = 15, Optional = 16, + Result = 18, + Option = 19, + Unit = 20, } public sealed record PdVmRuntimeTypeSchema( diff --git a/PdVm.Runtime/PdVmProgramBase.cs b/PdVm.Runtime/PdVmProgramBase.cs index 47a8d76b..f2de07eb 100644 --- a/PdVm.Runtime/PdVmProgramBase.cs +++ b/PdVm.Runtime/PdVmProgramBase.cs @@ -1255,7 +1255,7 @@ PdVmRuntimeTypeSchemaKind.GenericParameter or return schema.Kind switch { - PdVmRuntimeTypeSchemaKind.Null => declaredType == PdVmValueType.Null, + PdVmRuntimeTypeSchemaKind.Null or PdVmRuntimeTypeSchemaKind.Unit => declaredType == PdVmValueType.Null, PdVmRuntimeTypeSchemaKind.Int => declaredType == PdVmValueType.Int, PdVmRuntimeTypeSchemaKind.Float => declaredType == PdVmValueType.Float, PdVmRuntimeTypeSchemaKind.Number => declaredType is PdVmValueType.Int or PdVmValueType.Float, @@ -1279,7 +1279,7 @@ internal static bool MatchesSchema(PdVmValue value, PdVmRuntimeTypeSchema schema return schema.Kind switch { PdVmRuntimeTypeSchemaKind.Unknown or PdVmRuntimeTypeSchemaKind.GenericParameter => true, - PdVmRuntimeTypeSchemaKind.Null => value.Kind == PdVmValueKind.Null, + PdVmRuntimeTypeSchemaKind.Null or PdVmRuntimeTypeSchemaKind.Unit => value.Kind == PdVmValueKind.Null, PdVmRuntimeTypeSchemaKind.Int => value.Kind == PdVmValueKind.Int, PdVmRuntimeTypeSchemaKind.Float => value.Kind == PdVmValueKind.Float, PdVmRuntimeTypeSchemaKind.Number => value.Kind is PdVmValueKind.Int or PdVmValueKind.Float, diff --git a/PdVm.Runtime/PdVmWinFormsEventLoop.cs b/PdVm.Runtime/PdVmWinFormsEventLoop.cs index 8ee2b7ec..e4b81779 100644 --- a/PdVm.Runtime/PdVmWinFormsEventLoop.cs +++ b/PdVm.Runtime/PdVmWinFormsEventLoop.cs @@ -94,7 +94,7 @@ public static void Show(object form) => public static void BindClick( object form, object control, - [PdVmInteropSchema("fn() -> null")] PdVmCallableValue callable) + [PdVmInteropSchema("fn() -> ()")] PdVmCallableValue callable) { var session = PdVmWinFormsApplication.RequireCurrent(); var callback = session.CreateUnitCallback(form, callable); @@ -108,19 +108,19 @@ public static void BindDialog( object form, object control, object dialog, - [PdVmInteropSchema("fn() -> null")] PdVmCallableValue callable) => + [PdVmInteropSchema("fn() -> ()")] PdVmCallableValue callable) => BindClick(form, control, callable); public static void BindAction( object form, object control, - [PdVmInteropSchema("fn(map) -> null")] PdVmCallableValue callable, + [PdVmInteropSchema("fn(map) -> ()")] PdVmCallableValue callable, string action) => BindEventAction(form, control, "Click", callable, action); public static void BindShown( object form, - [PdVmInteropSchema("fn() -> null")] PdVmCallableValue callable) + [PdVmInteropSchema("fn() -> ()")] PdVmCallableValue callable) { var session = PdVmWinFormsApplication.RequireCurrent(); var callback = session.CreateUnitCallback(form, callable); @@ -132,7 +132,7 @@ public static void BindShown( public static void BindShownAction( object form, - [PdVmInteropSchema("fn(map) -> null")] PdVmCallableValue callable, + [PdVmInteropSchema("fn(map) -> ()")] PdVmCallableValue callable, string action) => BindEventAction(form, form, "Shown", callable, action); @@ -156,31 +156,31 @@ private static void BindEventAction( public static void BindMouseDown( object form, object control, - [PdVmInteropSchema("fn(map) -> null")] PdVmCallableValue callable) => + [PdVmInteropSchema("fn(map) -> ()")] PdVmCallableValue callable) => BindPointerEvent(form, control, "MouseDown", callable, hasCoordinates: true, action: string.Empty); public static void BindMouseUp( object form, object control, - [PdVmInteropSchema("fn(map) -> null")] PdVmCallableValue callable) => + [PdVmInteropSchema("fn(map) -> ()")] PdVmCallableValue callable) => BindPointerEvent(form, control, "MouseUp", callable, hasCoordinates: true, action: string.Empty); public static void BindMouseDoubleClick( object form, object control, - [PdVmInteropSchema("fn(map) -> null")] PdVmCallableValue callable) => + [PdVmInteropSchema("fn(map) -> ()")] PdVmCallableValue callable) => BindPointerEvent(form, control, "MouseDoubleClick", callable, hasCoordinates: true, action: string.Empty); public static void BindMouseLeave( object form, object control, - [PdVmInteropSchema("fn(map) -> null")] PdVmCallableValue callable) => + [PdVmInteropSchema("fn(map) -> ()")] PdVmCallableValue callable) => BindPointerEvent(form, control, "MouseLeave", callable, hasCoordinates: false, action: string.Empty); public static void BindPointer( object form, object control, - [PdVmInteropSchema("fn(map) -> null")] PdVmCallableValue callable) + [PdVmInteropSchema("fn(map) -> ()")] PdVmCallableValue callable) { BindPointerEvent(form, control, "MouseDown", callable, hasCoordinates: true, action: "board_down"); BindPointerEvent(form, control, "MouseUp", callable, hasCoordinates: true, action: "board_up"); @@ -190,7 +190,7 @@ public static void BindPointer( public static void BindClosing( object form, - [PdVmInteropSchema("fn() -> null")] PdVmCallableValue callable) + [PdVmInteropSchema("fn() -> ()")] PdVmCallableValue callable) { var session = PdVmWinFormsApplication.RequireCurrent(); var state = GetState(form); @@ -207,7 +207,7 @@ public static void BindClosing( public static void BindClosingAction( object form, - [PdVmInteropSchema("fn(map) -> null")] PdVmCallableValue callable, + [PdVmInteropSchema("fn(map) -> ()")] PdVmCallableValue callable, string action) { ArgumentNullException.ThrowIfNull(action); @@ -227,7 +227,7 @@ public static void BindClosingAction( public static void BindTimer( object form, long intervalMilliseconds, - [PdVmInteropSchema("fn() -> null")] PdVmCallableValue callable) + [PdVmInteropSchema("fn() -> ()")] PdVmCallableValue callable) { BindTimerCore(form, intervalMilliseconds, callable, action: null); } @@ -235,7 +235,7 @@ public static void BindTimer( public static void BindTimerAction( object form, long intervalMilliseconds, - [PdVmInteropSchema("fn(map) -> null")] PdVmCallableValue callable, + [PdVmInteropSchema("fn(map) -> ()")] PdVmCallableValue callable, string action) { ArgumentNullException.ThrowIfNull(action); diff --git a/PdVm.Tests/PdVmAbi25ExampleMatrixTests.cs b/PdVm.Tests/PdVmAbi25ExampleMatrixTests.cs index d533e973..eaf6ee47 100644 --- a/PdVm.Tests/PdVmAbi25ExampleMatrixTests.cs +++ b/PdVm.Tests/PdVmAbi25ExampleMatrixTests.cs @@ -50,7 +50,7 @@ public void CheckedInExamplesHaveExactCountAndCompileThroughNativeCompilerAndClr var bytes = PdVmNativeCompiler.CompileFile(path); Assert.True(bytes.AsSpan(0, 4).SequenceEqual("VMBC"u8)); - Assert.Equal((ushort)13, BitConverter.ToUInt16(bytes, 4)); + Assert.Equal((ushort)14, BitConverter.ToUInt16(bytes, 4)); var model = PdVmVmbcReader.ReadBytes(bytes); Assert.NotEmpty(model.Code); if (source.Contains("http::", StringComparison.Ordinal) || diff --git a/PdVm.Tests/PdVmCompilerTests.cs b/PdVm.Tests/PdVmCompilerTests.cs index e72f4e76..9f632c61 100644 --- a/PdVm.Tests/PdVmCompilerTests.cs +++ b/PdVm.Tests/PdVmCompilerTests.cs @@ -64,7 +64,80 @@ public void RunsBuiltinLenIntrinsic() } [Fact] - public void ReadsV13CallableMetadataAndExportSchema() + public void ReadsV14WithEmptyReturnCleanupSection() + { + var payload = EncodeVmbc([], [(byte)PdVmBytecodeOpCode.Ret], []); + + var model = PdVmVmbcReader.ReadBytes(payload); + + Assert.Single(model.Instructions); + } + + [Fact] + public void RejectsNonEmptyOrTruncatedReturnCleanupMetadata() + { + var payload = EncodeVmbc([], [(byte)PdVmBytecodeOpCode.Ret], []); + payload[^4] = 1; + var error = Assert.Throws(() => PdVmVmbcReader.ReadBytes(payload)); + Assert.Contains("non-empty return cleanup", error.Message); + var truncated = payload[..^1]; + Assert.Throws(() => PdVmVmbcReader.ReadBytes(truncated)); + } + + [Fact] + public void ReadsV14ResultOptionAndUnitSchemaTags() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); + writer.Write("VMBC"u8.ToArray()); + writer.Write((ushort)14); + writer.Write((ushort)0); + writer.Write((uint)0); // constants + writer.Write((uint)1); + writer.Write((byte)PdVmBytecodeOpCode.Ret); + writer.Write((uint)1); // imports + WriteString(writer, "test"); + writer.Write((byte)0); // arity + writer.Write((byte)PdVmValueType.Null); + writer.Write((byte)1); // host schema present + WriteString(writer, "test"); + writer.Write((uint)0); // parameters + writer.Write((byte)14); // Result + writer.Write((byte)15); // Option + writer.Write((byte)16); // Unit + writer.Write((byte)2); // Int + writer.Write((ulong)1); // fingerprint + writer.Write((byte)1); // type map + writer.Write((byte)1); // strict + writer.Write((uint)1); // locals + writer.Write((byte)PdVmValueType.Map); + writer.Write((byte)1); // schema present + writer.Write((byte)18); // Result + writer.Write((byte)19); // Option + writer.Write((byte)20); // Unit + writer.Write((byte)2); // Int + writer.Write((uint)1); writer.Write((byte)0); // callable slots + writer.Write((uint)1); writer.Write((byte)0); // optional slots + writer.Write((uint)0); // operand types + writer.Write((byte)0); // debug + for (var index = 0; index < 7; index++) writer.Write((uint)0); // metadata + writer.Flush(); + + var model = PdVmVmbcReader.ReadBytes(stream.ToArray()); + var host = Assert.Single(model.HostImportSchemas)!.ReturnType; + Assert.Equal(PdVmHostTypeSchemaKind.Result, host.Kind); + Assert.Equal(PdVmHostTypeSchemaKind.Option, host.Items[0].Kind); + Assert.Equal(PdVmHostTypeSchemaKind.Unit, host.Items[0].Element!.Kind); + Assert.Equal(PdVmHostTypeSchemaKind.Int, host.Items[1].Kind); + var schema = Assert.Single(model.TypeMap!.LocalSchemas)!; + Assert.Equal(PdVmTypeSchemaKind.Result, schema.Kind); + Assert.Equal(PdVmTypeSchemaKind.Option, schema.Items[0].Kind); + Assert.Equal(PdVmTypeSchemaKind.Unit, schema.Items[0].Element!.Kind); + Assert.Equal(PdVmTypeSchemaKind.Int, schema.Items[1].Kind); + } + + [Fact] + public void ReadsV14CallableMetadataAndExportSchema() { var callableSchema = new PdVmTypeSchema( PdVmTypeSchemaKind.Callable, @@ -533,7 +606,8 @@ public void MoveCaptureWritebackVacatesOwnedMapField() [InlineData(10)] [InlineData(11)] [InlineData(12)] - public void RejectsPreV13PayloadsWithPreciseVersion(int version) + [InlineData(13)] + public void RejectsPreV14PayloadsWithPreciseVersion(int version) { var payload = EncodeVmbc( Array.Empty(), @@ -544,7 +618,7 @@ public void RejectsPreV13PayloadsWithPreciseVersion(int version) var error = Assert.Throws(() => PdVmVmbcReader.ReadBytes(payload)); - Assert.Equal($"unsupported VMBC version {version}, expected 13", error.Message); + Assert.Equal($"unsupported VMBC version {version}, expected 14", error.Message); } [Fact] @@ -590,7 +664,14 @@ public void BuiltinCatalogIndexesRoundTripWithoutCollisions() var index = PdVmBuiltins.GetCallIndex(builtin); Assert.True(PdVmBuiltins.TryGetBuiltin(index, out var decoded)); Assert.Equal(builtin, decoded); - Assert.InRange(PdVmBuiltins.GetArity(builtin), (byte)0, (byte)3); + if (builtin == PdVmBuiltin.MapEdit) + { + Assert.Equal((byte)4, PdVmBuiltins.GetArity(builtin)); + } + else + { + Assert.InRange(PdVmBuiltins.GetArity(builtin), (byte)0, (byte)3); + } } Assert.Equal(0xFFA2, PdVmBuiltins.BuiltinCallBase); @@ -601,6 +682,7 @@ public void BuiltinCatalogIndexesRoundTripWithoutCollisions() Assert.Equal(0xFFFB, PdVmBuiltins.GetCallIndex(PdVmBuiltin.Count)); Assert.Equal(0xFF94, PdVmBuiltins.GetCallIndex(PdVmBuiltin.BindCallable)); Assert.Equal(0xFF93, PdVmBuiltins.GetCallIndex(PdVmBuiltin.DetachLocal)); + Assert.Equal(0xFF8F, PdVmBuiltins.GetCallIndex(PdVmBuiltin.MapEdit)); } [Fact] @@ -1139,7 +1221,7 @@ private static byte[] EncodeVmbc( using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); writer.Write("VMBC"u8.ToArray()); - writer.Write((ushort)13); + writer.Write((ushort)14); writer.Write((ushort)0); writer.Write((uint)constants.Count); foreach (var constant in constants) @@ -1172,7 +1254,8 @@ private static byte[] EncodeVmbc( { writeCallableMetadata(writer); } - writer.Write((uint)0); + writer.Write((uint)0); // named struct declarations + writer.Write((uint)0); // return cleanup metadata writer.Flush(); return stream.ToArray(); } diff --git a/PdVm.Tests/PdVmTypedDotNetInteropTests.cs b/PdVm.Tests/PdVmTypedDotNetInteropTests.cs index 01f1a69b..3ca3fd08 100644 --- a/PdVm.Tests/PdVmTypedDotNetInteropTests.cs +++ b/PdVm.Tests/PdVmTypedDotNetInteropTests.cs @@ -106,7 +106,7 @@ await Assert.ThrowsAsync(async () => [Fact] public void ShutdownInvalidatesCallableAndCallbackHandles() { - using var fixture = new SourceFixture("pub fn on_click() -> null { null }\n"); + using var fixture = new SourceFixture("pub fn on_click() -> () { () }\n"); var output = PdVmDotNetSourceCompiler.CompileFile(fixture.SourcePath, fixture.OutputPath); var program = Assert.IsAssignableFrom( PdVmAssemblyLoader.CreateProgram(Assembly.Load(File.ReadAllBytes(output)))); @@ -209,10 +209,10 @@ public async Task MutableBorrowAliasRefreshesAfterNestedCallable() { using var fixture = new SourceFixture( "let mut state: map = { value: 0 };\n" + - "fn update_state() -> null {\n" + + "fn update_state() -> () {\n" + " let mut current = &mut state;\n" + " current.value = current.value + 1;\n" + - " null\n" + + " ()\n" + "}\n" + "pub fn read_after_update() -> int {\n" + " let mut current = &mut state;\n" + @@ -295,7 +295,7 @@ public async Task MapCallbackAdapterMatchesCallableSchema() [Fact] public async Task EventHandlerPostsCallableOutsideTheEventStack() { - using var fixture = new SourceFixture("pub fn on_click() -> null { null }\n"); + using var fixture = new SourceFixture("pub fn on_click() -> () { () }\n"); var output = PdVmDotNetSourceCompiler.CompileFile(fixture.SourcePath, fixture.OutputPath); var program = Assert.IsAssignableFrom( PdVmAssemblyLoader.CreateProgram(Assembly.Load(File.ReadAllBytes(output)))); @@ -354,13 +354,13 @@ public void WinFormsButtonClickInvokesRssCallbackOnTheOwningStaThread() "let controls = Form::GetFormControls(form);\n" + "ControlCollection::Add(controls, button);\n" + "ControlCollection::Add(controls, label);\n" + - "fn on_click() -> null {\n" + + "fn on_click() -> () {\n" + " Label::SetLabelText(label, \"updated\");\n" + $" File::WriteAllText(\"{signalPath.Replace('\\', '/')}\", Label::GetLabelText(label));\n" + " Ui::Close(form);\n" + - " null\n" + + " ()\n" + "}\n" + - "fn on_shown() -> null { Button::PerformClick(button); null }\n" + + "fn on_shown() -> () { Button::PerformClick(button); () }\n" + "Ui::BindClick(form, button, on_click);\n" + "Ui::BindShown(form, on_shown);\n" + "Ui::Show(form);\n"); @@ -514,6 +514,14 @@ public void CallableValuesRoundTripThroughArraysMapsAndBuiltinTargets() _ = PdVmExecution.Run(program, PdVmDefaultHost.CreateConsoleHost()); Assert.Equal([41L, 42L, 3L], program.Stack.Select(value => value.AsInt())); + + using var keyFixture = new SourceFixture("fn key() -> int { 1 }\nkey;\n"); + var keyOutput = PdVmDotNetSourceCompiler.CompileFile(keyFixture.SourcePath, keyFixture.OutputPath); + var keyProgram = PdVmAssemblyLoader.CreateProgram(Assembly.Load(File.ReadAllBytes(keyOutput))); + _ = PdVmExecution.Run(keyProgram, PdVmDefaultHost.CreateConsoleHost()); + var callableKey = Assert.Single(keyProgram.Stack); + Assert.Throws(() => PdVmBuiltins.MapEditValue( + PdVmBuiltins.MapNewValue(), callableKey, PdVmValue.Null(), PdVmValue.FromBool(false))); } [Fact] @@ -537,11 +545,11 @@ public void BorrowedMapIterationUsesProgramOwnedIteratorState() } [Fact] - public void ExplicitSetNullDeletesMapEntryThroughGeneratedClr() + public void ExplicitRemoveDeletesMapEntryThroughGeneratedClr() { using var fixture = new SourceFixture( - "let mut values = { key: 1, drop: 2 };\n" + - "values[\"drop\"] = null;\n" + + "let mut values: map = { key: 1, drop: 2 };\n" + + "values = values.remove(\"drop\");\n" + "[values.has(\"drop\"), values.has(\"key\"), values.key];\n"); var output = PdVmDotNetSourceCompiler.CompileFile(fixture.SourcePath, fixture.OutputPath); var program = PdVmAssemblyLoader.CreateProgram(Assembly.Load(File.ReadAllBytes(output))); @@ -554,6 +562,22 @@ public void ExplicitSetNullDeletesMapEntryThroughGeneratedClr() Assert.Single(program.Stack).AsArray().Select(value => value.Kind == PdVmValueKind.Bool ? (value.AsBool() ? 1L : 0L) : value.AsInt())); + + using var unitFixture = new SourceFixture( + "let mut values: map<()> = {};\n" + + "values[\"unit\"] = ();\n" + + "[values.has(\"unit\"), values.length];\n" + + "values = values.remove(\"unit\");\n" + + "[values.has(\"unit\"), values.length];\n"); + var unitOutput = PdVmDotNetSourceCompiler.CompileFile(unitFixture.SourcePath, unitFixture.OutputPath); + var unitProgram = PdVmAssemblyLoader.CreateProgram(Assembly.Load(File.ReadAllBytes(unitOutput))); + Assert.Equal(PdVmStatusKind.Halted, PdVmExecution.Run(unitProgram, PdVmDefaultHost.CreateConsoleHost()).Status.Kind); + var before = unitProgram.Stack[0].AsArray(); + var after = unitProgram.Stack[1].AsArray(); + Assert.True(before[0].AsBool()); + Assert.Equal(1, before[1].AsInt()); + Assert.False(after[0].AsBool()); + Assert.Equal(0, after[1].AsInt()); } [Fact] @@ -674,8 +698,8 @@ public async Task PendingHostCallInsideCallableResumesOnceAndResetCancelsIt() public async Task PendingHostCallableValueNormalizesUnitResult() { using var fixture = new SourceFixture( - "fn delayed() -> null;\n" + - "let function: fn() -> null = delayed;\n" + + "fn delayed() -> ();\n" + + "let function: fn() -> () = delayed;\n" + "function();\n"); var output = PdVmDotNetSourceCompiler.CompileFile(fixture.SourcePath, fixture.OutputPath); var program = PdVmAssemblyLoader.CreateProgram(Assembly.Load(File.ReadAllBytes(output))); @@ -990,7 +1014,7 @@ public void SourceWrapperCompilesTypedWindowsFormsEventLoopProfile() "use System::Windows::Forms::Form;\n" + "use System::Windows::EventLoop as Ui;\n" + "let form = Form::NewForm();\n" + - "fn on_close() -> null { Ui::Close(form); null }\n" + + "fn on_close() -> () { Ui::Close(form); () }\n" + "Ui::BindClosing(form, on_close);\n" + "Ui::Show(form);\n"); @@ -1124,10 +1148,10 @@ public void WinFormsTimerInvokesRssCallableOnTheOwningStaThread() "use System::Windows::Forms::Form;\n" + "use System::Windows::EventLoop as Ui;\n" + "let form = Form::NewForm();\n" + - "fn on_tick() -> null {\n" + + "fn on_tick() -> () {\n" + $" File::WriteAllText(\"{signalPath.Replace('\\', '/')}\", \"tick\");\n" + " Ui::Close(form);\n" + - " null\n" + + " ()\n" + "}\n" + "Ui::BindTimer(form, 10, on_tick);\n" + "Ui::Show(form);\n"); diff --git a/docs/clr-callable-runtime-plan.md b/docs/clr-callable-runtime-plan.md index db05946c..b5dd726b 100644 --- a/docs/clr-callable-runtime-plan.md +++ b/docs/clr-callable-runtime-plan.md @@ -70,7 +70,7 @@ must be treated as one versioned contract: - `Call` remains direct builtin or host-import dispatch. - `CallValue` is opcode `0x19` with one `argc: u8` operand. - the stack segment before `CallValue` is `callee, arg0, ..., argN`; -- a completed callable invocation leaves exactly one result, using `null` for unit; +- a completed callable invocation leaves exactly one result, using `()` for unit; - `Ret` completes the active frame and follows its typed continuation; - branches remain inside the active function region; - callable constants are invalid; @@ -380,7 +380,7 @@ RSS execution begins after the originating UI event returns while remaining on t Typed UI bindings execute directly against their owning controls; there is no centralized hidden window or dedicated dispatcher thread. -Generated `EventLoop` declarations type callback parameters as `fn(...) -> null`. RSS therefore +Generated `EventLoop` declarations type callback parameters as `fn(...) -> ()`. RSS therefore passes the callable value itself, for example `Ui::BindClick(form, button, on_click)`. The CLR host converts that VM value to `PdVmCallableValue`, validates its Program generation and signature, and retains it in the form session; no export-name lookup occurs at the binding point. @@ -390,8 +390,9 @@ retains it in the form session; no export-name lookup occurs at the binding poin RSS source: ```rust -pub fn on_click() -> null { +pub fn on_click() -> () { System::Windows::Forms::MessageBox::Show("Called from RSS"); + () } Ui::BindClick(form, button, on_click); diff --git a/docs/dotnet-interop-wrapper-plan.md b/docs/dotnet-interop-wrapper-plan.md index 6d85faac..bfaa4c53 100644 --- a/docs/dotnet-interop-wrapper-plan.md +++ b/docs/dotnet-interop-wrapper-plan.md @@ -37,10 +37,10 @@ let name = Path::GetFileName("scripts/main.rss"); The generated `System/Console.rss` module is conceptually: ```rust -pub fn __clr_b_17d84a(value: string) -> null; +pub fn __clr_b_17d84a(value: string) -> (); -pub fn WriteLine(value: string) -> null { - __clr_b_17d84a(value); +pub fn WriteLine(value: string) -> () { + __clr_b_17d84a(value) } ``` @@ -108,7 +108,7 @@ Ambiguity is a compile-wrapper diagnostic that lists candidate signatures and th | CLR metadata type | RustScript schema | Runtime representation | | --- | --- | --- | -| `void` | `null` | one RustScript `null` result | +| `void` | `()` | one RustScript `()` result | | integral primitives | `int` | checked conversion to `i64` | | floating primitives | `float` | `f64` | | `bool` | `bool` | Boolean | @@ -116,7 +116,7 @@ Ambiguity is a compile-wrapper diagnostic that lists candidate signatures and th | `byte[]` | `bytes` | byte buffer | | supported arrays/lists | `[T]` | RustScript array | | supported dictionaries | `map` | RustScript map | -| nullable/reference optional | `T?` where supported | value or `null` | +| nullable/reference optional | `Option` where supported | `Some(value)` or `None` | | other reference types | `int` initially | checked CLR object handle | Conversions that lose range or precision are rejected unless the binding profile explicitly permits them. diff --git a/examples/dotnet-minesweeper.rss b/examples/dotnet-minesweeper.rss index 0a813ce4..3148b3ed 100644 --- a/examples/dotnet-minesweeper.rss +++ b/examples/dotnet-minesweeper.rss @@ -422,7 +422,7 @@ let mut flagged = new_board_array(64); let mut display = new_board_array(64); let mut flash_cells = new_board_array(64); -fn render_board(render_rows: int, render_columns: int, render_paused: bool, render_flash_until: int, render_pressed_index: int) -> null { +fn render_board(render_rows: int, render_columns: int, render_paused: bool, render_flash_until: int, render_pressed_index: int) -> () { // These arrays are resized when the difficulty changes. Borrow the root // slots so this renderer observes the replacement arrays instead of the // 8x8 values captured during startup. @@ -445,10 +445,10 @@ fn render_board(render_rows: int, render_columns: int, render_paused: bool, rend render_index = render_index + 1; } render_styles = Scene::Present(board_surface, render_styles); - null + () } -fn reset_game() -> null { +fn reset_game() -> () { let mut game = &mut state; game.active = true; game.started = false; @@ -471,10 +471,10 @@ fn reset_game() -> null { Visuals::SetControlBitmap(face, smile_bitmap); ToolStripMenuItem::SetToolStripMenuItemChecked(pause_item, false); let _board_rendered = render_board((&game).rows, (&game).columns, (&game).paused, (&game).flash_until, (&game).pressed_index); - null + () } -fn select_difficulty(new_rows: int, new_columns: int, new_mine_total: int, new_difficulty: int) -> null { +fn select_difficulty(new_rows: int, new_columns: int, new_mine_total: int, new_difficulty: int) -> () { let mut game = &mut state; game.rows = new_rows; game.columns = new_columns; @@ -493,10 +493,10 @@ fn select_difficulty(new_rows: int, new_columns: int, new_mine_total: int, new_d ToolStripMenuItem::SetToolStripMenuItemChecked(expert_item, (&game).difficulty == 2); ToolStripMenuItem::SetToolStripMenuItemChecked(custom_item, (&game).difficulty == 3); let _game_reset = reset_game(); - null + () } -fn open_cell(open_index: int) -> null { +fn open_cell(open_index: int) -> () { let mut game = &mut state; if open_index >= 0 && (&game).active && !(&game).paused && (&flagged)[open_index] != 1 && (&revealed)[open_index] == 0 { if !(&game).started { @@ -616,10 +616,10 @@ fn open_cell(open_index: int) -> null { } } } - null + () } -fn on_pause() -> null { +fn on_pause() -> () { let mut game = &mut state; if (&game).active && (&game).started => { if (&game).paused { @@ -635,26 +635,26 @@ fn on_pause() -> null { } ToolStripMenuItem::SetToolStripMenuItemChecked(pause_item, (&game).paused); let _board_rendered = render_board((&game).rows, (&game).columns, (&game).paused, (&game).flash_until, (&game).pressed_index); - null - } else => { null }; - null + () + } else => { () }; + () } -fn on_beginner() -> null { +fn on_beginner() -> () { let _difficulty_selected = select_difficulty(8, 8, 10, 0); - null + () } -fn on_intermediate() -> null { +fn on_intermediate() -> () { let _difficulty_selected = select_difficulty(16, 16, 40, 1); - null + () } -fn on_expert() -> null { +fn on_expert() -> () { let _difficulty_selected = select_difficulty(16, 30, 99, 2); - null + () } -fn on_custom() -> null { +fn on_custom() -> () { let game = &state; let custom_values = show_custom_fields(form, (&game).rows, (&game).columns, (&game).mine_total); if custom_values[0] == "ok" { @@ -671,9 +671,9 @@ fn on_custom() -> null { } } } - null + () } -fn on_marks() -> null { +fn on_marks() -> () { let mut game = &mut state; game.marks_enabled = !(&game).marks_enabled; ToolStripMenuItem::SetToolStripMenuItemChecked(marks_item, (&game).marks_enabled); @@ -692,9 +692,9 @@ fn on_marks() -> null { if board_changed { let _board_rendered = render_board((&game).rows, (&game).columns, (&game).paused, (&game).flash_until, (&game).pressed_index); } - null + () } -fn on_color() -> null { +fn on_color() -> () { let mut game = &mut state; game.color_enabled = !(&game).color_enabled; ToolStripMenuItem::SetToolStripMenuItemChecked(color_item, (&game).color_enabled); @@ -704,26 +704,26 @@ fn on_color() -> null { Scene::ConfigureStyles(board_surface, cell_border_styles, cell_backgrounds, cell_border_colors, monochrome_foregrounds, cell_texts, cell_sprites); } let _board_rendered = render_board((&game).rows, (&game).columns, (&game).paused, (&game).flash_until, (&game).pressed_index); - null + () } -fn on_best_times() -> null { +fn on_best_times() -> () { let game = &state; let beginner_time = format_best_time((&game).beginner_best_time); let intermediate_time = format_best_time((&game).intermediate_best_time); let expert_time = format_best_time((&game).expert_best_time); Visuals::ShowMessage(form, "Beginner: " + beginner_time + " seconds\nIntermediate: " + intermediate_time + " seconds\nExpert: " + expert_time + " seconds", "Best Times"); - null + () } -fn on_board_down(event: map) -> null { +fn on_board_down(event: map) -> () { let mut game = &mut state; if event.button == "Left" && (&game).active && !(&game).paused => { game.pressed_index = board_index_at(parse_positive_int(event.x), parse_positive_int(event.y), (&game).rows, (&game).columns); let _board_rendered = render_board((&game).rows, (&game).columns, (&game).paused, (&game).flash_until, (&game).pressed_index); - null - } else => { null }; - null + () + } else => { () }; + () } -fn on_board_up(event: map) -> null { +fn on_board_up(event: map) -> () { let mut game = &mut state; let current_revealed = &revealed; let pointer_index = board_index_at(parse_positive_int(event.x), parse_positive_int(event.y), (&game).rows, (&game).columns); @@ -759,9 +759,9 @@ fn on_board_up(event: map) -> null { game.pressed_index = -1; } let _board_rendered = render_board((&game).rows, (&game).columns, (&game).paused, (&game).flash_until, (&game).pressed_index); - null + () } -fn on_board_double_click(event: map) -> null { +fn on_board_double_click(event: map) -> () { let mut game = &mut state; let current_revealed = &revealed; let current_flagged = &flagged; @@ -824,38 +824,38 @@ fn on_board_double_click(event: map) -> null { } let _board_rendered = render_board((&game).rows, (&game).columns, (&game).paused, (&game).flash_until, (&game).pressed_index); } - null + () } -fn on_board_leave(event: map) -> null { +fn on_board_leave(event: map) -> () { let mut game = &mut state; if (&game).pressed_index >= 0 { game.pressed_index = -1; let _board_rendered = render_board((&game).rows, (&game).columns, (&game).paused, (&game).flash_until, (&game).pressed_index); } - null + () } -fn release_game_resources() -> null { +fn release_game_resources() -> () { let _random_released = Random::ReleaseRandom(random); Ui::Close(form); - null + () } -fn on_exit() -> null { +fn on_exit() -> () { let _game_closed = release_game_resources(); - null + () } -fn on_contents() -> null { +fn on_contents() -> () { Visuals::ShowMessage(form, "Open every square that does not contain a mine.\nRight-click to place a flag or question mark.\nDouble-click a revealed number to open its remaining neighbors.", "Minesweeper Help"); - null + () } -fn on_about() -> null { +fn on_about() -> () { Visuals::ShowMessage(form, "Minesweeper\nRustScript game logic running on IronRust.", "About Minesweeper"); - null + () } -fn on_timer_tick() -> null { +fn on_timer_tick() -> () { let mut game = &mut state; let mut board_changed = false; if (&game).flash_until > 0 && MonotonicClock::GetMilliseconds() >= (&game).flash_until { @@ -873,7 +873,7 @@ fn on_timer_tick() -> null { if board_changed { let _board_rendered = render_board((&game).rows, (&game).columns, (&game).paused, (&game).flash_until, (&game).pressed_index); } - null + () } Ui::BindClick(form, face, reset_game); diff --git a/examples/dotnet-typed-winforms.rss b/examples/dotnet-typed-winforms.rss index 0ca0cfdd..ab806d49 100644 --- a/examples/dotnet-typed-winforms.rss +++ b/examples/dotnet-typed-winforms.rss @@ -90,15 +90,15 @@ SaveFileDialog::SetSaveFileDialogAddExtension(save_dialog, true); let font_dialog = FontDialog::NewFontDialog(); let color_dialog = ColorDialog::NewColorDialog(); -fn on_new() -> null { +fn on_new() -> () { RichTextBox::SetRichTextBoxText(editor, ""); SaveFileDialog::SetSaveFileDialogFileName(save_dialog, ""); Form::SetFormText(form, "Untitled - RustScript Notepad"); ToolStripStatusLabel::SetToolStripStatusLabelText(status_label, "New document"); - null + () } -fn on_open() -> null { +fn on_open() -> () { if Ui::ShowDialog(form, open_dialog) == "OK" { let current_path = OpenFileDialog::GetOpenFileDialogFileName(open_dialog); SaveFileDialog::SetSaveFileDialogFileName(save_dialog, ¤t_path); @@ -106,10 +106,10 @@ fn on_open() -> null { Form::SetFormText(form, (¤t_path) + " - RustScript Notepad"); ToolStripStatusLabel::SetToolStripStatusLabelText(status_label, "Opened " + current_path); } - null + () } -fn on_save() -> null { +fn on_save() -> () { let mut current_path = SaveFileDialog::GetSaveFileDialogFileName(save_dialog); if current_path == "" { if Ui::ShowDialog(form, save_dialog) == "OK" { @@ -121,44 +121,44 @@ fn on_save() -> null { Form::SetFormText(form, (¤t_path) + " - RustScript Notepad"); ToolStripStatusLabel::SetToolStripStatusLabelText(status_label, "Saved " + current_path); } - null + () } -fn on_save_as() -> null { +fn on_save_as() -> () { if Ui::ShowDialog(form, save_dialog) == "OK" { let current_path = SaveFileDialog::GetSaveFileDialogFileName(save_dialog); File::WriteAllText(¤t_path, RichTextBox::GetRichTextBoxText(editor)); Form::SetFormText(form, (¤t_path) + " - RustScript Notepad"); ToolStripStatusLabel::SetToolStripStatusLabelText(status_label, "Saved " + current_path); } - null + () } -fn on_font() -> null { +fn on_font() -> () { if Ui::ShowDialog(form, font_dialog) == "OK" { RichTextBox::SetRichTextBoxFont(editor, FontDialog::GetFontDialogFont(font_dialog)); } - null + () } -fn on_color() -> null { +fn on_color() -> () { if Ui::ShowDialog(form, color_dialog) == "OK" { RichTextBox::SetRichTextBoxForeColor(editor, ColorDialog::GetColorDialogColor(color_dialog)); } - null + () } -fn on_wrap() -> null { +fn on_wrap() -> () { let word_wrap = !RichTextBox::GetRichTextBoxWordWrap(editor); RichTextBox::SetRichTextBoxWordWrap(editor, word_wrap); ToolStripMenuItem::SetToolStripMenuItemChecked(wrap_item, word_wrap); ToolStripStatusLabel::SetToolStripStatusLabelText(status_label, "Word wrap changed"); - null + () } -fn on_close() -> null { +fn on_close() -> () { Ui::Close(form); - null + () } Ui::BindClick(form, new_item, || on_new()); diff --git a/examples/pdedge-http-proxy-http1-body-read.rss b/examples/pdedge-http-proxy-http1-body-read.rss index 3c03249d..b639af9e 100644 --- a/examples/pdedge-http-proxy-http1-body-read.rss +++ b/examples/pdedge-http-proxy-http1-body-read.rss @@ -2,7 +2,13 @@ use http; use proxy; let downstream_version = http::request::get_http_version(); -let request_body_mode = http::request::get_header("x-bench-body-mode"); +let request_body_mode = match http::request::get_header("x-bench-body-mode") { + Result::Ok(present) => match present { + Some(text) => text, + None => "", + }, + Result::Err(error) => "", +}; let upstream = http::exchange::default_upstream(); http::exchange::set_target(upstream, "127.0.0.1", 18080); http::exchange::set_header(upstream, "x-downstream-version", downstream_version); diff --git a/native/pd-vm-compiler/Cargo.lock b/native/pd-vm-compiler/Cargo.lock index 10703c00..c7a25af4 100644 --- a/native/pd-vm-compiler/Cargo.lock +++ b/native/pd-vm-compiler/Cargo.lock @@ -34,21 +34,21 @@ checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "lazy_static" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" [[package]] name = "libc" -version = "0.2.189" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "memchr" @@ -65,16 +65,17 @@ checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" [[package]] name = "pd-edge-abi" version = "0.1.0" -source = "git+https://github.com/rustscript-lang/pd-edge.git?rev=5f4f889e349bdfbd5534deb42bd13b616a6114f5#5f4f889e349bdfbd5534deb42bd13b616a6114f5" +source = "git+https://github.com/rustscript-lang/pd-edge.git?rev=9a9ee3303a17fcf65893f04b1ce4e4df9d7f50c1#9a9ee3303a17fcf65893f04b1ce4e4df9d7f50c1" dependencies = [ "pd-host-function", + "pd-vm", "syn 2.0.119", ] [[package]] name = "pd-host-function" version = "0.1.0" -source = "git+https://github.com/rustscript-lang/rustscript.git?rev=b1d6cffede77f49410bf63525f30b9a46b02dc01#b1d6cffede77f49410bf63525f30b9a46b02dc01" +source = "git+https://github.com/rustscript-lang/rustscript.git?rev=2f433edab3f1907e8cb060e901357d7e2af016ce#2f433edab3f1907e8cb060e901357d7e2af016ce" dependencies = [ "pd-host-schema", "proc-macro2", @@ -85,7 +86,7 @@ dependencies = [ [[package]] name = "pd-host-schema" version = "0.1.0" -source = "git+https://github.com/rustscript-lang/rustscript.git?rev=b1d6cffede77f49410bf63525f30b9a46b02dc01#b1d6cffede77f49410bf63525f30b9a46b02dc01" +source = "git+https://github.com/rustscript-lang/rustscript.git?rev=2f433edab3f1907e8cb060e901357d7e2af016ce#2f433edab3f1907e8cb060e901357d7e2af016ce" dependencies = [ "proc-macro2", "syn 2.0.119", @@ -94,7 +95,7 @@ dependencies = [ [[package]] name = "pd-vm" version = "0.1.0" -source = "git+https://github.com/rustscript-lang/rustscript.git?rev=b1d6cffede77f49410bf63525f30b9a46b02dc01#b1d6cffede77f49410bf63525f30b9a46b02dc01" +source = "git+https://github.com/rustscript-lang/rustscript.git?rev=2f433edab3f1907e8cb060e901357d7e2af016ce#2f433edab3f1907e8cb060e901357d7e2af016ce" dependencies = [ "base64", "futures-channel", @@ -209,14 +210,14 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] name = "serde_json" -version = "1.0.151" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -238,9 +239,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.6" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -249,9 +250,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.26" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "windows-sys" diff --git a/native/pd-vm-compiler/Cargo.toml b/native/pd-vm-compiler/Cargo.toml index 94d9dbfd..b91757cc 100644 --- a/native/pd-vm-compiler/Cargo.toml +++ b/native/pd-vm-compiler/Cargo.toml @@ -10,9 +10,9 @@ crate-type = ["cdylib", "rlib"] [dependencies] # ABI declarations only: none of these features includes a protocol implementation. -edge = { package = "pd-edge-abi", git = "https://github.com/rustscript-lang/pd-edge.git", rev = "5f4f889e349bdfbd5534deb42bd13b616a6114f5", default-features = false, features = ["console", "http", "tls", "websocket"] } -vm = { package = "pd-vm", git = "https://github.com/rustscript-lang/rustscript.git", rev = "b1d6cffede77f49410bf63525f30b9a46b02dc01", default-features = false } +edge = { package = "pd-edge-abi", git = "https://github.com/rustscript-lang/pd-edge.git", rev = "9a9ee3303a17fcf65893f04b1ce4e4df9d7f50c1", default-features = false, features = ["console", "http", "tls", "websocket"] } +vm = { package = "pd-vm", git = "https://github.com/rustscript-lang/rustscript.git", rev = "2f433edab3f1907e8cb060e901357d7e2af016ce", default-features = false } [dev-dependencies] -# Execute parity fixtures and compare the frozen upstream encoder in tests only. -vm = { package = "pd-vm", git = "https://github.com/rustscript-lang/rustscript.git", rev = "b1d6cffede77f49410bf63525f30b9a46b02dc01", default-features = false, features = ["runtime"] } +# Execute parity fixtures with the runtime in tests only. +vm = { package = "pd-vm", git = "https://github.com/rustscript-lang/rustscript.git", rev = "2f433edab3f1907e8cb060e901357d7e2af016ce", default-features = false, features = ["runtime"] } diff --git a/native/pd-vm-compiler/src/catalog.rs b/native/pd-vm-compiler/src/catalog.rs index 9b8d8af7..d0883ed5 100644 --- a/native/pd-vm-compiler/src/catalog.rs +++ b/native/pd-vm-compiler/src/catalog.rs @@ -1,5 +1,5 @@ -//! Compiler-only projection of the frozen pd-edge ABI25 declarations. -//! Schema projection and stdlib overlays follow pd-edge 5f4f889 +//! Compiler-only projection of the frozen pd-edge ABI26 declarations. +//! Schema projection and stdlib overlays follow pd-edge 1ab0dec //! (see LICENSE.pd-edge); there are no protocol handlers or VM adapters. use edge::{AbiParamType, AbiValueType}; use std::path::Path; @@ -27,7 +27,7 @@ fn edge_param_type_schema(param: AbiParamType) -> HostTypeSchema { fn edge_return_type_schema(value: AbiValueType) -> HostTypeSchema { match value { AbiValueType::Unknown => HostTypeSchema::Unknown, - AbiValueType::Null => HostTypeSchema::Null, + AbiValueType::Unit => HostTypeSchema::Unit, AbiValueType::Int => HostTypeSchema::Int, AbiValueType::Float => HostTypeSchema::Float, AbiValueType::Bool => HostTypeSchema::Bool, @@ -35,6 +35,10 @@ fn edge_return_type_schema(value: AbiValueType) -> HostTypeSchema { AbiValueType::Bytes => HostTypeSchema::Bytes, AbiValueType::Array => HostTypeSchema::Array(Box::new(HostTypeSchema::Unknown)), AbiValueType::Map => HostTypeSchema::Map(Box::new(HostTypeSchema::Unknown)), + AbiValueType::ResultOptionString => HostTypeSchema::Result { + ok: Box::new(HostTypeSchema::Option(Box::new(HostTypeSchema::String))), + err: Box::new(HostTypeSchema::String), + }, } } @@ -45,31 +49,28 @@ fn mqtt_event_schema() -> HostTypeSchema { HostStructField::new("kind", HostTypeSchema::String), HostStructField::new( "topic", - HostTypeSchema::Optional(Box::new(HostTypeSchema::String)), + HostTypeSchema::Option(Box::new(HostTypeSchema::String)), ), HostStructField::new( "payload_text", - HostTypeSchema::Optional(Box::new(HostTypeSchema::String)), + HostTypeSchema::Option(Box::new(HostTypeSchema::String)), ), HostStructField::new( "payload_base64", - HostTypeSchema::Optional(Box::new(HostTypeSchema::String)), - ), - HostStructField::new( - "qos", - HostTypeSchema::Optional(Box::new(HostTypeSchema::Int)), + HostTypeSchema::Option(Box::new(HostTypeSchema::String)), ), + HostStructField::new("qos", HostTypeSchema::Option(Box::new(HostTypeSchema::Int))), HostStructField::new( "retain", - HostTypeSchema::Optional(Box::new(HostTypeSchema::Bool)), + HostTypeSchema::Option(Box::new(HostTypeSchema::Bool)), ), HostStructField::new( "dup", - HostTypeSchema::Optional(Box::new(HostTypeSchema::Bool)), + HostTypeSchema::Option(Box::new(HostTypeSchema::Bool)), ), HostStructField::new( "reason", - HostTypeSchema::Optional(Box::new(HostTypeSchema::String)), + HostTypeSchema::Option(Box::new(HostTypeSchema::String)), ), ], ) diff --git a/native/pd-vm-compiler/src/lib.rs b/native/pd-vm-compiler/src/lib.rs index 9fd26aaf..c8b74c1d 100644 --- a/native/pd-vm-compiler/src/lib.rs +++ b/native/pd-vm-compiler/src/lib.rs @@ -7,14 +7,13 @@ mod catalog; pub use catalog::compile_edge_source_file; mod vmbc; -mod wire; const STATUS_OK: i32 = 0; const STATUS_COMPILE_ERROR: i32 = 1; const STATUS_INVALID_ARGUMENT: i32 = 2; const STATUS_PANIC: i32 = 3; -const FROZEN_EDGE_ABI: u16 = 25; +const FROZEN_EDGE_ABI: u16 = 26; #[unsafe(no_mangle)] #[allow(clippy::not_unsafe_ptr_arg_deref)] @@ -193,11 +192,11 @@ mod tests { } #[test] - fn frozen_edge_abi_is_version_25() { + fn frozen_edge_abi_is_version_26() { assert_eq!(ABI_VERSION, FROZEN_EDGE_ABI); assert!( - edge::abi_json().contains("\"abi_version\": 25"), - "published edge ABI JSON must record version 25" + edge::abi_json().contains("\"abi_version\": 26"), + "published edge ABI JSON must record version 26" ); } diff --git a/native/pd-vm-compiler/src/vmbc.rs b/native/pd-vm-compiler/src/vmbc.rs index ea4bbfb4..584fcc80 100644 --- a/native/pd-vm-compiler/src/vmbc.rs +++ b/native/pd-vm-compiler/src/vmbc.rs @@ -9,7 +9,7 @@ pub fn encode_program(mut program: Program) -> Result, String> { } } } - crate::wire::encode_program(&program).map_err(|error| error.to_string()) + vm::encode_program(&program).map_err(|error| error.to_string()) } fn repair_utf8_mojibake(value: &str) -> std::borrow::Cow<'_, str> { diff --git a/native/pd-vm-compiler/src/wire.rs b/native/pd-vm-compiler/src/wire.rs deleted file mode 100644 index d3b66670..00000000 --- a/native/pd-vm-compiler/src/wire.rs +++ /dev/null @@ -1,552 +0,0 @@ -//! VMBC v13 encoder extracted from rustscript src/vmbc.rs at -//! b1d6cffede77f49410bf63525f30b9a46b02dc01 (see LICENSE.rustscript). -//! The pinned upstream gates its wire API behind `runtime`. Keep only the -//! encoding routines here, using public compiler metadata accessors, so the -//! distributed compiler does not link a Rust VM. Tests compare bytes against -//! the pinned upstream encoder, including the complete example corpus. - -use vm::debug_info::DebugInfo; -use vm::host_api::{HostImportSchema, HostParamPassing, HostTypeSchema, MAX_HOST_SCHEMA_DEPTH}; -use vm::{CallableKind, CallableTarget, Program, TypeMap, TypeSchema, Value}; - -const MAGIC: [u8; 4] = *b"VMBC"; -const VERSION_V13: u16 = 13; -const FLAGS: u16 = 0; -const MAX_CONSTANT_DEPTH: usize = 64; - -#[derive(Debug)] -pub enum WireError { - UnsupportedConstantType(&'static str), - LengthTooLarge(&'static str, usize), - HostSchemaImportMismatch, - InvalidHostSchemaComplexity(String), -} - -impl std::fmt::Display for WireError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::UnsupportedConstantType(kind) => { - write!(f, "unsupported constant type for wire format: {kind}") - } - Self::LengthTooLarge(field, len) => write!(f, "{field} length too large: {len}"), - Self::HostSchemaImportMismatch => { - write!(f, "host import schema does not match its import") - } - Self::InvalidHostSchemaComplexity(reason) => { - write!(f, "invalid host schema complexity: {reason}") - } - } - } -} - -impl std::error::Error for WireError {} - -fn write_constant(value: &Value, out: &mut Vec, depth: usize) -> Result<(), WireError> { - if depth >= MAX_CONSTANT_DEPTH { - return Err(WireError::LengthTooLarge("constant nesting depth", depth)); - } - match value { - Value::Int(value) => { - out.push(0); - out.extend_from_slice(&value.to_le_bytes()); - } - Value::Bool(value) => { - out.push(1); - out.push(u8::from(*value)); - } - Value::String(value) => { - out.push(2); - write_u32_len("constant string", value.len(), out)?; - out.extend_from_slice(value.as_bytes()); - } - Value::Float(value) => { - out.push(3); - out.extend_from_slice(&value.to_le_bytes()); - } - Value::Null => out.push(4), - Value::Bytes(value) => { - out.push(5); - write_u32_len("constant bytes", value.len(), out)?; - out.extend_from_slice(value.as_slice()); - } - Value::Array(values) => { - out.push(6); - write_u32_count("constant array", values.len(), out)?; - for value in values.iter() { - write_constant(value, out, depth + 1)?; - } - } - Value::Map(entries) => { - out.push(7); - write_u32_count("constant map", entries.len(), out)?; - for (key, value) in entries.iter() { - write_constant(key, out, depth + 1)?; - write_constant(value, out, depth + 1)?; - } - } - Value::Callable(_) => return Err(WireError::UnsupportedConstantType("callable")), - } - Ok(()) -} - -pub fn encode_program(program: &Program) -> Result, WireError> { - let mut out = Vec::new(); - out.extend_from_slice(&MAGIC); - out.extend_from_slice(&VERSION_V13.to_le_bytes()); - out.extend_from_slice(&FLAGS.to_le_bytes()); - write_u32_count("constants", program.constants.len(), &mut out)?; - - for constant in &program.constants { - write_constant(constant, &mut out, 0)?; - } - - write_u32_len("code", program.code.len(), &mut out)?; - out.extend_from_slice(&program.code); - - write_u32_count("imports", program.imports.len(), &mut out)?; - if !program.host_import_schemas().is_empty() { - if program.host_import_schemas().len() != program.imports.len() { - return Err(WireError::HostSchemaImportMismatch); - } - vm::validate_host_import_schemas( - &program - .host_import_schemas() - .iter() - .flatten() - .cloned() - .collect::>(), - ) - .map_err(|error| WireError::InvalidHostSchemaComplexity(error.to_string()))?; - } - for (index, import) in program.imports.iter().enumerate() { - write_string("import name", &import.name, &mut out)?; - out.push(import.arity); - out.push(import.return_type as u8); - let schema = if program.host_import_schemas().is_empty() { - None - } else { - if program.host_import_schemas().len() != program.imports.len() { - return Err(WireError::HostSchemaImportMismatch); - } - program.host_import_schemas()[index].as_ref() - }; - write_optional_host_import_schema(schema, &mut out)?; - } - - write_type_map(&mut out, program.type_map.as_ref())?; - write_debug_info(&mut out, program.debug.as_ref())?; - write_callable_metadata(&mut out, program)?; - write_named_struct_decls(&mut out, program)?; - - Ok(out) -} - -fn write_callable_metadata(out: &mut Vec, program: &Program) -> Result<(), WireError> { - write_u32_count("script functions", program.script_functions.len(), out)?; - for function in &program.script_functions { - out.extend_from_slice(&function.entry_ip.to_le_bytes()); - out.extend_from_slice(&function.end_ip.to_le_bytes()); - } - - write_u32_count( - "callable prototypes", - program.callable_prototypes.len(), - out, - )?; - for prototype in &program.callable_prototypes { - out.push(match prototype.kind { - CallableKind::FunctionItem => 0, - CallableKind::Closure => 1, - CallableKind::HostFunction => 2, - }); - match prototype.target { - CallableTarget::ScriptFunction(id) => { - out.push(0); - out.extend_from_slice(&id.to_le_bytes()); - } - CallableTarget::HostImport(id) => { - out.push(1); - out.extend_from_slice(&u32::from(id).to_le_bytes()); - } - } - out.push(prototype.arity); - write_u32_count("callable frame locals", prototype.frame_local_count, out)?; - write_u16_list("callable parameters", &prototype.parameter_slots, out)?; - write_u16_list( - "callable capture sources", - &prototype.capture_source_slots, - out, - )?; - write_u16_list("callable captures", &prototype.capture_slots, out)?; - write_u32_count("callable capture modes", prototype.capture_modes.len(), out)?; - for mode in &prototype.capture_modes { - out.push(*mode as u8); - } - match prototype.self_slot { - Some(slot) => { - out.push(1); - out.extend_from_slice(&slot.to_le_bytes()); - } - None => out.push(0), - } - match &prototype.schema { - Some(schema) => { - out.push(1); - write_schema(schema, out)?; - } - None => out.push(0), - } - } - - write_u32_count("function regions", program.function_regions.len(), out)?; - for region in &program.function_regions { - out.extend_from_slice(®ion.start_ip.to_le_bytes()); - out.extend_from_slice(®ion.end_ip.to_le_bytes()); - match region.prototype_id { - Some(id) => { - out.push(1); - out.extend_from_slice(&id.to_le_bytes()); - } - None => out.push(0), - } - } - - write_u32_count( - "root callable bindings", - program.root_callable_bindings.len(), - out, - )?; - for binding in &program.root_callable_bindings { - out.extend_from_slice(&binding.local_slot.to_le_bytes()); - out.extend_from_slice(&binding.prototype_id.to_le_bytes()); - } - write_u32_count("exported callables", program.exported_callables.len(), out)?; - for exported in &program.exported_callables { - write_string("exported callable name", &exported.name, out)?; - out.extend_from_slice(&exported.local_slot.to_le_bytes()); - } - Ok(()) -} - -fn write_named_struct_decls(out: &mut Vec, program: &Program) -> Result<(), WireError> { - let mut decls = program.named_struct_decls().values().collect::>(); - decls.sort_unstable_by(|lhs, rhs| lhs.name.cmp(&rhs.name)); - write_u32_count("named struct decls", decls.len(), out)?; - for decl in decls { - write_string("named struct name", &decl.name, out)?; - write_u32_count("named struct type params", decl.type_params.len(), out)?; - for type_param in &decl.type_params { - write_string("named struct type param", type_param, out)?; - } - write_schema(&decl.body_schema, out)?; - } - Ok(()) -} - -fn write_u16_list(field: &'static str, values: &[u16], out: &mut Vec) -> Result<(), WireError> { - write_u32_count(field, values.len(), out)?; - for value in values { - out.extend_from_slice(&value.to_le_bytes()); - } - Ok(()) -} - -fn write_debug_info(out: &mut Vec, debug: Option<&DebugInfo>) -> Result<(), WireError> { - match debug { - None => { - out.push(0); - Ok(()) - } - Some(debug) => { - out.push(1); - - match &debug.source { - None => out.push(0), - Some(source) => { - out.push(1); - write_string("debug source", source, out)?; - } - } - - write_u32_count("debug lines", debug.lines.len(), out)?; - for line in &debug.lines { - out.extend_from_slice(&line.offset.to_le_bytes()); - out.extend_from_slice(&line.line.to_le_bytes()); - } - - write_u32_count("debug functions", debug.functions.len(), out)?; - for function in &debug.functions { - write_string("debug function name", &function.name, out)?; - write_u32_count("debug function args", function.args.len(), out)?; - for arg in &function.args { - write_string("debug arg name", &arg.name, out)?; - out.push(arg.position); - } - } - - write_u32_count("debug locals", debug.locals.len(), out)?; - for local in &debug.locals { - write_string("debug local name", &local.name, out)?; - out.push(local.index); - write_optional_u32(local.declared_line, out); - write_optional_u32(local.last_line, out); - } - - Ok(()) - } - } -} - -fn write_type_map(out: &mut Vec, type_map: Option<&TypeMap>) -> Result<(), WireError> { - let Some(type_map) = type_map else { - out.push(0); - return Ok(()); - }; - - out.push(1); - out.push(u8::from(type_map.strict_types)); - write_u32_count("type map locals", type_map.local_types.len(), out)?; - for ty in &type_map.local_types { - out.push(*ty as u8); - } - for schema in &type_map.local_schemas { - write_optional_schema(schema.as_ref(), out)?; - } - write_bool_slice("type map callable slots", &type_map.callable_slots, out)?; - write_bool_slice("type map optional slots", &type_map.optional_slots, out)?; - - write_u32_count("type map operands", type_map.operand_types.len(), out)?; - let mut operand_entries = type_map - .operand_types - .iter() - .map(|(offset, pair)| (*offset, *pair)) - .collect::>(); - operand_entries.sort_unstable_by_key(|(offset, _)| *offset); - for (offset, (lhs, rhs)) in operand_entries { - write_u32_count("type map operand offset", offset, out)?; - out.push(lhs as u8); - out.push(rhs as u8); - } - Ok(()) -} - -fn write_optional_u32(value: Option, out: &mut Vec) { - match value { - Some(value) => { - out.push(1); - out.extend_from_slice(&value.to_le_bytes()); - } - None => out.push(0), - } -} - -fn write_bool_slice( - field: &'static str, - values: &[bool], - out: &mut Vec, -) -> Result<(), WireError> { - write_u32_count(field, values.len(), out)?; - out.extend(values.iter().map(|value| u8::from(*value))); - Ok(()) -} - -fn write_optional_schema(schema: Option<&TypeSchema>, out: &mut Vec) -> Result<(), WireError> { - match schema { - Some(schema) => { - out.push(1); - write_schema(schema, out)?; - } - None => out.push(0), - } - Ok(()) -} - -fn write_optional_host_import_schema( - schema: Option<&HostImportSchema>, - out: &mut Vec, -) -> Result<(), WireError> { - match schema { - Some(schema) => { - out.push(1); - write_host_import_schema(schema, out)?; - } - None => out.push(0), - } - Ok(()) -} - -fn write_host_import_schema(schema: &HostImportSchema, out: &mut Vec) -> Result<(), WireError> { - schema - .validate() - .map_err(|error| WireError::InvalidHostSchemaComplexity(error.to_string()))?; - write_string("host import schema name", &schema.name, out)?; - write_u32_count("host import schema parameters", schema.params.len(), out)?; - for param in &schema.params { - write_string("host import parameter name", ¶m.name, out)?; - write_host_type_schema(¶m.schema, out, 0)?; - out.push(match param.passing { - HostParamPassing::Value => 0, - HostParamPassing::Borrow => 1, - HostParamPassing::BorrowMut => 2, - HostParamPassing::TakeOwned => 3, - }); - } - write_host_type_schema(&schema.return_type, out, 0)?; - out.extend_from_slice(&schema.fingerprint.as_u64().to_le_bytes()); - Ok(()) -} - -fn write_host_type_schema( - schema: &HostTypeSchema, - out: &mut Vec, - depth: usize, -) -> Result<(), WireError> { - if depth >= MAX_HOST_SCHEMA_DEPTH { - return Err(WireError::LengthTooLarge( - "host schema nesting depth", - depth, - )); - } - match schema { - HostTypeSchema::Unknown => out.push(0), - HostTypeSchema::Null => out.push(1), - HostTypeSchema::Int => out.push(2), - HostTypeSchema::Float => out.push(3), - HostTypeSchema::Number => out.push(4), - HostTypeSchema::Bool => out.push(5), - HostTypeSchema::String => out.push(6), - HostTypeSchema::Bytes => out.push(7), - HostTypeSchema::Array(inner) => { - out.push(8); - write_host_type_schema(inner, out, next_host_schema_depth(depth)?)?; - } - HostTypeSchema::Map(inner) => { - out.push(9); - write_host_type_schema(inner, out, next_host_schema_depth(depth)?)?; - } - HostTypeSchema::Optional(inner) => { - out.push(10); - write_host_type_schema(inner, out, next_host_schema_depth(depth)?)?; - } - HostTypeSchema::Callable { params, result } => { - out.push(11); - write_u32_count("host callable parameters", params.len(), out)?; - for param in params { - write_host_type_schema(param, out, depth + 1)?; - } - write_host_type_schema(result, out, depth + 1)?; - } - HostTypeSchema::Resource(key) => { - out.push(12); - write_string("host resource type key", key.as_str(), out)?; - } - HostTypeSchema::Named { name, fields } => { - out.push(13); - write_string("host named struct name", name, out)?; - write_u32_count("host named struct fields", fields.len(), out)?; - for field in fields { - write_string("host named struct field name", &field.name, out)?; - write_host_type_schema(&field.ty, out, next_host_schema_depth(depth)?)?; - } - } - } - Ok(()) -} - -fn next_host_schema_depth(depth: usize) -> Result { - depth.checked_add(1).ok_or(WireError::LengthTooLarge( - "host schema nesting depth", - depth, - )) -} - -fn write_schema(schema: &TypeSchema, out: &mut Vec) -> Result<(), WireError> { - match schema { - TypeSchema::Unknown => out.push(0), - TypeSchema::Null => out.push(1), - TypeSchema::Int => out.push(2), - TypeSchema::Float => out.push(3), - TypeSchema::Number => out.push(4), - TypeSchema::Bool => out.push(5), - TypeSchema::String => out.push(6), - TypeSchema::Bytes => out.push(7), - TypeSchema::Optional(inner) => { - out.push(16); - write_schema(inner, out)?; - } - TypeSchema::GenericParam(name) => { - out.push(8); - write_string("schema generic", name, out)?; - } - TypeSchema::Named(name, type_args) => { - out.push(9); - write_string("schema name", name, out)?; - write_u32_count("schema type args", type_args.len(), out)?; - for type_arg in type_args { - write_schema(type_arg, out)?; - } - } - TypeSchema::Array(item) => { - out.push(10); - write_schema(item, out)?; - } - TypeSchema::ArrayTuple(items) => { - out.push(11); - write_u32_count("schema tuple items", items.len(), out)?; - for item in items { - write_schema(item, out)?; - } - } - TypeSchema::ArrayTupleRest { prefix, rest } => { - out.push(12); - write_u32_count("schema tuple prefix", prefix.len(), out)?; - for item in prefix { - write_schema(item, out)?; - } - write_schema(rest, out)?; - } - TypeSchema::Map(item) => { - out.push(13); - write_schema(item, out)?; - } - TypeSchema::Object(fields) => { - out.push(14); - let mut entries = fields.iter().collect::>(); - entries.sort_unstable_by_key(|(name, _)| *name); - write_u32_count("schema object fields", entries.len(), out)?; - for (name, value) in entries { - write_string("schema object field", name, out)?; - write_schema(value, out)?; - } - } - TypeSchema::Callable { params, result } => { - out.push(15); - write_u32_count("schema callable params", params.len(), out)?; - for param in params { - write_schema(param, out)?; - } - write_schema(result, out)?; - } - TypeSchema::Resource(key) => { - out.push(17); - write_string("schema resource key", key.as_str(), out)?; - } - } - Ok(()) -} - -fn write_string(field: &'static str, value: &str, out: &mut Vec) -> Result<(), WireError> { - write_u32_len(field, value.len(), out)?; - out.extend_from_slice(value.as_bytes()); - Ok(()) -} - -fn write_u32_len(field: &'static str, len: usize, out: &mut Vec) -> Result<(), WireError> { - let len_u32 = u32::try_from(len).map_err(|_| WireError::LengthTooLarge(field, len))?; - out.extend_from_slice(&len_u32.to_le_bytes()); - Ok(()) -} - -fn write_u32_count(field: &'static str, count: usize, out: &mut Vec) -> Result<(), WireError> { - write_u32_len(field, count, out) -} diff --git a/native/pd-vm-compiler/stdlib/http/upstream/response.rss b/native/pd-vm-compiler/stdlib/http/upstream/response.rss index fcc15785..2f8a23ce 100644 --- a/native/pd-vm-compiler/stdlib/http/upstream/response.rss +++ b/native/pd-vm-compiler/stdlib/http/upstream/response.rss @@ -10,7 +10,7 @@ pub fn get_status() -> int { http::exchange::get_status(upstream_response_default_exchange()) } -pub fn get_header(name: string) -> string { +pub fn get_header(name: string) -> Result, string> { http::exchange::get_header(upstream_response_default_exchange(), name) } diff --git a/native/pd-vm-compiler/tests/frozen_abi.rs b/native/pd-vm-compiler/tests/frozen_abi.rs index 585bb632..27fca093 100644 --- a/native/pd-vm-compiler/tests/frozen_abi.rs +++ b/native/pd-vm-compiler/tests/frozen_abi.rs @@ -1,4 +1,4 @@ -//! Frozen core/pd-edge ABI 25 pin proofs and the checked-in example corpus. +//! Frozen core/pd-edge ABI 26 pin proofs and the checked-in example corpus. use std::collections::BTreeSet; use std::path::{Path, PathBuf}; @@ -7,11 +7,11 @@ use std::ptr; use edge::{ABI_VERSION, function_by_name, host_namespace_specs}; use pd_vm_compiler::compile_edge_source_file; -const FROZEN_CORE_REV: &str = "b1d6cffede77f49410bf63525f30b9a46b02dc01"; +const FROZEN_CORE_REV: &str = "2f433edab3f1907e8cb060e901357d7e2af016ce"; const FROZEN_CORE_URL: &str = "https://github.com/rustscript-lang/rustscript.git"; -const FROZEN_EDGE_REV: &str = "5f4f889e349bdfbd5534deb42bd13b616a6114f5"; +const FROZEN_EDGE_REV: &str = "9a9ee3303a17fcf65893f04b1ce4e4df9d7f50c1"; const FROZEN_EDGE_URL: &str = "https://github.com/rustscript-lang/pd-edge.git"; -const FROZEN_EDGE_ABI: u16 = 25; +const FROZEN_EDGE_ABI: u16 = 26; const EXPECTED_EXAMPLES: usize = 7; fn manifest_dir() -> PathBuf { @@ -361,7 +361,7 @@ fn ci_resolves_pins_from_cargo_and_does_not_use_sibling_checkouts() { } #[test] -fn edge_abi_is_version_25_with_typed_http_catalog_and_named_mqtt_event_surface() { +fn edge_abi_is_version_26_with_typed_http_catalog_and_named_mqtt_event_surface() { assert_eq!(ABI_VERSION, FROZEN_EDGE_ABI); let namespaces: Vec<&str> = host_namespace_specs() .iter() @@ -376,8 +376,8 @@ fn edge_abi_is_version_25_with_typed_http_catalog_and_named_mqtt_event_surface() let manifest = edge::abi_json(); assert!( - manifest.contains("\"abi_version\": 25"), - "published ABI JSON must record version 25" + manifest.contains("\"abi_version\": 26"), + "published ABI JSON must record version 26" ); if let Some(function) = function_by_name("mqtt::connection::next_event") { @@ -427,8 +427,8 @@ fn native_compiler_compiles_and_executes_the_non_overlay_example_corpus() { ); assert_eq!( u16::from_le_bytes(vmbc[4..6].try_into().expect("VMBC version bytes")), - 13, - "{} must emit VMBC v13", + 14, + "{} must emit VMBC v14", path.display() ); compiled.push((path.clone(), program, source));