diff --git a/docs/building.md b/docs/building.md index c62e141..7adc664 100644 --- a/docs/building.md +++ b/docs/building.md @@ -126,6 +126,26 @@ Build and execution commands act on the document active when the command starts. The compiler currently supports `.zasm`; `.zsrc` files can be opened, edited, and saved, but are not yet supported by the compiler. +Save, validation, build, and optional run/debug startup are coordinated by +`EditorExecutionCoordinator` using Lite.StateMachine. The state classes all use +the `State` suffix: `ValidateCompilerState`, `SaveSourceState`, +`ValidateSourceState`, `CompileState`, `LaunchState`, and the terminal +`CompletedState`, `CanceledState`, `FailedState`, and `RunFailedState`. +Canceling the save picker stops the workflow before compilation; this does not +add cancellation of an already-running compiler process. Failed compilation +never launches a program, and run failures retain compiler diagnostics. +Debug startup always builds the Debug configuration. Each request captures its +source document, compiler path, and configuration, and overlapping executions +are rejected. UI callbacks return to the caller's synchronization context. +The native debugger session continues to own running/paused state independently. +See the [generated execution state diagrams](ide-execution.md) for Build, Run, +and Debug flows and regeneration instructions. + +Other potential state-machine workflows include update download/verification/ +installation, extension activation/deactivation, and future project loading +and dependency restoration. Those workflows are not implemented as state +machines yet; simple editor and docking notifications do not need one. + The toolbar provides icon buttons for New, Open, Save, Undo, Redo, and Build and Execute. Hover over a button for its name and shortcut. The build configuration selector offers Debug and Release. Play or F5 builds and launches the current diff --git a/docs/ide-execution.md b/docs/ide-execution.md new file mode 100644 index 0000000..733f7a4 --- /dev/null +++ b/docs/ide-execution.md @@ -0,0 +1,70 @@ +# IDE execution state diagrams + +These diagrams are generated by Lite.StateMachine's `ExportUml` method from the +same registered transitions used by `EditorExecutionCoordinator`. They describe +build and launch orchestration, not the native debugger's running/paused states. + +State labels use the class names; normal steps and cancellation/run-failure +branches carry the execution numbering from the XML comments. +Blue **Success** edges continue the workflow. Red **Error** edges report a +failure. The amber **Failure** edge from `SaveSourceState` means the user +canceled saving; no compilation or launch follows. Black circles mark entry and +terminal exits. Each request ends at one terminal state; terminals do not execute +in sequence. + +## Build only + +Successful compilation goes straight to `CompletedState`, skipping step 5. +The clean-and-build option is handled within `CompileState`. + +![Build-only execution state diagram](images/ide-execution/build.svg) + +[Graphviz DOT source](images/ide-execution/build.dot) + +## Build and run without debugging + +After compilation, `LaunchState` starts the program. Launch errors lead to +`RunFailedState`, retaining successful compiler diagnostics. + +![Build-and-run execution state diagram](images/ide-execution/run.svg) + +[Graphviz DOT source](images/ide-execution/run.dot) + +## Build and start debugging + +Debug startup always uses the Debug configuration. `LaunchState` starts the +debugger; startup errors lead to `FailedState`. After startup completes, the +separate `IDebugSession` owns execution, pause, step, and stop state. + +![Build-and-debug execution state diagram](images/ide-execution/debug.svg) + +[Graphviz DOT source](images/ide-execution/debug.dot) + +`Built` is a progress notification emitted inside `CompileState`, not a separate +registered state, so it does not appear as a node. + +## Regenerating + +From the repository root, export all three DOT files without executing the +workflow, saving documents, invoking a compiler, or starting a debugger: + +```powershell +dotnet run --project source/Zero.Ide.Diagrams/Zero.Ide.Diagrams.csproj -c Release -- docs/images/ide-execution +``` + +Render the DOT files with a local Graphviz installation, for example: + +```powershell +dot -Tsvg docs/images/ide-execution/run.dot -o docs/images/ide-execution/run.svg +``` + +To reproduce the committed SVG styling without a system Graphviz installation, +use the optional Graphviz WebAssembly renderer (requires Node.js and npm): + +```powershell +npm install --prefix output/ide-diagram-tools --no-save --ignore-scripts --no-audit --no-fund @viz-js/viz@3.31.0 +node source/Zero.Ide.Diagrams/render.mjs output/ide-diagram-tools/node_modules/@viz-js/viz/dist/viz.js docs/images/ide-execution +``` + +The renderer changes presentation only. State names, edges, and transition +results come directly from Lite.StateMachine's exported DOT. diff --git a/docs/images/ide-execution/build.dot b/docs/images/ide-execution/build.dot new file mode 100644 index 0000000..98d2590 --- /dev/null +++ b/docs/images/ide-execution/build.dot @@ -0,0 +1,26 @@ +digraph "Zero IDE — Build" { + compound=true; + fontsize=12; + "ValidateCompiler" [shape=box, style=rounded, label="1. ValidateCompilerState"]; + "Save" [shape=box, style=rounded, label="2. SaveSourceState"]; + "ValidateSource" [shape=box, style=rounded, label="3. ValidateSourceState"]; + "Build" [shape=box, style=rounded, label="4. CompileState"]; + "Completed" [shape=box, style=rounded, label="6. CompletedState"]; + "Canceled" [shape=box, style=rounded, label="2a. CanceledState"]; + "Failed" [shape=box, style=rounded, label="FailedState"]; + "ValidateCompiler" -> "Save" [color="#2563EB", label="Success"]; + "ValidateCompiler" -> "Failed" [color="#B91C1C", label="Error"]; + "Save" -> "ValidateSource" [color="#2563EB", label="Success"]; + "Save" -> "Failed" [color="#B91C1C", label="Error"]; + "Save" -> "Canceled" [color="#B45309", label="Failure"]; + "ValidateSource" -> "Build" [color="#2563EB", label="Success"]; + "ValidateSource" -> "Failed" [color="#B91C1C", label="Error"]; + "Build" -> "Completed" [color="#2563EB", label="Success"]; + "Build" -> "Failed" [color="#B91C1C", label="Error"]; + "start_global" [shape=circle, style=filled, fillcolor="black", color="black", label="", width=0.25, height=0.25, fixedsize=true]; + "start_global" -> "ValidateCompiler" [color="black", label="start"]; + "final_global" [shape=doublecircle, style=filled, fillcolor="black", color="black", label="", width=0.35, height=0.35, fixedsize=true]; + "Completed" -> "final_global" [color="black", label="final"]; + "Canceled" -> "final_global" [color="black", label="final"]; + "Failed" -> "final_global" [color="black", label="final"]; +} diff --git a/docs/images/ide-execution/build.svg b/docs/images/ide-execution/build.svg new file mode 100644 index 0000000..05d6786 --- /dev/null +++ b/docs/images/ide-execution/build.svg @@ -0,0 +1,158 @@ + + + + + + +Zero IDE — Build + +Zero IDE — Build + + +ValidateCompiler + +1. ValidateCompilerState + + + +Save + +2. SaveSourceState + + + +ValidateCompiler->Save + + +Success + + + +Failed + +FailedState + + + +ValidateCompiler->Failed + + +Error + + + +ValidateSource + +3. ValidateSourceState + + + +Save->ValidateSource + + +Success + + + +Canceled + +2a. CanceledState + + + +Save->Canceled + + +Failure + + + +Save->Failed + + +Error + + + +Build + +4. CompileState + + + +ValidateSource->Build + + +Success + + + +ValidateSource->Failed + + +Error + + + +Completed + +6. CompletedState + + + +Build->Completed + + +Success + + + +Build->Failed + + +Error + + + +final_global + + + + + +Completed->final_global + + +final + + + +Canceled->final_global + + +final + + + +Failed->final_global + + +final + + + +start_global + + + + +start_global->ValidateCompiler + + +start + + + diff --git a/docs/images/ide-execution/debug.dot b/docs/images/ide-execution/debug.dot new file mode 100644 index 0000000..6970ba2 --- /dev/null +++ b/docs/images/ide-execution/debug.dot @@ -0,0 +1,29 @@ +digraph "Zero IDE — Debug" { + compound=true; + fontsize=12; + "ValidateCompiler" [shape=box, style=rounded, label="1. ValidateCompilerState"]; + "Save" [shape=box, style=rounded, label="2. SaveSourceState"]; + "ValidateSource" [shape=box, style=rounded, label="3. ValidateSourceState"]; + "Build" [shape=box, style=rounded, label="4. CompileState"]; + "Completed" [shape=box, style=rounded, label="6. CompletedState"]; + "Canceled" [shape=box, style=rounded, label="2a. CanceledState"]; + "Failed" [shape=box, style=rounded, label="FailedState"]; + "Launch" [shape=box, style=rounded, label="5. LaunchState"]; + "ValidateCompiler" -> "Save" [color="#2563EB", label="Success"]; + "ValidateCompiler" -> "Failed" [color="#B91C1C", label="Error"]; + "Save" -> "ValidateSource" [color="#2563EB", label="Success"]; + "Save" -> "Failed" [color="#B91C1C", label="Error"]; + "Save" -> "Canceled" [color="#B45309", label="Failure"]; + "ValidateSource" -> "Build" [color="#2563EB", label="Success"]; + "ValidateSource" -> "Failed" [color="#B91C1C", label="Error"]; + "Build" -> "Launch" [color="#2563EB", label="Success"]; + "Build" -> "Failed" [color="#B91C1C", label="Error"]; + "Launch" -> "Completed" [color="#2563EB", label="Success"]; + "Launch" -> "Failed" [color="#B91C1C", label="Error"]; + "start_global" [shape=circle, style=filled, fillcolor="black", color="black", label="", width=0.25, height=0.25, fixedsize=true]; + "start_global" -> "ValidateCompiler" [color="black", label="start"]; + "final_global" [shape=doublecircle, style=filled, fillcolor="black", color="black", label="", width=0.35, height=0.35, fixedsize=true]; + "Completed" -> "final_global" [color="black", label="final"]; + "Canceled" -> "final_global" [color="black", label="final"]; + "Failed" -> "final_global" [color="black", label="final"]; +} diff --git a/docs/images/ide-execution/debug.svg b/docs/images/ide-execution/debug.svg new file mode 100644 index 0000000..b08b608 --- /dev/null +++ b/docs/images/ide-execution/debug.svg @@ -0,0 +1,178 @@ + + + + + + +Zero IDE — Debug + +Zero IDE — Debug + + +ValidateCompiler + +1. ValidateCompilerState + + + +Save + +2. SaveSourceState + + + +ValidateCompiler->Save + + +Success + + + +Failed + +FailedState + + + +ValidateCompiler->Failed + + +Error + + + +ValidateSource + +3. ValidateSourceState + + + +Save->ValidateSource + + +Success + + + +Canceled + +2a. CanceledState + + + +Save->Canceled + + +Failure + + + +Save->Failed + + +Error + + + +Build + +4. CompileState + + + +ValidateSource->Build + + +Success + + + +ValidateSource->Failed + + +Error + + + +Build->Failed + + +Error + + + +Launch + +5. LaunchState + + + +Build->Launch + + +Success + + + +Completed + +6. CompletedState + + + +final_global + + + + + +Completed->final_global + + +final + + + +Canceled->final_global + + +final + + + +Failed->final_global + + +final + + + +Launch->Completed + + +Success + + + +Launch->Failed + + +Error + + + +start_global + + + + +start_global->ValidateCompiler + + +start + + + diff --git a/docs/images/ide-execution/run.dot b/docs/images/ide-execution/run.dot new file mode 100644 index 0000000..27f2e98 --- /dev/null +++ b/docs/images/ide-execution/run.dot @@ -0,0 +1,31 @@ +digraph "Zero IDE — Run" { + compound=true; + fontsize=12; + "ValidateCompiler" [shape=box, style=rounded, label="1. ValidateCompilerState"]; + "Save" [shape=box, style=rounded, label="2. SaveSourceState"]; + "ValidateSource" [shape=box, style=rounded, label="3. ValidateSourceState"]; + "Build" [shape=box, style=rounded, label="4. CompileState"]; + "Completed" [shape=box, style=rounded, label="6. CompletedState"]; + "Canceled" [shape=box, style=rounded, label="2a. CanceledState"]; + "Failed" [shape=box, style=rounded, label="FailedState"]; + "Launch" [shape=box, style=rounded, label="5. LaunchState"]; + "RunFailed" [shape=box, style=rounded, label="5a. RunFailedState"]; + "ValidateCompiler" -> "Save" [color="#2563EB", label="Success"]; + "ValidateCompiler" -> "Failed" [color="#B91C1C", label="Error"]; + "Save" -> "ValidateSource" [color="#2563EB", label="Success"]; + "Save" -> "Failed" [color="#B91C1C", label="Error"]; + "Save" -> "Canceled" [color="#B45309", label="Failure"]; + "ValidateSource" -> "Build" [color="#2563EB", label="Success"]; + "ValidateSource" -> "Failed" [color="#B91C1C", label="Error"]; + "Build" -> "Launch" [color="#2563EB", label="Success"]; + "Build" -> "Failed" [color="#B91C1C", label="Error"]; + "Launch" -> "Completed" [color="#2563EB", label="Success"]; + "Launch" -> "RunFailed" [color="#B91C1C", label="Error"]; + "start_global" [shape=circle, style=filled, fillcolor="black", color="black", label="", width=0.25, height=0.25, fixedsize=true]; + "start_global" -> "ValidateCompiler" [color="black", label="start"]; + "final_global" [shape=doublecircle, style=filled, fillcolor="black", color="black", label="", width=0.35, height=0.35, fixedsize=true]; + "Completed" -> "final_global" [color="black", label="final"]; + "Canceled" -> "final_global" [color="black", label="final"]; + "Failed" -> "final_global" [color="black", label="final"]; + "RunFailed" -> "final_global" [color="black", label="final"]; +} diff --git a/docs/images/ide-execution/run.svg b/docs/images/ide-execution/run.svg new file mode 100644 index 0000000..bea5d70 --- /dev/null +++ b/docs/images/ide-execution/run.svg @@ -0,0 +1,191 @@ + + + + + + +Zero IDE — Run + +Zero IDE — Run + + +ValidateCompiler + +1. ValidateCompilerState + + + +Save + +2. SaveSourceState + + + +ValidateCompiler->Save + + +Success + + + +Failed + +FailedState + + + +ValidateCompiler->Failed + + +Error + + + +ValidateSource + +3. ValidateSourceState + + + +Save->ValidateSource + + +Success + + + +Canceled + +2a. CanceledState + + + +Save->Canceled + + +Failure + + + +Save->Failed + + +Error + + + +Build + +4. CompileState + + + +ValidateSource->Build + + +Success + + + +ValidateSource->Failed + + +Error + + + +Build->Failed + + +Error + + + +Launch + +5. LaunchState + + + +Build->Launch + + +Success + + + +Completed + +6. CompletedState + + + +final_global + + + + + +Completed->final_global + + +final + + + +Canceled->final_global + + +final + + + +Failed->final_global + + +final + + + +Launch->Completed + + +Success + + + +RunFailed + +5a. RunFailedState + + + +Launch->RunFailed + + +Error + + + +RunFailed->final_global + + +final + + + +start_global + + + + +start_global->ValidateCompiler + + +start + + + diff --git a/source/Zero.Ide.Diagrams/Program.cs b/source/Zero.Ide.Diagrams/Program.cs new file mode 100644 index 0000000..6afbc06 --- /dev/null +++ b/source/Zero.Ide.Diagrams/Program.cs @@ -0,0 +1,14 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System.Text; +using Zero.Ide.Services; + +var destination = Path.GetFullPath(args.Length > 0 ? args[0] : "docs/images/ide-execution"); +Directory.CreateDirectory(destination); +foreach (var mode in Enum.GetValues()) +{ + var path = Path.Combine(destination, $"{mode.ToString().ToLowerInvariant()}.dot"); + File.WriteAllText(path, EditorExecutionCoordinator.ExportStateDiagram(mode), new UTF8Encoding(false)); + Console.WriteLine(path); +} diff --git a/source/Zero.Ide.Diagrams/Zero.Ide.Diagrams.csproj b/source/Zero.Ide.Diagrams/Zero.Ide.Diagrams.csproj new file mode 100644 index 0000000..64289f4 --- /dev/null +++ b/source/Zero.Ide.Diagrams/Zero.Ide.Diagrams.csproj @@ -0,0 +1,13 @@ + + + Exe + net10.0 + $(NETCoreSdkRuntimeIdentifier) + enable + enable + ../../output/Zero.Ide.Diagrams/ + + + + + diff --git a/source/Zero.Ide.Diagrams/render.mjs b/source/Zero.Ide.Diagrams/render.mjs new file mode 100644 index 0000000..7bb2365 --- /dev/null +++ b/source/Zero.Ide.Diagrams/render.mjs @@ -0,0 +1,20 @@ +// Render Lite.StateMachine's exported DOT with Graphviz, without changing its topology. +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +const [rendererModule, destination = 'docs/images/ide-execution'] = process.argv.slice(2); +if (!rendererModule) throw new Error('Pass the path to @viz-js/viz/dist/viz.js.'); +const { instance } = await import(pathToFileURL(path.resolve(rendererModule)).href); +const viz = await instance(); +for (const mode of ['build', 'run', 'debug']) { + const dot = await fs.readFile(path.join(destination, `${mode}.dot`), 'utf8'); + const svg = viz.renderString(dot, { + format: 'svg', engine: 'dot', + graphAttributes: { bgcolor: 'white', pad: '0.3', nodesep: '0.5', ranksep: '0.55', label: `Zero IDE — ${mode[0].toUpperCase()}${mode.slice(1)}`, labelloc: 't', fontname: 'Arial', fontsize: '20' }, + nodeAttributes: { fontname: 'Arial', fontsize: '12', color: '#64748B', fontcolor: '#0F172A', penwidth: '1.2', margin: '0.15,0.1' }, + edgeAttributes: { fontname: 'Arial', fontsize: '10', penwidth: '1.3' }, + }); + await fs.writeFile(path.join(destination, `${mode}.svg`), svg); + console.log(path.join(destination, `${mode}.svg`)); +} diff --git a/source/Zero.Ide.Tests/EditorExecutionCoordinatorTests.cs b/source/Zero.Ide.Tests/EditorExecutionCoordinatorTests.cs new file mode 100644 index 0000000..20b3da7 --- /dev/null +++ b/source/Zero.Ide.Tests/EditorExecutionCoordinatorTests.cs @@ -0,0 +1,269 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Avalonia.Headless; +using Avalonia.Threading; +using Moq; +using Zero.Ide.Models; +using Zero.Ide.Services; + +namespace Zero.Ide.Tests; + +[TestClass] +[DoNotParallelize] +public class EditorExecutionCoordinatorTests +{ + [TestMethod] + [DataRow(EditorExecutionMode.Build)] + [DataRow(EditorExecutionMode.Run)] + [DataRow(EditorExecutionMode.Debug)] + public void DiagramExportUsesModeSpecificRegisteredTransitions(EditorExecutionMode mode) + { + var dot = EditorExecutionCoordinator.ExportStateDiagram(mode); + Assert.Contains("1. ValidateCompilerState", dot); + Assert.Contains("4. CompileState", dot); + Assert.Contains("\"Save\" -> \"Canceled\"", dot); + Assert.Contains("\"Build\" -> \"Failed\"", dot); + Assert.DoesNotContain("\"Built\" [", dot); // Built is a notification, not a registered state. + if (mode == EditorExecutionMode.Build) + { + Assert.Contains("\"Build\" -> \"Completed\"", dot); + Assert.DoesNotContain("LaunchState", dot); + } + else + { + Assert.Contains("\"Build\" -> \"Launch\"", dot); + Assert.Contains(mode == EditorExecutionMode.Run ? "\"Launch\" -> \"RunFailed\"" : "\"Launch\" -> \"Failed\"", dot); + } + + if (mode != EditorExecutionMode.Run) Assert.DoesNotContain("RunFailedState", dot); + } + + private static string SourcePath => Path.Combine(Path.GetTempPath(), "program" + SourceFileExtensions.Assembly); + + [TestMethod] + public async Task CancelingSaveNeverValidatesBuildsOrLaunchesAsync() + { + var compiler = new Mock(MockBehavior.Strict); + var runner = new Mock(MockBehavior.Strict); + var stages = new List(); + + var result = await new EditorExecutionCoordinator(compiler.Object, runner.Object).ExecuteAsync( + Request(EditorExecutionMode.Run) with + { + SaveSourceAsync = () => Task.FromResult(null) + }, update => stages.Add(update.Stage)); + + Assert.AreEqual(EditorExecutionStage.Canceled, result.Stage); + Assert.AreSequenceEqual(new[] { EditorExecutionStage.ValidateCompiler, EditorExecutionStage.Save, EditorExecutionStage.Canceled }, stages); + + compiler.VerifyNoOtherCalls(); + runner.VerifyNoOtherCalls(); + } + + [TestMethod] + public async Task ConcurrentExecutionIsRejectedWithoutASecondCompilerProcessAsync() + { + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var compiler = new Mock(); + + compiler + .Setup(c => c.BuildAsync(It.IsAny(), It.IsAny(), It.IsAny(), false)) + .Callback(() => entered.SetResult()).Returns(finished.Task); + + var coordinator = new EditorExecutionCoordinator(compiler.Object); + var first = coordinator.ExecuteAsync(Request(EditorExecutionMode.Build), _ => { }); + + await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + + try + { + await Assert.ThrowsExactlyAsync( + () => coordinator.ExecuteAsync(Request(EditorExecutionMode.Build), _ => { })); + } + finally + { + finished.TrySetResult(new CompilerResult(0, "compiled", "program.exe")); + await first; + } + + compiler.Verify( + c => c.BuildAsync(It.IsAny(), It.IsAny(), It.IsAny(), false), + Times.Once); + } + + [TestMethod] + [DataRow("missing-compiler")] + [DataRow("invalid-source")] + [DataRow("save-error")] + [DataRow("compiler-error")] + [DataRow("compiler-exception")] + public async Task FailuresStopTheWorkflowBeforeLaunchingAsync(string failure) + { + var compiler = new Mock(); + var compilation = new CompilerResult(2, "bad instruction", "program.exe"); + compiler + .Setup(c => c.BuildAsync(It.IsAny(), It.IsAny(), It.IsAny(), false)) + .ReturnsAsync(compilation); + + if (failure == "compiler-exception") + compiler + .Setup(c => c.BuildAsync(It.IsAny(), It.IsAny(), It.IsAny(), false)) + .ThrowsAsync(new IOException("Unable to start")); + + var runner = new Mock(MockBehavior.Strict); + var request = Request(EditorExecutionMode.Run); + + if (failure == "missing-compiler") + request = request with { CompilerPath = "" }; + + if (failure == "invalid-source") + request = request with { SaveSourceAsync = () => Task.FromResult(Path.ChangeExtension(SourcePath, SourceFileExtensions.Source)) }; + + if (failure == "save-error") + request = request with { SaveSourceAsync = () => throw new IOException("Disk full") }; + + var result = await new EditorExecutionCoordinator(compiler.Object, runner.Object).ExecuteAsync(request, _ => { }); + Assert.AreEqual(EditorExecutionStage.Failed, result.Stage); + + if (failure == "compiler-error") + Assert.AreSame(compilation, result.Compilation); + else + Assert.IsNotNull(result.Error); + + if (failure is "missing-compiler" or "invalid-source" or "save-error") + compiler.VerifyNoOtherCalls(); + + runner.VerifyNoOtherCalls(); + } + + [TestMethod] + [DataRow(EditorExecutionMode.Run, EditorExecutionStage.RunFailed)] + [DataRow(EditorExecutionMode.Debug, EditorExecutionStage.Failed)] + public async Task LaunchFailuresPreserveCompilerOutputAndPermitRetryAsync(EditorExecutionMode mode, EditorExecutionStage expected) + { + var compiler = new Mock(); + + compiler.Setup(c => c.BuildAsync(It.IsAny(), It.IsAny(), It.IsAny(), false)) + .ReturnsAsync(new CompilerResult(0, "compiled successfully", "program.exe")); + + var runner = new Mock(); + runner.Setup(r => r.Run(It.IsAny(), It.IsAny())) + .Throws(new InvalidOperationException("Cannot run")); + + var coordinator = new EditorExecutionCoordinator(compiler.Object, runner.Object); + var result = await coordinator.ExecuteAsync(Request(mode) with { StartDebuggerAsync = (_, _) => throw new InvalidOperationException("No debug map") }, _ => { }); + + Assert.AreEqual(expected, result.Stage); + Assert.AreEqual("compiled successfully", result.Compilation!.Output); + Assert.IsNotNull(result.Error); + Assert.AreEqual(EditorExecutionStage.Completed, (await coordinator.ExecuteAsync(Request(EditorExecutionMode.Build), _ => { })).Stage); + } + + [TestMethod] + [DataRow(EditorExecutionMode.Build)] + [DataRow(EditorExecutionMode.Run)] + [DataRow(EditorExecutionMode.Debug)] + public async Task SuccessfulWorkflowSavesBuildsThenUsesOnlyRequestedLauncherAsync(EditorExecutionMode mode) + { + var calls = new List(); + var compiler = new Mock(); + var configuration = mode == EditorExecutionMode.Debug ? BuildConstants.DebugConfiguration : BuildConstants.ReleaseConfiguration; + + compiler + .Setup(c => c.BuildAsync("compiler", SourcePath, configuration, true)) + .Callback(() => calls.Add("compile")) + .ReturnsAsync(new CompilerResult(0, "compiled", "program.exe")); + + var runner = new Mock(); + runner.Setup(r => r.Run("program.exe", Path.GetDirectoryName(SourcePath)!)) + .Callback(() => calls.Add("run")); + + var request = new EditorExecutionRequest( + "compiler", + BuildConstants.ReleaseConfiguration, + true, + mode, + () => + { + calls.Add("save"); + return Task.FromResult(SourcePath); + }, + (executable, source) => + { + Assert.AreEqual("program.exe", executable); + Assert.AreEqual(SourcePath, source); + calls.Add("debug"); + return Task.CompletedTask; + }); + + var updates = new List(); + var result = await new EditorExecutionCoordinator(compiler.Object, runner.Object).ExecuteAsync(request, updates.Add); + + Assert.AreEqual(EditorExecutionStage.Completed, result.Stage); + Assert.AreSequenceEqual( + mode == EditorExecutionMode.Build + ? new[] { "save", "compile" } + : new[] { "save", "compile", mode == EditorExecutionMode.Run ? "run" : "debug" }, calls); + + Assert.AreEqual(EditorExecutionStage.ValidateCompiler, updates[0].Stage); + Assert.IsGreaterThan(updates.FindIndex(update => update.Stage == EditorExecutionStage.Build), updates.FindIndex(update => update.Stage == EditorExecutionStage.Built)); + } + + [TestMethod] + public async Task WorkflowCallbacksRemainOnAvaloniaUiThreadAfterAsyncTransitionsAsync() + { + using var session = HeadlessUnitTestSession.StartNew(typeof(DebuggerDockRenderingTests.DockingTestApp)); + await session.Dispatch(async () => + { + var updates = new List(); + var compiler = new Mock(); + + compiler.Setup(c => c.BuildAsync(It.IsAny(), It.IsAny(), It.IsAny(), false)) + .Returns(async () => + { + await Task.Delay(1); + return new CompilerResult(0, "compiled", "program.exe"); + }); + + var coordinator = new EditorExecutionCoordinator(compiler.Object); + var result = await coordinator.ExecuteAsync(Request(EditorExecutionMode.Debug) with + { + SaveSourceAsync = async () => + { + Assert.IsTrue(Dispatcher.UIThread.CheckAccess()); + await Task.Delay(1); + return SourcePath; + }, + StartDebuggerAsync = (_, _) => + { + Assert.IsTrue(Dispatcher.UIThread.CheckAccess()); + return Task.CompletedTask; + }, + }, update => + { + Assert.IsTrue(Dispatcher.UIThread.CheckAccess()); + updates.Add(update); + }); + + Assert.AreEqual(EditorExecutionStage.Completed, result.Stage); + Assert.Contains(update => update.Stage == EditorExecutionStage.Launch, updates); + + return 0; + }, CancellationToken.None); + } + + private static EditorExecutionRequest Request(EditorExecutionMode mode) => + new( + "compiler", + BuildConstants.DebugConfiguration, + false, + mode, + () => Task.FromResult(SourcePath)); +} diff --git a/source/Zero.Ide/App.axaml.cs b/source/Zero.Ide/App.axaml.cs index e8f4035..45ae989 100644 --- a/source/Zero.Ide/App.axaml.cs +++ b/source/Zero.Ide/App.axaml.cs @@ -33,6 +33,7 @@ protected override void RegisterTypes(IContainerRegistry containerRegistry) containerRegistry.RegisterSingleton(); containerRegistry.RegisterSingleton(); containerRegistry.RegisterSingleton(); + containerRegistry.RegisterSingleton(); containerRegistry.RegisterSingleton(); containerRegistry.RegisterSingleton(); diff --git a/source/Zero.Ide/Services/EditorExecutionCoordinator.cs b/source/Zero.Ide/Services/EditorExecutionCoordinator.cs new file mode 100644 index 0000000..1ba9b90 --- /dev/null +++ b/source/Zero.Ide/Services/EditorExecutionCoordinator.cs @@ -0,0 +1,253 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Lite.StateMachine; +using Zero.Ide.Models; + +namespace Zero.Ide.Services; + +public enum EditorExecutionMode +{ Build, Run, Debug } + +public enum EditorExecutionStage +{ + ValidateCompiler, + Save, + ValidateSource, + Build, + Built, + Launch, + Completed, + Canceled, + Failed, + RunFailed, +} + +public sealed record EditorExecutionRequest( + string CompilerPath, string Configuration, bool CleanFirst, EditorExecutionMode Mode, + Func> SaveSourceAsync, Func? StartDebuggerAsync = null); + +public sealed record EditorExecutionUpdate(EditorExecutionStage Stage, CompilerResult? Compilation = null, Exception? Error = null); + +/// Coordinates save, validation, compilation, and optional launch through explicit state transitions. +public sealed class EditorExecutionCoordinator(ICompilerService compiler, IProgramRunner? runner = null) +{ + private int _executing; + + /// Exports the registered workflow for the requested mode as Graphviz DOT without executing any states. + public static string ExportStateDiagram(EditorExecutionMode mode) => CreateMachine(mode).ExportUml( + initialStateIds: [EditorExecutionStage.ValidateCompiler], + includeLegend: false, + transitionColors: new Dictionary + { + [Result.Success] = "#2563EB", [Result.Error] = "#B91C1C", [Result.Failure] = "#B45309", + }, + graphName: $"Zero IDE — {mode}", + rankLeftToRight: false, + nodeLabelSelector: stage => stage switch + { + EditorExecutionStage.ValidateCompiler => $"1. {nameof(ValidateCompilerState)}", + EditorExecutionStage.Save => $"2. {nameof(SaveSourceState)}", + EditorExecutionStage.ValidateSource => $"3. {nameof(ValidateSourceState)}", + EditorExecutionStage.Build => $"4. {nameof(CompileState)}", + EditorExecutionStage.Launch => $"5. {nameof(LaunchState)}", + EditorExecutionStage.Completed => $"6. {nameof(CompletedState)}", + EditorExecutionStage.Canceled => $"2a. {nameof(CanceledState)}", + EditorExecutionStage.Failed => nameof(FailedState), + EditorExecutionStage.RunFailed => $"5a. {nameof(RunFailedState)}", + _ => stage.ToString(), + }); + + /// Shares one transition definition between execution and diagram export, omitting states unused by the selected mode. + private static StateMachine CreateMachine(EditorExecutionMode mode, Func? factory = null) + { + if (mode is not (EditorExecutionMode.Build or EditorExecutionMode.Run or EditorExecutionMode.Debug)) + throw new ArgumentOutOfRangeException(nameof(mode)); + + var machine = new StateMachine(containerFactory: factory) + .RegisterState(EditorExecutionStage.ValidateCompiler, EditorExecutionStage.Save, EditorExecutionStage.Failed) + .RegisterState(EditorExecutionStage.Save, EditorExecutionStage.ValidateSource, EditorExecutionStage.Failed, EditorExecutionStage.Canceled, parentStateId: null) + .RegisterState(EditorExecutionStage.ValidateSource, EditorExecutionStage.Build, EditorExecutionStage.Failed) + .RegisterState(EditorExecutionStage.Build, + mode == EditorExecutionMode.Build ? EditorExecutionStage.Completed : EditorExecutionStage.Launch, EditorExecutionStage.Failed) + .RegisterState(EditorExecutionStage.Completed) + .RegisterState(EditorExecutionStage.Canceled) + .RegisterState(EditorExecutionStage.Failed); + + if (mode != EditorExecutionMode.Build) + machine.RegisterState(EditorExecutionStage.Launch, EditorExecutionStage.Completed, + mode == EditorExecutionMode.Run ? EditorExecutionStage.RunFailed : EditorExecutionStage.Failed); + + if (mode == EditorExecutionMode.Run) + machine.RegisterState(EditorExecutionStage.RunFailed); + + return machine; + } + + public async Task ExecuteAsync(EditorExecutionRequest request, Action report) + { + if (Interlocked.CompareExchange(ref _executing, 1, 0) != 0) + throw new InvalidOperationException("An editor execution is already in progress."); + + try + { + var run = new ExecutionRun(request, compiler, runner, report, SynchronizationContext.Current); + + // Build state instances for each execution stage. + var states = new Dictionary> + { + [typeof(ValidateCompilerState)] = new ValidateCompilerState(run), + [typeof(SaveSourceState)] = new SaveSourceState(run), + [typeof(ValidateSourceState)] = new ValidateSourceState(run), + [typeof(CompileState)] = new CompileState(run), + [typeof(LaunchState)] = new LaunchState(run), + [typeof(CompletedState)] = new CompletedState(run), + [typeof(CanceledState)] = new CanceledState(run), + [typeof(FailedState)] = new FailedState(run), + [typeof(RunFailedState)] = new RunFailedState(run), + }; + + var machine = CreateMachine(request.Mode, type => states[type]); + + await machine.RunAsync(EditorExecutionStage.ValidateCompiler); + return run.Update; + } + finally + { + Volatile.Write(ref _executing, 0); + } + } + + /// 2a. Alternate terminal path: reports cancellation when the save step returns no source path, without compiling or launching. + private sealed class CanceledState(ExecutionRun run) : ExecutionState(run); + + /// 4. Invokes the compiler with the selected configuration and clean option, retaining diagnostics and checking success before launch. + private sealed class CompileState(ExecutionRun run) : ExecutionState(run); + + /// 6. Reports successful completion after launch, or directly after step 4 for a build-only request. + private sealed class CompletedState(ExecutionRun run) : ExecutionState(run); + + private sealed class ExecutionRun(EditorExecutionRequest request, ICompilerService compiler, IProgramRunner? runner, + Action report, SynchronizationContext? uiContext) + { + private readonly string _configuration = request.Mode == EditorExecutionMode.Debug ? BuildConstants.DebugConfiguration : request.Configuration; + private CompilerResult? _compilation; + private string? _sourcePath; + + public Exception? Error { get; set; } + public EditorExecutionUpdate Update { get; private set; } = new(EditorExecutionStage.ValidateCompiler); + + public Task InvokeAsync(Func> action) + { + // Lite.StateMachine uses ConfigureAwait(false); UI operations must retain the caller's context. + if (uiContext is null || ReferenceEquals(SynchronizationContext.Current, uiContext)) + return action(); + + var completed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + uiContext.Post(async _ => + { + try { completed.SetResult(await action()); } + catch (Exception ex) { completed.SetException(ex); } + }, null); + return completed.Task; + } + + public async Task StepAsync(EditorExecutionStage stage) + { + Notify(stage); + switch (stage) + { + case EditorExecutionStage.ValidateCompiler: + if (string.IsNullOrWhiteSpace(request.CompilerPath)) + throw new InvalidOperationException("Select the Zero CLI executable in Tools > Options > Compiler before building."); + + if (!BuildConstants.IsSupportedConfiguration(_configuration)) + throw new ArgumentException("Choose Debug or Release."); + + break; + + case EditorExecutionStage.Save: + _sourcePath = await request.SaveSourceAsync(); + if (_sourcePath is null) return Result.Failure; + break; + + case EditorExecutionStage.ValidateSource: + if (!Path.IsPathFullyQualified(_sourcePath!)) + throw new InvalidOperationException($"Building requires a local {SourceFileExtensions.Assembly} file."); + + if (!string.Equals(Path.GetExtension(_sourcePath), SourceFileExtensions.Assembly, StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException($"Only {SourceFileExtensions.Assembly} source files can be built."); + + break; + + case EditorExecutionStage.Build: + _compilation = await compiler.BuildAsync(request.CompilerPath, _sourcePath!, _configuration, request.CleanFirst); + if (!_compilation.Succeeded) + return Result.Error; + + Notify(EditorExecutionStage.Built); + break; + + case EditorExecutionStage.Launch: + if (request.Mode == EditorExecutionMode.Debug) + await (request.StartDebuggerAsync ?? throw new InvalidOperationException("The debugger is unavailable."))(_compilation!.OutputPath, _sourcePath!); + else + (runner ?? throw new InvalidOperationException("The program runner is unavailable.")).Run(_compilation!.OutputPath, Path.GetDirectoryName(_sourcePath)!); + break; + } + + return Result.Success; + } + + private void Notify(EditorExecutionStage stage) + { + Update = new EditorExecutionUpdate(stage, _compilation, Error); + report(Update); + } + } + + /// Shared base for steps 1–6 and alternate exits; runs state actions on the caller's UI context and routes exceptions to error transitions. + private abstract class ExecutionState(ExecutionRun run) : IState + { + public async Task OnEnter(Context context) + { + try + { + context.NextState(await run.InvokeAsync(() => run.StepAsync(context.CurrentStateId))); + } + catch (Exception ex) + { + run.Error = ex; + context.NextState(Result.Error); + } + } + + public Task OnEntering(Context context) => Task.CompletedTask; + + public Task OnExit(Context context) => Task.CompletedTask; + } + + /// 1–5, alternate terminal path. Reports validation, save, compilation, or debugger-startup failure instead of continuing to subsequent steps. + private sealed class FailedState(ExecutionRun run) : ExecutionState(run); + + /// 5. After successful compilation, launches the executable normally or starts a debug session; skipped for build-only requests. + private sealed class LaunchState(ExecutionRun run) : ExecutionState(run); + + /// 5a. Alternate terminal path: reports a normal program-launch failure while preserving successful compiler output. + private sealed class RunFailedState(ExecutionRun run) : ExecutionState(run); + + /// 2. Runs the source-saving callback and captures its resulting path; cancellation branches to step 2a. + private sealed class SaveSourceState(ExecutionRun run) : ExecutionState(run); + + /// 1. Checks that a compiler is configured and that the effective Debug or Release configuration is supported before requesting a save. + private sealed class ValidateCompilerState(ExecutionRun run) : ExecutionState(run); + + /// 3. Verifies that the saved source path is fully qualified and has the supported ZASM extension before compilation. + private sealed class ValidateSourceState(ExecutionRun run) : ExecutionState(run); +} diff --git a/source/Zero.Ide/ViewModels/MainWindowViewModel.cs b/source/Zero.Ide/ViewModels/MainWindowViewModel.cs index 271ad62..05b99d7 100644 --- a/source/Zero.Ide/ViewModels/MainWindowViewModel.cs +++ b/source/Zero.Ide/ViewModels/MainWindowViewModel.cs @@ -22,6 +22,7 @@ public partial class MainWindowViewModel : ViewModelBase private readonly ICompilerService? _compilerService; private readonly IEditorDialogService _dialogs; private readonly EditorViewModel _emptyEditor = new(); + private readonly EditorExecutionCoordinator? _executionCoordinator; private readonly IProgramRunner? _programRunner; private readonly ISettingsService? _settings; private readonly IUpdateService? _updates; @@ -37,11 +38,12 @@ public partial class MainWindowViewModel : ViewModelBase public MainWindowViewModel(EditorViewModel editor, IEditorDialogService dialogs, ISettingsService? settings = null, ICompilerService? compilerService = null, IProgramRunner? programRunner = null, IUpdateService? updates = null, - IDebugSession? debugSession = null) + IDebugSession? debugSession = null, EditorExecutionCoordinator? executionCoordinator = null) { _dialogs = dialogs; _settings = settings; _compilerService = compilerService; + _executionCoordinator = executionCoordinator ?? (compilerService is null ? null : new EditorExecutionCoordinator(compilerService, programRunner)); _programRunner = programRunner; _updates = updates; settings?.SettingsChanged += (_, _) => NotifyThemeChanged(); @@ -316,58 +318,64 @@ private async Task BuildAsync(bool cleanFirst, bool runAfterBuild = false, bool return; var editor = document.Editor; - - if (string.IsNullOrWhiteSpace(editor.Settings.CompilerPath)) - throw new InvalidOperationException("Select the Zero CLI executable in Tools > Options > Compiler before building."); - - if ((document.File is null || editor.IsModified) && - !await SaveAsync(document, false)) - return; - - var sourcePath = document.File?.TryGetLocalPath() ?? throw new InvalidOperationException($"Building requires a local {SourceFileExtensions.Assembly} file."); - - if (!string.Equals(Path.GetExtension(sourcePath), SourceFileExtensions.Assembly, StringComparison.OrdinalIgnoreCase)) - throw new InvalidOperationException($"Only {SourceFileExtensions.Assembly} source files can be built."); - - BuildState = EditorBuildState.Building; var configuration = debugAfterBuild ? BuildConstants.DebugConfiguration : BuildConfiguration; - Status = $"Building {editor.FileName} ({configuration})"; - BuildOutput = Status; - - var result = await _compilerService!.BuildAsync(editor.Settings.CompilerPath, sourcePath, configuration, cleanFirst); + var mode = debugAfterBuild ? EditorExecutionMode.Debug : runAfterBuild ? EditorExecutionMode.Run : EditorExecutionMode.Build; + + var request = new EditorExecutionRequest( + editor.Settings.CompilerPath, + configuration, + cleanFirst, + mode, + SaveSourceAsync: async () => + { + if ((document.File is null || editor.IsModified) && !await SaveAsync(document, false)) + return null; - BuildOutput = result.Output + Environment.NewLine + $"Compiler exit code: {result.ExitCode}"; + return document.File?.TryGetLocalPath() + ?? throw new InvalidOperationException($"Building requires a local {SourceFileExtensions.Assembly} file."); + }, StartDebuggerAsync: LaunchDebuggerAsync); - if (!result.Succeeded) + var outcome = await _executionCoordinator!.ExecuteAsync(request, update => { - BuildState = EditorBuildState.Failed; - Status = "Build failed"; - await _dialogs.ShowMessageAsync("Build failure", BuildOutput); - return; - } - - BuildState = EditorBuildState.Idle; - Status = $"Build succeeded: {result.OutputPath}"; - - if (debugAfterBuild) - await LaunchDebuggerAsync(result.OutputPath, sourcePath); + if (update.Stage == EditorExecutionStage.Build) + { + BuildState = EditorBuildState.Building; + BuildOutput = Status = $"Building {editor.FileName} ({configuration})"; + } + else if (update.Stage == EditorExecutionStage.Built) + { + BuildState = EditorBuildState.Idle; + BuildOutput = update.Compilation!.Output + Environment.NewLine + $"Compiler exit code: {update.Compilation.ExitCode}"; + Status = $"Build succeeded: {update.Compilation.OutputPath}"; + } + else if (update.Stage == EditorExecutionStage.Completed && mode == EditorExecutionMode.Run) + { + Status = $"Started {update.Compilation!.OutputPath}"; + BuildOutput += Environment.NewLine + Status; + } + }); - if (runAfterBuild) + if (outcome.Stage == EditorExecutionStage.Failed) { - try + if (outcome.Error is { } error) { - _programRunner!.Run(result.OutputPath, Path.GetDirectoryName(sourcePath)!); - Status = $"Started {result.OutputPath}"; - BuildOutput += Environment.NewLine + Status; + await ReportBuildFailureAsync(error); } - catch (Exception ex) + else { - BuildState = EditorBuildState.RunFailed; - Status = "Run failed"; - BuildOutput += Environment.NewLine + ex.Message; - await _dialogs.ShowMessageAsync("Run failure", ex.Message); + BuildState = EditorBuildState.Failed; + Status = "Build failed"; + BuildOutput = outcome.Compilation!.Output + Environment.NewLine + $"Compiler exit code: {outcome.Compilation.ExitCode}"; + await _dialogs.ShowMessageAsync("Build failure", BuildOutput); } } + else if (outcome.Stage == EditorExecutionStage.RunFailed) + { + BuildState = EditorBuildState.RunFailed; + Status = "Run failed"; + BuildOutput += Environment.NewLine + outcome.Error!.Message; + await _dialogs.ShowMessageAsync("Run failure", outcome.Error.Message); + } } catch (Exception ex) {