Skip to content

Commit

Permalink
Refactor interpreter configuration APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergio0694 committed Sep 14, 2024
1 parent d24f976 commit b42ead3
Show file tree
Hide file tree
Showing 18 changed files with 285 additions and 892 deletions.
17 changes: 9 additions & 8 deletions profiling/Brainf_ckSharp.Profiler/Brainf_ckBenchmark.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Engines;
using BenchmarkDotNet.Jobs;
using Brainf_ckSharp.Configurations;
using Brainf_ckSharp.Models;
using Brainf_ckSharp.Models.Base;
using Brainf_ckSharp.Unit.Shared;
Expand Down Expand Up @@ -54,14 +55,14 @@ private void TriggerTier1Jit()
[Benchmark]
public string RunScript()
{
Option<InterpreterResult> result = Brainf_ckInterpreter
.CreateReleaseConfiguration()
.WithSource(this.script!.Source)
.WithStdin(this.script.Stdin)
.WithMemorySize(this.script.MemorySize)
.WithDataType(this.script.DataType)
.WithExecutionOptions(this.script.ExecutionOptions)
.TryRun();
Option<InterpreterResult> result = Brainf_ckInterpreter.TryRun(new ReleaseConfiguration
{
Source = this.script!.Source.AsMemory(),
Stdin = this.script.Stdin.AsMemory(),
MemorySize = this.script.MemorySize,
DataType = this.script.DataType,
ExecutionOptions = this.script.ExecutionOptions
});

result.Value!.MachineState.Dispose();

Expand Down
25 changes: 13 additions & 12 deletions src/Brainf_ckSharp.Shared/ViewModels/Controls/StatusBarViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Threading;
using Brainf_ckSharp.Configurations;
using Brainf_ckSharp.Enums;
using Brainf_ckSharp.Memory.Interfaces;
using Brainf_ckSharp.Models;
Expand Down Expand Up @@ -45,7 +46,7 @@ public sealed partial class StatusBarViewModel : ObservableRecipient
/// <summary>
/// The last stdin that was used
/// </summary>
private string stdin = string.Empty;
private ReadOnlyMemory<char> stdin;

/// <summary>
/// The last memory size setting that was used
Expand Down Expand Up @@ -140,14 +141,14 @@ private void RunBackgroundCode()
// Before actually executing the code, also check with the previously
// stored arguments to be able to skip the execution if there were no changes.
ReadOnlyMemory<char> source = viewModel.Text;
string stdin = Messenger.Send(new StdinRequestMessage(true));
ReadOnlyMemory<char> stdin = Messenger.Send(new StdinRequestMessage(true)).Response.AsMemory();
int memorySize = this.settingsService.GetValue<int>(SettingsKeys.MemorySize);
DataType dataType = this.settingsService.GetValue<DataType>(SettingsKeys.DataType);
ExecutionOptions executionOptions = this.settingsService.GetValue<ExecutionOptions>(SettingsKeys.ExecutionOptions);
IReadOnlyMachineState? machineState = (viewModel as ConsoleViewModel)?.MachineState;

if (source.Span.SequenceEqual(this.source.Span) &&
stdin.Equals(this.stdin) &&
stdin.Span.SequenceEqual(this.stdin.Span) &&
memorySize == this.memorySize &&
dataType == this.dataType &&
executionOptions == this.executionOptions &&
Expand All @@ -166,15 +167,15 @@ private void RunBackgroundCode()

CancellationTokenSource tokenSource = new(TimeSpan.FromSeconds(2));

Option<InterpreterResult> result = Brainf_ckInterpreter
.CreateReleaseConfiguration()
.WithSource(WorkspaceViewModel.Text)
.WithStdin(stdin)
.WithMemorySize(memorySize)
.WithDataType(dataType)
.WithExecutionOptions(executionOptions)
.WithExecutionToken(tokenSource.Token)
.TryRun();
Option<InterpreterResult> result = Brainf_ckInterpreter.TryRun(new ReleaseConfiguration
{
Source = WorkspaceViewModel.Text,
Stdin = stdin,
MemorySize = memorySize,
DataType = dataType,
ExecutionOptions = executionOptions,
ExecutionToken = tokenSource.Token
});

// Update the property from the original synchronization context
this.context.Post(_ => BackgroundExecutionResult = result, null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Buffers;
using System.Threading;
using System.Threading.Tasks;
using Brainf_ckSharp.Configurations;
using Brainf_ckSharp.Enums;
using Brainf_ckSharp.Models;
using Brainf_ckSharp.Services;
Expand Down Expand Up @@ -117,16 +118,15 @@ private async Task LoadDataAsync()
{
InterpreterResult result = await Task.Run(() =>
{
return Brainf_ckInterpreter
.CreateReleaseConfiguration()
.WithSource(Script!)
.WithStdin(stdin)
.WithMemorySize(memorySize)
.WithDataType(dataType)
.WithExecutionOptions(executionOptions)
.WithExecutionToken(this.executionTokenSource.Token)
.TryRun()
.Value!;
return Brainf_ckInterpreter.TryRun(new ReleaseConfiguration
{
Source = Script.AsMemory(),
Stdin = stdin.AsMemory(),
MemorySize = memorySize,
DataType = dataType,
ExecutionOptions = executionOptions,
ExecutionToken = this.executionTokenSource.Token
}).Value!;
});

LoadResults(result);
Expand All @@ -138,18 +138,17 @@ private async Task LoadDataAsync()
// Run in DEBUG mode
this.debugSession = await Task.Run(() =>
{
InterpreterSession session = Brainf_ckInterpreter
.CreateDebugConfiguration()
.WithSource(Script!)
.WithStdin(stdin)
.WithBreakpoints(Breakpoints.Memory)
.WithMemorySize(memorySize)
.WithDataType(dataType)
.WithExecutionOptions(executionOptions)
.WithExecutionToken(this.executionTokenSource.Token)
.WithDebugToken(this.debugTokenSource.Token)
.TryRun()
.Value!;
InterpreterSession session = Brainf_ckInterpreter.TryRun(new DebugConfiguration
{
Source = Script.AsMemory(),
Stdin = stdin.AsMemory(),
Breakpoints = Breakpoints.Memory,
MemorySize = memorySize,
DataType = dataType,
ExecutionOptions = executionOptions,
ExecutionToken = this.executionTokenSource.Token,
DebugToken = this.debugTokenSource.Token
}).Value!;

_ = session.MoveNext();

Expand Down
17 changes: 9 additions & 8 deletions src/Brainf_ckSharp.Shared/ViewModels/Views/ConsoleViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Brainf_ckSharp.Configurations;
using Brainf_ckSharp.Enums;
using Brainf_ckSharp.Memory.Interfaces;
using Brainf_ckSharp.Memory.Tools;
Expand Down Expand Up @@ -265,14 +266,14 @@ private async Task ExecuteCommandAsync(string command)

Option<InterpreterResult> result = await Task.Run(() =>
{
return Brainf_ckInterpreter
.CreateReleaseConfiguration()
.WithSource(command)
.WithStdin(stdin)
.WithInitialState(MachineState)
.WithExecutionOptions(executionOptions)
.WithExecutionToken(new CancellationTokenSource(TimeSpan.FromSeconds(2)).Token)
.TryRun();
return Brainf_ckInterpreter.TryRun(new ReleaseConfiguration
{
Source = command.AsMemory(),
Stdin = stdin.AsMemory(),
InitialState = MachineState,
ExecutionOptions = executionOptions,
ExecutionToken = new CancellationTokenSource(TimeSpan.FromSeconds(2)).Token
});
});

if (!result.ValidationResult.IsSuccess)
Expand Down
84 changes: 74 additions & 10 deletions src/Brainf_ckSharp/Brainf_ckInterpreter.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
using System.Runtime.CompilerServices;
using Brainf_ckSharp.Configurations;
using Brainf_ckSharp.Constants;
using Brainf_ckSharp.Memory;
using Brainf_ckSharp.Models.Base;
using Brainf_ckSharp.Models;
using CommunityToolkit.Diagnostics;
using Brainf_ckSharp.Opcodes;
using CommunityToolkit.HighPerformance.Buffers;

namespace Brainf_ckSharp;

Expand All @@ -9,22 +16,79 @@ namespace Brainf_ckSharp;
public static partial class Brainf_ckInterpreter
{
/// <summary>
/// Creates a new <see cref="DebugConfiguration"/> instance to prepare a script execution in DEBUG mode
/// Runs the current Brainf*ck/PBrain configuration
/// </summary>
/// <returns>A <see cref="DebugConfiguration"/> instance to prepare a script execution</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DebugConfiguration CreateDebugConfiguration()
/// <param name="configuration">The configuration to run</param>
/// <returns>An <see cref="Option{T}"/> of <see cref="InterpreterResult"/> instance with the results of the execution</returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public static Option<InterpreterSession> TryRun(in DebugConfiguration configuration)
{
return default;
if (configuration.InitialState is TuringMachineState initialState)
{
Guard.IsNull(configuration.MemorySize);
Guard.IsNull(configuration.DataType);

initialState = (TuringMachineState)initialState.Clone();
}
else
{
int size = configuration.MemorySize ?? Specs.DefaultMemorySize;

Guard.IsBetweenOrEqualTo(size, Specs.MinimumMemorySize, Specs.MaximumMemorySize, nameof(configuration.MemorySize));

initialState = new TuringMachineState(size, configuration.DataType ?? Specs.DefaultDataType);
}

return Debug.TryCreateSession(
configuration.Source.Span,
configuration.Breakpoints.Span,
configuration.Stdin,
initialState,
configuration.ExecutionOptions,
configuration.ExecutionToken,
configuration.DebugToken);
}

/// <summary>
/// Creates a new <see cref="ReleaseConfiguration"/> instance to prepare a script execution in RELEASE mode
/// Runs the current Brainf*ck/PBrain configuration
/// </summary>
/// <returns>A <see cref="ReleaseConfiguration"/> instance to prepare a script execution</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReleaseConfiguration CreateReleaseConfiguration()
/// <param name="configuration">The configuration to run</param>
/// <returns>An <see cref="Option{T}"/> of <see cref="InterpreterResult"/> instance with the results of the execution</returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public static Option<InterpreterResult> TryRun(in ReleaseConfiguration configuration)
{
return default;
using MemoryOwner<Brainf_ckOperation>? operations = Brainf_ckParser.TryParse<Brainf_ckOperation>(
configuration.Source.Span,
out SyntaxValidationResult validationResult);

if (!validationResult.IsSuccess)
{
return Option<InterpreterResult>.From(validationResult);
}

if (configuration.InitialState is TuringMachineState initialState)
{
Guard.IsNull(configuration.MemorySize);
Guard.IsNull(configuration.DataType);

initialState = (TuringMachineState)initialState.Clone();
}
else
{
int size = configuration.MemorySize ?? Specs.DefaultMemorySize;

Guard.IsBetweenOrEqualTo(size, Specs.MinimumMemorySize, Specs.MaximumMemorySize, nameof(configuration.MemorySize));

initialState = new TuringMachineState(size, configuration.DataType ?? Specs.DefaultDataType);
}

InterpreterResult result = Release.Run(
operations!.Span,
configuration.Stdin.Span,
initialState,
configuration.ExecutionOptions,
configuration.ExecutionToken);

return Option<InterpreterResult>.From(validationResult, result);
}
}
29 changes: 1 addition & 28 deletions src/Brainf_ckSharp/Brainf_ckSharp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,34 +9,7 @@
<ItemGroup>
<PackageReference Include="CommunityToolkit.Diagnostics" Version="8.3.1" />
<PackageReference Include="CommunityToolkit.HighPerformance" Version="8.3.1" />
</ItemGroup>

<ItemGroup>
<None Update="Configurations\Extensions\ConfigurationExtensions.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>ConfigurationExtensions.cs</LastGenOutput>
</None>
<None Update="Configurations\Configuration.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>Configuration.cs</LastGenOutput>
</None>
</ItemGroup>

<ItemGroup>
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup>

<ItemGroup>
<Compile Update="Configurations\Extensions\ConfigurationExtensions.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>ConfigurationExtensions.tt</DependentUpon>
</Compile>
<Compile Update="Configurations\Configuration.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Configuration.tt</DependentUpon>
</Compile>
<PackageReference Include="PolySharp" Version="1.14.1" PrivateAssets="all" />
</ItemGroup>

</Project>
61 changes: 0 additions & 61 deletions src/Brainf_ckSharp/Configurations/Configuration.Debug.cs

This file was deleted.

Loading

0 comments on commit b42ead3

Please sign in to comment.