Skip to content

Commit

Permalink
Improve readability in the program code with C# 12
Browse files Browse the repository at this point in the history
Use some features of C# 12 to clean up program code and improve readability:

+ Use aliases for common instances of generic types to reduce visual clutter.
+ Use the new 'collection literals' feature to simplify the coding of sequences.
  • Loading branch information
Viir committed Sep 12, 2023
1 parent aaeabd3 commit 75f9af9
Show file tree
Hide file tree
Showing 58 changed files with 285 additions and 307 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/build-native-tools.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:
- environment: ubuntu-22.04
publish-runtime-id: linux-x64
- environment: windows-2022
publish-runtime-id: win10-x64
publish-runtime-id: win-x64
- environment: macos-13
publish-runtime-id: osx-x64

Expand All @@ -32,7 +32,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-dotnet@v3
with:
dotnet-version: '7.0.400'
dotnet-version: '8.0.100-rc.1.23455.8'

- name: Try use dotnet
run: dotnet --info
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/publish-to-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
- environment: ubuntu-22.04
publish-runtime-id: linux-x64
- environment: windows-2022
publish-runtime-id: win10-x64
publish-runtime-id: win-x64
- environment: macos-12
publish-runtime-id: osx-x64

Expand All @@ -33,7 +33,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-dotnet@v3
with:
dotnet-version: '7.0.400'
dotnet-version: '8.0.100-rc.1.23455.8'

- name: Try use dotnet
run: dotnet --info
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/test-and-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
- environment: ubuntu-22.04
publish-runtime-id: linux-x64
- environment: windows-2022
publish-runtime-id: win10-x64
publish-runtime-id: win-x64
- environment: macos-13
publish-runtime-id: osx-x64

Expand All @@ -27,7 +27,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-dotnet@v3
with:
dotnet-version: '7.0.400'
dotnet-version: '8.0.100-rc.1.23455.8'

- name: Try use dotnet
run: dotnet --info
Expand Down
2 changes: 1 addition & 1 deletion azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ steps:
- task: UseDotNet@2
inputs:
packageType: 'sdk' # Options: runtime, sdk
version: '7.0.400'
version: '8.0.100-rc.1.23455.8'
includePreviewVersions: true

- script: dotnet --version
Expand Down
4 changes: 2 additions & 2 deletions implement/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Build dotnet build image
FROM mcr.microsoft.com/dotnet/sdk:7.0.400 AS build-env
FROM mcr.microsoft.com/dotnet/sdk:8.0.100-rc.1 AS build-env
WORKDIR /app

# Copy everything and build
Expand All @@ -8,7 +8,7 @@ WORKDIR /app/elm-time
RUN dotnet publish -c Debug -o out

# Build runtime image
FROM mcr.microsoft.com/dotnet/aspnet:7.0.10 AS binaries
FROM mcr.microsoft.com/dotnet/aspnet:8.0.0-rc.1 AS binaries

COPY --from=build-env /app/elm-time/out /elm-time/dotnet/

Expand Down
4 changes: 2 additions & 2 deletions implement/elm-time/Elm019/Elm019Binaries.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public record ElmMakeOk(ReadOnlyMemory<byte> producedFile);
public static Result<string, ElmMakeOk> ElmMakeToJavascript(
IImmutableDictionary<IReadOnlyList<string>, ReadOnlyMemory<byte>> elmCodeFiles,
IReadOnlyList<string>? workingDirectoryRelative,
IImmutableList<string> pathToFileWithElmEntryPoint,
IReadOnlyList<string> pathToFileWithElmEntryPoint,
string? elmMakeCommandAppendix = null) =>
ElmMake(
elmCodeFiles,
Expand Down Expand Up @@ -212,7 +212,7 @@ An alternative would be retrying when this error is parsed from `commandResults.
.ToImmutableList();

var outputFileExpectedPath =
(workingDirectoryRelative ?? ImmutableList<string>.Empty).ToImmutableList().Add(outputFileName);
(workingDirectoryRelative ?? []).ToImmutableList().Add(outputFileName);

var outputFiles =
newFiles
Expand Down
9 changes: 4 additions & 5 deletions implement/elm-time/Elm019/ElmJsonStructure.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text.Json.Serialization;

Expand All @@ -15,7 +14,7 @@ public record ElmJsonStructure(

public static RelativeDirectory ParseSourceDirectory(string sourceDirectory)
{
var initialRecord = new RelativeDirectory(ParentLevel: 0, Subdirectories: ImmutableList<string>.Empty);
var initialRecord = new RelativeDirectory(ParentLevel: 0, Subdirectories: []);

if (sourceDirectory == ".")
return initialRecord;
Expand All @@ -37,7 +36,7 @@ public static RelativeDirectory ParseSourceDirectory(string sourceDirectory)
0 < aggregate.Subdirectories.Count ?
aggregate with
{
Subdirectories = aggregate.Subdirectories.RemoveAt(aggregate.Subdirectories.Count - 1)
Subdirectories = [.. aggregate.Subdirectories.SkipLast(1)]
}
:
aggregate with
Expand All @@ -47,13 +46,13 @@ aggregate with
_ =>
aggregate with
{
Subdirectories = aggregate.Subdirectories.Add(nextSegment)
Subdirectories = [.. aggregate.Subdirectories, nextSegment]
}
});
}

public record RelativeDirectory(
int ParentLevel,
IImmutableList<string> Subdirectories);
IReadOnlyList<string> Subdirectories);
}

18 changes: 9 additions & 9 deletions implement/elm-time/ElmInteractive/ElmInteractive.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ public static Result<string, EvaluatedSctructure> EvaluateSubmissionAndGetResult
var argumentsJson = System.Text.Json.JsonSerializer.Serialize(
new
{
modulesTexts = modulesTexts ?? ImmutableList<string>.Empty,
modulesTexts = modulesTexts ?? [],
submission = submission,
previousLocalSubmissions = previousLocalSubmissions ?? ImmutableList<string>.Empty,
previousLocalSubmissions = previousLocalSubmissions ?? [],
}
);

Expand Down Expand Up @@ -65,7 +65,7 @@ public static IReadOnlyList<string> GetDefaultElmCoreModulesTexts(
{
var allModulesTexts =
GetDefaultElmCoreModulesTexts(evalElmPreparedJavaScriptEngine)
.Concat(ModulesTextsFromAppCodeTree(appCodeTree).EmptyIfNull())
.Concat(ModulesTextsFromAppCodeTree(appCodeTree) ?? [])
.ToImmutableList();

return
Expand Down Expand Up @@ -117,7 +117,7 @@ closestBase is not null
(closestBase, compilationCacheBefore))
:
CompileInteractiveEnvironmentForModules(
elmModulesTexts: ImmutableList<string>.Empty,
elmModulesTexts: [],
evalElmPreparedJavaScriptEngine: evalElmPreparedJavaScriptEngine,
parentEnvironment: null,
compilationCacheBefore: compilationCacheBefore);
Expand All @@ -133,7 +133,7 @@ closestBase is not null
{
var resultBeforeCache =
CompileInteractiveEnvironmentForModules(
elmModulesTexts: ImmutableList.Create(elmCoreModuleText),
elmModulesTexts: [elmCoreModuleText],
evalElmPreparedJavaScriptEngine: evalElmPreparedJavaScriptEngine,
parentEnvironment: prev.compileResult,
compilationCacheBefore: prev.compilationCache);
Expand Down Expand Up @@ -229,7 +229,7 @@ private ReadOnlyMemory<byte> ComputeHash()
if (parent is null)
return selfHash;

return PineValueHashTree.ComputeHash(PineValue.List(new[] { PineValue.Blob(selfHash), PineValue.Blob(parent.Hash) }));
return PineValueHashTree.ComputeHash(PineValue.List([PineValue.Blob(selfHash), PineValue.Blob(parent.Hash)]));
}

public virtual bool Equals(CompileInteractiveEnvironmentResult? other)
Expand Down Expand Up @@ -596,7 +596,7 @@ private static PineValue ParsePineValueFromJson(PineValueJson fromJson, IReadOnl

var compilationResult = ElmAppCompilation.AsCompletelyLoweredElmApp(
sourceFiles: TreeToFlatDictionaryWithPathComparer(sourceTree),
workingDirectoryRelative: ImmutableList<string>.Empty,
workingDirectoryRelative: [],
ElmAppInterfaceConfig.Default with { compilationRootFilePath = compilationRootFilePath });

return
Expand Down Expand Up @@ -641,7 +641,7 @@ public static string PrepareJavaScriptToEvaluateElm()
compileElmProgramCodeFiles
.Extract(error => throw new NotImplementedException(nameof(LoadCompileElmProgramCodeFiles) + ": " + error)),
workingDirectoryRelative: null,
ImmutableList.Create("src", "ElmInteractiveMain.elm"));
["src", "ElmInteractiveMain.elm"]);

var javascriptFromElmMake =
Encoding.UTF8.GetString(
Expand Down Expand Up @@ -681,7 +681,7 @@ public static string PrepareJavaScriptToEvaluateElm()

public static Result<string, IImmutableDictionary<IReadOnlyList<string>, ReadOnlyMemory<byte>>> LoadCompileElmProgramCodeFiles() =>
DotNetAssembly.LoadDirectoryFilesFromManifestEmbeddedFileProviderAsDictionary(
directoryPath: ImmutableList.Create("ElmTime", "compile-elm-program"),
directoryPath: ["ElmTime", "compile-elm-program"],
assembly: typeof(ElmInteractive).Assembly);

private record EvaluateSubmissionResponseStructure
Expand Down
12 changes: 6 additions & 6 deletions implement/elm-time/ElmInteractive/TestElmInteractive.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,10 @@ public static ImmutableDictionary<string, InteractiveScenarioTestReport> TestElm
console.WriteLine(
string.Join(
" - ",
(failedSteps.Any() ? "Failed" : "Passed") + "!",
(!failedSteps.IsEmpty ? "Failed" : "Passed") + "!",
string.Join(", ", overallStats.Select(stat => stat.label + ": " + stat.value)),
scenariosTreeCompositionHash[..10] + " (elm-time " + Program.AppVersionId + ")"),
color: failedSteps.Any() ? IConsole.TextColor.Red : IConsole.TextColor.Green);
color: !failedSteps.IsEmpty ? IConsole.TextColor.Red : IConsole.TextColor.Green);

var failedScenarios =
failedSteps
Expand Down Expand Up @@ -206,10 +206,10 @@ Result<InteractiveScenarioTestStepFailure, object> getResult()
public static Result<string, Scenario> ParseScenario(TreeNodeWithStringPath scenarioTree)
{
var appCodeTree =
scenarioTree.GetNodeAtPath(new[] { "context-app" });
scenarioTree.GetNodeAtPath(["context-app"]);

var stepsDirectory =
scenarioTree.GetNodeAtPath(new[] { "steps" });
scenarioTree.GetNodeAtPath(["steps"]);

var testScenarioSteps =
stepsDirectory switch
Expand Down Expand Up @@ -251,14 +251,14 @@ public static Result<string, Scenario> ParseScenario(TreeNodeWithStringPath scen
public static Result<string, ScenarioStep> ParseScenarioStep(TreeNodeWithStringPath sessionStep)
{
var expectedResponse =
sessionStep.GetNodeAtPath(new[] { "expected-value.txt" }) is TreeNodeWithStringPath.BlobNode expectedValueBlob
sessionStep.GetNodeAtPath(["expected-value.txt"]) is TreeNodeWithStringPath.BlobNode expectedValueBlob
?
Encoding.UTF8.GetString(expectedValueBlob.Bytes.Span)
:
null;

return
(sessionStep.GetNodeAtPath(new[] { "submission.txt" }) switch
(sessionStep.GetNodeAtPath(["submission.txt"]) switch
{
TreeNodeWithStringPath.BlobNode submissionBlob => Result<string, string>.ok(Encoding.UTF8.GetString(submissionBlob.Bytes.Span)),
_ => Result<string, string>.err("Missing submission"),
Expand Down
2 changes: 1 addition & 1 deletion implement/elm-time/ElmSyntax/ElmModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public static IReadOnlyList<string> ModulesTextOrderedForCompilationByDependenci
IEnumerable<IReadOnlyList<string>> EnumerateImportsOfModuleTransitive(IReadOnlyList<string> moduleName) =>
!parsedModulesByName.ContainsKey(moduleName)
?
ImmutableList<IReadOnlyList<string>>.Empty
[]
:
parsedModulesByName[moduleName].importedModulesNames
.SelectMany(
Expand Down
29 changes: 14 additions & 15 deletions implement/elm-time/ElmTestRs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ public static (ExecutableFile.ProcessOutput processOutput, IReadOnlyList<(string

var environmentFilesExecutable =
ImmutableDictionary.Create<IReadOnlyList<string>, ReadOnlyMemory<byte>>()
.SetItem(ImmutableList.Create(elmExecutableFileName), Elm019Binaries.GetElmExecutableFile);
.SetItem([elmExecutableFileName], Elm019Binaries.GetElmExecutableFile);

var executeElmTestResult =
ExecutableFile.ExecuteFileWithArguments(
Expand Down Expand Up @@ -169,12 +169,12 @@ public static (IReadOnlyList<(string text, ElmTestRsConsoleOutputColor color)> t
if (@event.@event == "runStart")
{
return
(ImmutableList.Create(
([
(string.Join("\n",
"Running " + @event.testCount + " tests. To reproduce these results later,"
, "run elm-test-rs with --seed " + @event.initialSeed + " and --fuzz " + @event.fuzzRuns),
ElmTestRsConsoleOutputColor.DefaultColor)
),
],
overallSuccess: null);
}

Expand All @@ -189,59 +189,58 @@ public static (IReadOnlyList<(string text, ElmTestRsConsoleOutputColor color)> t
("\nTEST RUN FAILED\n\n", ElmTestRsConsoleOutputColor.RedColor);

return
(ImmutableList.Create(
([
overallSuccessText,
(string.Join("\n",
"Duration: " + string.Format("{0:#,##0}", @event.duration) + " ms",
"Passed: " + @event.passed,
"Failed: " + @event.failed),
ElmTestRsConsoleOutputColor.DefaultColor)),
ElmTestRsConsoleOutputColor.DefaultColor)],
overallSuccess);
}

if (@event.@event == "testsCompleted" && @event.status != "pass")
{
var textsFromLabels =
@event.labels.EmptyIfNull().SkipLast(1).Select(label => ("\n↓ " + label, ElmTestRsConsoleOutputColor.DefaultColor))
.Concat(@event.labels.EmptyIfNull().TakeLast(1).Select(label => ("\n✗ " + label, ElmTestRsConsoleOutputColor.RedColor)))
(@event.labels ?? []).SkipLast(1).Select(label => ("\n↓ " + label, ElmTestRsConsoleOutputColor.DefaultColor))
.Concat((@event.labels ?? []).TakeLast(1).Select(label => ("\n✗ " + label, ElmTestRsConsoleOutputColor.RedColor)))
.ToImmutableList();

static IReadOnlyList<string> renderFailureReasonData(ElmTestRsReportJsonEntryFailureReasonData failureReasonData)
{
if (failureReasonData.Equality != null)
{
return ImmutableList.Create(
return [
"",
failureReasonData.Equality.actual,
"╷",
"│ " + failureReasonData.Equality.comparison,
"╵",
failureReasonData.Equality.expected,
""
);
];
}

if (failureReasonData.String != null)
return ImmutableList.Create("", failureReasonData.String, "");
return ["", failureReasonData.String, ""];

throw new Exception("Incomplete match on sum type.");
}

var textsFromFailures =
@event.failures.EmptyIfNull()
(@event.failures ?? [])
.Select(failure => failure.reason?.data)
.WhereNotNull()
.SelectMany(renderFailureReasonData)
.ToImmutableList();

return
(textsFromLabels.Concat(
textsFromFailures
.Select(textFromFailure => ("\n " + textFromFailure, ElmTestRsConsoleOutputColor.DefaultColor))).ToImmutableList(),
([.. textsFromLabels
, .. textsFromFailures.Select(textFromFailure => ("\n " + textFromFailure, ElmTestRsConsoleOutputColor.DefaultColor))],
null);
}

return (ImmutableList<(string text, ElmTestRsConsoleOutputColor color)>.Empty, null);
return ([], null);
}
}

Expand Down
Loading

0 comments on commit 75f9af9

Please sign in to comment.