From 570f288bbf99ac6f2562a8468f97651cd458935e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 10:47:54 +0200 Subject: [PATCH 01/53] Update Lombiq.Analyzers submodule. --- tools/Lombiq.Analyzers | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/Lombiq.Analyzers b/tools/Lombiq.Analyzers index bafe4fa0..67d6bce3 160000 --- a/tools/Lombiq.Analyzers +++ b/tools/Lombiq.Analyzers @@ -1 +1 @@ -Subproject commit bafe4fa0ded9e52d2fc43c5ea1b96d83085e3876 +Subproject commit 67d6bce3a0cc6f21211013f9622376e926d5cfb2 From b5ea05245259f1c99f307da553daf70fe58aae3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 11:00:43 +0200 Subject: [PATCH 02/53] Use StringHelper.CreateInvariant(). --- src/Hastlayer/Hast.Catapult/CatapultLibrary.cs | 10 +++++----- .../Hast.Synthesis/Services/BuildLogger.cs | 6 +++--- .../ArchitectureComponentNameExtensions.cs | 3 ++- .../ArchitectureComponentNameHelper.cs | 3 ++- .../InvocationProxyBuilder.cs | 3 ++- .../BinaryOperatorExpressionTransformer.cs | 3 ++- .../MemberInvocationInstanceCountConfiguration.cs | 3 ++- .../Services/TransformationContextCacheService.cs | 3 ++- .../Hast.Transformer/SimpleMemory/SimpleMemory.cs | 14 +++++++------- .../Representation/Declaration/ArrayType.cs | 3 ++- .../MultiCycleSdcStatementsAttributeExpression.cs | 3 ++- .../Representation/Declaration/RangedDataType.cs | 5 +++-- .../Representation/Declaration/SizedDataType.cs | 7 ++++--- .../Declaration/UnconstrainedArrayInstantiation.cs | 3 ++- .../Representation/Declaration/XdcFile.cs | 3 ++- .../Representation/Expression/VectorSlice.cs | 3 ++- src/Hastlayer/Hast.Vitis/Services/BinaryOpenCl.cs | 9 +++++---- .../Services/OpenClCommunicationService.cs | 7 ++++--- .../ImageProcessingAlgorithmsSampleRunner.cs | 3 ++- .../SampleRunners/ImageSharpSampleRunner.cs | 7 ++++--- .../SampleRunners/ParallelAlgorithmSampleRunner.cs | 3 ++- .../ImageSharpInternals/ResizeHelper.cs | 3 ++- .../ImageSharpInternals/ThrowHelper.cs | 3 ++- .../MonteCarloPiEstimator.cs | 2 +- test/Hast.Algorithms.Tests/Fix64Tests.cs | 3 ++- ...naryAndUnaryOperatorExpressionCasesGenerator.cs | 5 +++-- 26 files changed, 71 insertions(+), 49 deletions(-) diff --git a/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs b/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs index 0decf809..f4005a32 100644 --- a/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs +++ b/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs @@ -31,7 +31,7 @@ public sealed class CatapultLibrary : IDisposable /// /// Gets the name of the instance (Catapult:N where N is the PCIe endpoint number). /// - public string InstanceName => FormattableString.Invariant($"{Constants.ChannelName}:{PcieEndpointNumber}"); + public string InstanceName => StringHelper.CreateInvariant($"{Constants.ChannelName}:{PcieEndpointNumber}"); /// /// Contains the latest tasks to be awaited when starting a new task. @@ -352,7 +352,7 @@ private async Task> AssignJobAsync( var jobResult = await job; if (TesterOutput == null) return jobResult; - var message = FormattableString.Invariant( + var message = StringHelper.CreateInvariant( $"Job Finished{Environment.NewLine}************{Environment.NewLine}Slot: {currentSlot}{Environment.NewLine}"); if (!ignoreResponse) { @@ -377,7 +377,7 @@ private async Task> AssignMultiSliceJobAsync( int totalDataSize, int currentSliceCount) { - await TesterWriteLineAsync(FormattableString.Invariant($"Slices: {currentSliceCount}")); + await TesterWriteLineAsync(StringHelper.CreateInvariant($"Slices: {currentSliceCount}")); bool slotOverflow = currentSliceCount > BufferCount; // If the data exceeds buffer size limit, then cut it into maximal slices. @@ -443,10 +443,10 @@ private async Task> RunJobAsync(int bufferIndex, Memory input LogLineInvariant(Constants.Log.Info, $"Job on slot #{bufferIndex} starting..."); Debug.Assert( bufferIndex < BufferCount, - FormattableString.Invariant($"The buffer index is out of range. (current: {bufferIndex}, max: {BufferCount})")); + StringHelper.CreateInvariant($"The buffer index is out of range. (current: {bufferIndex}, max: {BufferCount})")); Debug.Assert( inputData.Length <= BufferSize, - FormattableString.Invariant($"The input data doesn't fit in the buffer. (current: {inputData.Length}, max: {BufferSize})")); + StringHelper.CreateInvariant($"The input data doesn't fit in the buffer. (current: {inputData.Length}, max: {BufferSize})")); var slot = (uint)bufferIndex; // Makes sure the buffer is ready to be written. diff --git a/src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs b/src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs index 29448cf9..cfdf8db5 100644 --- a/src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs +++ b/src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs @@ -76,7 +76,7 @@ private void OnCommandEvent( Log( LogLevel.None, name, - FormattableString.Invariant($"#{started.ProcessId} arguments:\n\t{string.Join("\n\t", arguments)}"), + StringHelper.CreateInvariant($"#{started.ProcessId} arguments:\n\t{string.Join("\n\t", arguments)}"), "started"); break; case StandardOutputCommandEvent output: @@ -158,8 +158,8 @@ public static (BuildLogger BuildLogger, TextWriter BuildOutput) Create( for (var i = 0; i < 100 && buildOutput == null; i++) { var fileName = i == 0 - ? FormattableString.Invariant($"{outFileName}.out") - : FormattableString.Invariant($"{outFileName}~{i}.out"); + ? StringHelper.CreateInvariant($"{outFileName}.out") + : StringHelper.CreateInvariant($"{outFileName}~{i}.out"); buildOutputPath = Path.Combine(buildOutputDirectoryPath, fileName); try diff --git a/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameExtensions.cs b/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameExtensions.cs index e499c3ad..66509c5b 100644 --- a/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameExtensions.cs +++ b/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameExtensions.cs @@ -1,3 +1,4 @@ +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Linq; @@ -39,7 +40,7 @@ public static string GetNextUnusedIndexedObjectName(this IArchitectureComponent component.InternallyDrivenSignals.Any(signal => signal.Name == component.CreatePrefixedObjectName(objectName))) { objectNameIndex++; - objectName = FormattableString.Invariant($"{name}.{objectNameIndex}"); + objectName = StringHelper.CreateInvariant($"{name}.{objectNameIndex}"); } return component.CreatePrefixedObjectName(objectName); diff --git a/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameHelper.cs b/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameHelper.cs index 18a950e0..c83e07f1 100644 --- a/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameHelper.cs +++ b/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameHelper.cs @@ -1,4 +1,5 @@ using Hast.VhdlBuilder.Extensions; +using Lombiq.HelpfulLibraries.Common.Utilities; using System; namespace Hast.Transformer.Vhdl.ArchitectureComponents; @@ -24,7 +25,7 @@ public static string CreateFinishedSignalName(string componentName) => CreatePrefixedObjectName(componentName, NameSuffixes.Finished); public static string CreateIndexedComponentName(string componentName, int index) => - FormattableString.Invariant($"{componentName}.{index}"); + StringHelper.CreateInvariant($"{componentName}.{index}"); public static string CreatePrefixedSegmentedObjectName(string componentName, params string[] segments) => CreatePrefixedObjectName(componentName, string.Join(".", segments)); diff --git a/src/Hastlayer/Hast.Transformer.Vhdl/InvocationProxyBuilders/InvocationProxyBuilder.cs b/src/Hastlayer/Hast.Transformer.Vhdl/InvocationProxyBuilders/InvocationProxyBuilder.cs index d781bb8b..22f9b758 100644 --- a/src/Hastlayer/Hast.Transformer.Vhdl/InvocationProxyBuilders/InvocationProxyBuilder.cs +++ b/src/Hastlayer/Hast.Transformer.Vhdl/InvocationProxyBuilders/InvocationProxyBuilder.cs @@ -9,6 +9,7 @@ using Hast.VhdlBuilder.Representation.Declaration; using Hast.VhdlBuilder.Representation.Expression; using ICSharpCode.Decompiler.CSharp.Syntax; +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Collections.Generic; using System.Linq; @@ -713,7 +714,7 @@ string GetTargetMemberComponentNameLocal(int index) => var targetComponentName = GetTargetMemberComponentNameLocal(targetIndex); var invokerIndex = invokedFromSingleComponent ? j : 0; - signalConnectionsBlock.Add(new LineComment(FormattableString.Invariant( + signalConnectionsBlock.Add(new LineComment(StringHelper.CreateInvariant( $"Signal connections for {invokerName} (#{targetIndex}):"))); signalConnectionsBlock.Add(new Assignment diff --git a/src/Hastlayer/Hast.Transformer.Vhdl/SubTransformers/ExpressionTransformers/BinaryOperatorExpressionTransformer.cs b/src/Hastlayer/Hast.Transformer.Vhdl/SubTransformers/ExpressionTransformers/BinaryOperatorExpressionTransformer.cs index efb5e351..170779ae 100644 --- a/src/Hastlayer/Hast.Transformer.Vhdl/SubTransformers/ExpressionTransformers/BinaryOperatorExpressionTransformer.cs +++ b/src/Hastlayer/Hast.Transformer.Vhdl/SubTransformers/ExpressionTransformers/BinaryOperatorExpressionTransformer.cs @@ -8,6 +8,7 @@ using Hast.VhdlBuilder.Representation.Expression; using ICSharpCode.Decompiler.CSharp.Syntax; using ICSharpCode.Decompiler.TypeSystem; +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -306,7 +307,7 @@ private static void BuildWaitState( new GeneratedComment(vhdlGenerationOptions => { var vhdl = operationResultDataObjectReference.ToVhdl(vhdlGenerationOptions); - return FormattableString.Invariant( + return StringHelper.CreateInvariant( $"Waiting for the result to appear in {vhdl} (have to wait {clockCyclesToWait} clock cycles in this state)."); }), new LineComment( diff --git a/src/Hastlayer/Hast.Transformer/Configuration/MemberInvocationInstanceCountConfiguration.cs b/src/Hastlayer/Hast.Transformer/Configuration/MemberInvocationInstanceCountConfiguration.cs index 1cb89cd1..e5e609d5 100644 --- a/src/Hastlayer/Hast.Transformer/Configuration/MemberInvocationInstanceCountConfiguration.cs +++ b/src/Hastlayer/Hast.Transformer/Configuration/MemberInvocationInstanceCountConfiguration.cs @@ -1,4 +1,5 @@ using Hast.Layer; +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Diagnostics; using System.Linq.Expressions; @@ -71,7 +72,7 @@ public MemberInvocationInstanceCountConfiguration(string memberNamePrefix) /// constructing a . /// public static string AddLambdaExpressionIndexToSimpleName(string simpleName, int lambdaExpressionIndex) => - FormattableString.Invariant($"{simpleName}.LambdaExpression.{lambdaExpressionIndex}"); + StringHelper.CreateInvariant($"{simpleName}.LambdaExpression.{lambdaExpressionIndex}"); } public class MemberInvocationInstanceCountConfigurationForMethod : MemberInvocationInstanceCountConfiguration diff --git a/src/Hastlayer/Hast.Transformer/Services/TransformationContextCacheService.cs b/src/Hastlayer/Hast.Transformer/Services/TransformationContextCacheService.cs index ee774585..43857732 100644 --- a/src/Hastlayer/Hast.Transformer/Services/TransformationContextCacheService.cs +++ b/src/Hastlayer/Hast.Transformer/Services/TransformationContextCacheService.cs @@ -1,6 +1,7 @@ using Hast.Common.Services; using Hast.Layer; using Hast.Transformer.Models; +using Lombiq.HelpfulLibraries.Common.Utilities; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using System; @@ -94,6 +95,6 @@ private static string GetCacheKey(IEnumerable assemblyPaths, string tran } var hashCode = transformationId.GetHashCode(StringComparison.InvariantCulture); - return FormattableString.Invariant($"Hast.Transformer.TransformationContextCache.{fileHashes} - {hashCode}"); + return StringHelper.CreateInvariant($"Hast.Transformer.TransformationContextCache.{fileHashes} - {hashCode}"); } } diff --git a/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs b/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs index e08aeede..a6289ecd 100644 --- a/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs +++ b/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs @@ -109,13 +109,13 @@ internal SimpleMemory(Memory memory, int prefixCellCount, int alignment) #else throw new InvalidOperationException( "Alignment failed! (" + - FormattableString.Invariant($"64-bit: {Environment.Is64BitProcess}; ") + - FormattableString.Invariant($"address: {address}; ") + - FormattableString.Invariant($"addressLong: {addressLong}; ") + - FormattableString.Invariant($"{nameof(memory)} length: {memory.Length}; ") + - FormattableString.Invariant($"alignment: {alignment}; ") + - FormattableString.Invariant($"alignmentOffset: {alignmentOffset}; ") + - FormattableString.Invariant($"expectedLength: {expectedLength})")); + StringHelper.CreateInvariant($"64-bit: {Environment.Is64BitProcess}; ") + + StringHelper.CreateInvariant($"address: {address}; ") + + StringHelper.CreateInvariant($"addressLong: {addressLong}; ") + + StringHelper.CreateInvariant($"{nameof(memory)} length: {memory.Length}; ") + + StringHelper.CreateInvariant($"alignment: {alignment}; ") + + StringHelper.CreateInvariant($"alignmentOffset: {alignmentOffset}; ") + + StringHelper.CreateInvariant($"expectedLength: {expectedLength})")); #endif } } diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/ArrayType.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/ArrayType.cs index 52a36cdf..95e87eaf 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/ArrayType.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/ArrayType.cs @@ -1,3 +1,4 @@ +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Diagnostics; @@ -18,7 +19,7 @@ public override string ToVhdl(IVhdlGenerationOptions vhdlGenerationOptions) var vhdl = ElementType.ToReference().ToVhdl(vhdlGenerationOptions); return Terminated.Terminate( - FormattableString.Invariant($"type {shortName} is array ({range}) of {vhdl}"), + StringHelper.CreateInvariant($"type {shortName} is array ({range}) of {vhdl}"), vhdlGenerationOptions); } } diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/MultiCycleSdcStatementsAttributeExpression.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/MultiCycleSdcStatementsAttributeExpression.cs index 27737063..62e9e03e 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/MultiCycleSdcStatementsAttributeExpression.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/MultiCycleSdcStatementsAttributeExpression.cs @@ -1,4 +1,5 @@ using Hast.VhdlBuilder.Extensions; +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Collections.Generic; using System.Diagnostics; @@ -70,7 +71,7 @@ public string ToVhdl(IVhdlGenerationOptions vhdlGenerationOptions) var vhdl = PathReference.ToVhdl(vhdlGenerationOptions).TrimExtendedVhdlIdDelimiters().Replace(" ", "\\ "); - return FormattableString.Invariant( + return StringHelper.CreateInvariant( $"-name SDC_STATEMENT \"\"set_multicycle_path {ClockCycles} -{Type} -to {{*{name}{vhdl}[*]}}\"\""); } } diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/RangedDataType.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/RangedDataType.cs index eca97c75..d222a213 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/RangedDataType.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/RangedDataType.cs @@ -1,3 +1,4 @@ +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Diagnostics; @@ -28,7 +29,7 @@ public RangedDataType() public override DataType ToReference() => this; public override string ToVhdl(IVhdlGenerationOptions vhdlGenerationOptions) => - FormattableString.Invariant($"{Name} range {RangeMin} to {RangeMax}"); + StringHelper.CreateInvariant($"{Name} range {RangeMin} to {RangeMax}"); public override bool Equals(object obj) { @@ -38,6 +39,6 @@ public override bool Equals(object obj) } public override int GetHashCode() => - FormattableString.Invariant($"{Name}{TypeCategory}{RangeMin}{RangeMax}") + StringHelper.CreateInvariant($"{Name}{TypeCategory}{RangeMin}{RangeMax}") .GetHashCode(StringComparison.InvariantCulture); } diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/SizedDataType.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/SizedDataType.cs index cca4a60f..df1ea6b9 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/SizedDataType.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/SizedDataType.cs @@ -1,3 +1,4 @@ +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Diagnostics; @@ -36,8 +37,8 @@ public override string ToVhdl(IVhdlGenerationOptions vhdlGenerationOptions) var state = (SizeNumber > 0 ? hasNumericSize : 0) + (SizeExpression != null ? hasSizeExpression : 0); return state switch { - hasNumericSize => FormattableString.Invariant($"{Name}({SizeNumber - 1} downto 0)"), - hasSizeExpression => FormattableString.Invariant($"{Name}({SizeExpression.ToVhdl(vhdlGenerationOptions)} downto 0)"), + hasNumericSize => StringHelper.CreateInvariant($"{Name}({SizeNumber - 1} downto 0)"), + hasSizeExpression => StringHelper.CreateInvariant($"{Name}({SizeExpression.ToVhdl(vhdlGenerationOptions)} downto 0)"), hasBoth => throw new InvalidOperationException( "VHDL sized data types should have their size specified either as an integer value or as an expression, but not both."), _ => Name, @@ -55,6 +56,6 @@ public override bool Equals(object obj) } public override int GetHashCode() => - FormattableString.Invariant($"{Name}{TypeCategory}{SizeNumber}") + StringHelper.CreateInvariant($"{Name}{TypeCategory}{SizeNumber}") .GetHashCode(StringComparison.InvariantCulture); } diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/UnconstrainedArrayInstantiation.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/UnconstrainedArrayInstantiation.cs index b08c9e7f..7410a2f1 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/UnconstrainedArrayInstantiation.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/UnconstrainedArrayInstantiation.cs @@ -1,3 +1,4 @@ +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Diagnostics; @@ -15,5 +16,5 @@ public class UnconstrainedArrayInstantiation : ArrayTypeBase public override DataType ToReference() => this; public override string ToVhdl(IVhdlGenerationOptions vhdlGenerationOptions) => - FormattableString.Invariant($"{vhdlGenerationOptions.NameShortener(Name)}({RangeFrom} to {RangeTo})"); + StringHelper.CreateInvariant($"{vhdlGenerationOptions.NameShortener(Name)}({RangeFrom} to {RangeTo})"); } diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/XdcFile.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/XdcFile.cs index 93cb8396..ec11b660 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/XdcFile.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/XdcFile.cs @@ -1,4 +1,5 @@ using Hast.VhdlBuilder.Extensions; +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Collections.Generic; using System.Diagnostics; @@ -63,7 +64,7 @@ public string ToVhdl(IVhdlGenerationOptions vhdlGenerationOptions) // identifier. Spaces need to be escaped with a slash. var vhdl = PathReference.ToVhdl(vhdlGenerationOptions).TrimExtendedVhdlIdDelimiters().Replace(" ", "\\ "); - return FormattableString.Invariant( + return StringHelper.CreateInvariant( $"set_multicycle_path {ClockCycles} -{Type} -to [get_cells {hierarchical}{{*{vhdl}*}}]"); } } diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Expression/VectorSlice.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Expression/VectorSlice.cs index 20924c81..781c7a20 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Expression/VectorSlice.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Expression/VectorSlice.cs @@ -1,3 +1,4 @@ +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Diagnostics; @@ -17,6 +18,6 @@ public string ToVhdl(IVhdlGenerationOptions vhdlGenerationOptions) { var vhdl = Vector.ToVhdl(vhdlGenerationOptions); var direction = IsDownTo ? "downto" : "to"; - return FormattableString.Invariant($"{vhdl}({IndexFrom} {direction} {IndexTo})"); + return StringHelper.CreateInvariant($"{vhdl}({IndexFrom} {direction} {IndexTo})"); } } diff --git a/src/Hastlayer/Hast.Vitis/Services/BinaryOpenCl.cs b/src/Hastlayer/Hast.Vitis/Services/BinaryOpenCl.cs index 045373fb..fc77f9ad 100644 --- a/src/Hastlayer/Hast.Vitis/Services/BinaryOpenCl.cs +++ b/src/Hastlayer/Hast.Vitis/Services/BinaryOpenCl.cs @@ -3,6 +3,7 @@ using Hast.Vitis.Interop; using Hast.Vitis.Interop.Enums; using Hast.Vitis.Models; +using Lombiq.HelpfulLibraries.Common.Utilities; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; @@ -250,7 +251,7 @@ private IntPtr CreateProgramWithBinary(IntPtr binary, int binaryLength) VerifyResults( resultsPerDevice, (deviceResult, i) => new InvalidOperationException( - FormattableString.Invariant($"Error while creating program on device #{i}: {deviceResult}"))); + StringHelper.CreateInvariant($"Error while creating program on device #{i}: {deviceResult}"))); VerifyResult(_cl.BuildProgram( program, @@ -330,7 +331,7 @@ public void Dispose() var queueReleaseExceptions = VerifyResults( _queues.Values.Select(_cl.ReleaseCommandQueue), (result, index) => new InvalidOperationException( - FormattableString.Invariant($"Error releasing queue for device #{queues[index].Key}: {result}"))); + StringHelper.CreateInvariant($"Error releasing queue for device #{queues[index].Key}: {result}"))); if (queueReleaseExceptions != null) exceptions.AddRange(queueReleaseExceptions.InnerExceptions); @@ -356,7 +357,7 @@ private IntPtr GetQueue(int queueIndex) { if (_queues.TryGetValue(queueIndex, out var queue)) return queue; throw new InvalidOperationException( - FormattableString.Invariant( + StringHelper.CreateInvariant( $"There is no command queue for device #{queueIndex}. Please use {nameof(CreateCommandQueue)} to create one!")); } @@ -364,7 +365,7 @@ private IntPtr GetKernel(string kernelName) { if (_kernels.TryGetValue(kernelName, out var kernel)) return kernel; throw new InvalidOperationException( - FormattableString.Invariant( + StringHelper.CreateInvariant( $"The kernel '{kernelName}' does not exit. You can create a kernel with {nameof(CreateBinaryKernel)}.")); } diff --git a/src/Hastlayer/Hast.Vitis/Services/OpenClCommunicationService.cs b/src/Hastlayer/Hast.Vitis/Services/OpenClCommunicationService.cs index 2d60cb89..2201478a 100644 --- a/src/Hastlayer/Hast.Vitis/Services/OpenClCommunicationService.cs +++ b/src/Hastlayer/Hast.Vitis/Services/OpenClCommunicationService.cs @@ -5,6 +5,7 @@ using Hast.Vitis.Extensions; using Hast.Vitis.Interop.Enums; using Hast.Vitis.Models; +using Lombiq.HelpfulLibraries.Common.Utilities; using Microsoft.Extensions.Logging; using System; using System.Buffers; @@ -74,7 +75,7 @@ public override async Task ExecuteAsync( { devices.Add(new Device { - Identifier = FormattableString.Invariant($"{ChannelName}:{configuration.VendorName ?? "any"}:{i}"), + Identifier = StringHelper.CreateInvariant($"{ChannelName}:{configuration.VendorName ?? "any"}:{i}"), Metadata = i, }); _binaryOpenCl.CreateCommandQueue(i); @@ -102,7 +103,7 @@ public override async Task ExecuteAsync( if (hostMemory.Length <= headerSize) { throw new InvalidOperationException( - FormattableString.Invariant( + StringHelper.CreateInvariant( $"The result size is only {hostMemory.Length}b but it must be more than the header size of {headerSize}b.")); } @@ -238,7 +239,7 @@ private OpenClResultMetadata GetResultMetadata(Span bufferSpan, IOpenClCon if (bufferSpan.Length <= headerSize) { throw new InvalidOperationException( - FormattableString.Invariant( + StringHelper.CreateInvariant( $"The result size is only {bufferSpan.Length}b but it must be more than the header size of {headerSize}b.")); } diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageProcessingAlgorithmsSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageProcessingAlgorithmsSampleRunner.cs index a4c09324..3fb1c008 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageProcessingAlgorithmsSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageProcessingAlgorithmsSampleRunner.cs @@ -1,5 +1,6 @@ using Hast.Layer; using Hast.Samples.SampleAssembly; +using Lombiq.HelpfulLibraries.Common.Utilities; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Bmp; using SixLabors.ImageSharp.PixelFormats; @@ -39,7 +40,7 @@ public async Task RunAsync(IHastlayer hastlayer, IHardwareRepresentation hardwar hardwareRepresentation.HardwareGenerationConfiguration); sw.Stop(); await modifiedImageCpu.SaveAsync("contrast-cpu.bmp", new BmpEncoder()); - Console.WriteLine(FormattableString.Invariant($"On CPU it took {sw.ElapsedMilliseconds} ms.")); + Console.WriteLine(StringHelper.CreateInvariant($"On CPU it took {sw.ElapsedMilliseconds} ms.")); // ImageFilter disabled until it's improved. //// var imageFilter = await hastlayer.GenerateProxy(hardwareRepresentation, new ImageFilter()); //// var filteredImage = imageFilter.DetectHorizontalEdges(bitmap); diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageSharpSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageSharpSampleRunner.cs index 9c9d95f7..f8d70c27 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageSharpSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageSharpSampleRunner.cs @@ -1,6 +1,7 @@ using Hast.Layer; using Hast.Samples.SampleAssembly; using Hast.Samples.SampleAssembly.ImageSharpModifications.Resize; +using Lombiq.HelpfulLibraries.Common.Utilities; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Processing; using System; @@ -52,7 +53,7 @@ Image FpgaClone(out long milliseconds) using var newImage = FpgaClone(out var timeFpga); await newImage.SaveAsync("FpgaResizedWithHastlayer.jpg"); - Console.WriteLine(FormattableString.Invariant($"On FPGA it took {timeFpga} ms")); + Console.WriteLine(StringHelper.CreateInvariant($"On FPGA it took {timeFpga} ms")); } private static void RunSoftwareBenchmarks(Image image) @@ -68,7 +69,7 @@ private static void RunSoftwareBenchmarks(Image image) out var timeNew); resizedNew.Save("FpgaResizedWithModifiedImageSharp.jpg"); Console.WriteLine( - FormattableString.Invariant($"On CPU Modified ImageSharp algorithm took {timeNew} ms")); + StringHelper.CreateInvariant($"On CPU Modified ImageSharp algorithm took {timeNew} ms")); using var resizedOld = CloneAndMeasure( image, @@ -76,7 +77,7 @@ private static void RunSoftwareBenchmarks(Image image) out var timeOld); resizedOld.Save("FpgaResizedWithOriginalImageSharp.jpg"); Console.WriteLine( - FormattableString.Invariant($"On CPU Original ImageSharp algorithm took {timeOld} ms")); + StringHelper.CreateInvariant($"On CPU Original ImageSharp algorithm took {timeOld} ms")); } private static Image CloneAndMeasure( diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/ParallelAlgorithmSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/ParallelAlgorithmSampleRunner.cs index 23b8ab71..89db7e7c 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/ParallelAlgorithmSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/ParallelAlgorithmSampleRunner.cs @@ -1,5 +1,6 @@ using Hast.Layer; using Hast.Samples.SampleAssembly; +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Diagnostics; using System.Threading.Tasks; @@ -50,7 +51,7 @@ long RunLogAndTime(ParallelAlgorithm parallelAlgorithm, int input) parallel = new ParallelAlgorithm(); // Replace proxy with CPU implementation. foreach (var number in numbers) { - Console.WriteLine(FormattableString.Invariant($"On CPU it took {RunLogAndTime(parallel, number)}ms.")); + Console.WriteLine(StringHelper.CreateInvariant($"On CPU it took {RunLogAndTime(parallel, number)}ms.")); } } } diff --git a/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/ImageSharpInternals/ResizeHelper.cs b/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/ImageSharpInternals/ResizeHelper.cs index 3fb4053f..0445ac31 100644 --- a/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/ImageSharpInternals/ResizeHelper.cs +++ b/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/ImageSharpInternals/ResizeHelper.cs @@ -3,6 +3,7 @@ // Modified file, original is found at: // https://github.com/SixLabors/ImageSharp/blob/master/src/ImageSharp/Processing/Processors/Transforms/Resize/ResizeHelper.cs +using Lombiq.HelpfulLibraries.Common.Utilities; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Processing; using System; @@ -19,7 +20,7 @@ public static (Size Size, Rectangle Rectangle) CalculateTargetLocationAndBounds( if (width <= 0 && height <= 0) { ThrowInvalid( - FormattableString.Invariant($"Target width {width} and height {height} must be greater than zero.")); + StringHelper.CreateInvariant($"Target width {width} and height {height} must be greater than zero.")); } // Ensure target size is populated across both dimensions. diff --git a/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/ImageSharpInternals/ThrowHelper.cs b/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/ImageSharpInternals/ThrowHelper.cs index e0d1aeb2..4dfd4352 100644 --- a/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/ImageSharpInternals/ThrowHelper.cs +++ b/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/ImageSharpInternals/ThrowHelper.cs @@ -1,6 +1,7 @@ // Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Runtime.CompilerServices; @@ -77,7 +78,7 @@ public static void ThrowArgumentOutOfRangeExceptionForMustBeBetweenOrEqualTo( [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentOutOfRangeExceptionForMustBeSizedAtLeast(int minLength, string parameterName) => ThrowArgumentException( - FormattableString.Invariant($"Spans must be at least of length {minLength}!"), + StringHelper.CreateInvariant($"Spans must be at least of length {minLength}!"), parameterName); /// diff --git a/src/Samples/Hast.Samples.SampleAssembly/MonteCarloPiEstimator.cs b/src/Samples/Hast.Samples.SampleAssembly/MonteCarloPiEstimator.cs index e17be7d7..a0e6839e 100644 --- a/src/Samples/Hast.Samples.SampleAssembly/MonteCarloPiEstimator.cs +++ b/src/Samples/Hast.Samples.SampleAssembly/MonteCarloPiEstimator.cs @@ -86,7 +86,7 @@ public double EstimatePi(uint iterationsCount, IHastlayer hastlayer = null, IHar if (iterationsCount % MaxDegreeOfParallelism != 0) { throw new InvalidOperationException( - FormattableString.Invariant( + StringHelper.CreateInvariant( $"The number of iterations must be divisible by {MaxDegreeOfParallelism}.")); } diff --git a/test/Hast.Algorithms.Tests/Fix64Tests.cs b/test/Hast.Algorithms.Tests/Fix64Tests.cs index 0668c643..1d4fdee7 100644 --- a/test/Hast.Algorithms.Tests/Fix64Tests.cs +++ b/test/Hast.Algorithms.Tests/Fix64Tests.cs @@ -1,3 +1,4 @@ +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Collections.Generic; using System.Diagnostics; @@ -367,7 +368,7 @@ public void Modulus() deltas.Add(delta); Assert.True( delta <= 60 * Fix64.Precision, - FormattableString.Invariant($"{f1} % {f2} = expected {expected} but got {actual}")); + StringHelper.CreateInvariant($"{f1} % {f2} = expected {expected} but got {actual}")); } } diff --git a/test/TestInputAssemblies/Hast.TestInputs.Dynamic/BinaryAndUnaryOperatorExpressionCasesGenerator.cs b/test/TestInputAssemblies/Hast.TestInputs.Dynamic/BinaryAndUnaryOperatorExpressionCasesGenerator.cs index 19b7eb45..7fba3d2b 100644 --- a/test/TestInputAssemblies/Hast.TestInputs.Dynamic/BinaryAndUnaryOperatorExpressionCasesGenerator.cs +++ b/test/TestInputAssemblies/Hast.TestInputs.Dynamic/BinaryAndUnaryOperatorExpressionCasesGenerator.cs @@ -1,3 +1,4 @@ +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; @@ -142,7 +143,7 @@ private static string AddiSaveResults( memoryIndex += 16; // The long cast will be unnecessary most of the time but determining when it's needed is complex so good // enough. Awkward indentation is so the generated code can be properly formatted. - return FormattableString.Invariant($@"SaveResult( + return StringHelper.CreateInvariant($@"SaveResult( memory, {originalMemoryIndex}, (long)({code0}), // {originalMemoryIndex} @@ -195,6 +196,6 @@ private static string AddSaveResult(int memoryIndex, string code, bool addLongCa // The long cast will be unnecessary most of the time but determining when it's needed is complex so good // enough. if (addLongCast) code = $"(long)({code})"; - return FormattableString.Invariant($@"SaveResult(memory, {originalMemoryIndex}, {code});"); + return StringHelper.CreateInvariant($@"SaveResult(memory, {originalMemoryIndex}, {code});"); } } From 0382637ecb8677a5bd4eb62f3c67b7ef5a449c57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 12:43:24 +0200 Subject: [PATCH 03/53] Fix MA0089 (Use an overload with char instead of string). --- src/Hastlayer/Hast.Common/Extensions/MethodInfoExtensions.cs | 2 +- src/Hastlayer/Hast.Console/Subcommands/VitisSubcommand.cs | 2 +- src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs | 2 +- .../ArchitectureComponents/ArchitectureComponentNameHelper.cs | 2 +- src/Hastlayer/Hast.Transformer/Extensions/MemberExtensions.cs | 2 +- .../Declaration/MultiCycleSdcStatementsAttributeExpression.cs | 2 +- .../Hast.VhdlBuilder/Representation/VhdlGenerationOptions.cs | 2 +- src/Hastlayer/Hast.Vitis/Models/AzureStorageConfiguration.cs | 2 +- .../AzureHardwareImplementationComposerBuildProvider.cs | 2 +- src/Samples/Hast.Samples.Consumer/Attributes/HintAttribute.cs | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Hastlayer/Hast.Common/Extensions/MethodInfoExtensions.cs b/src/Hastlayer/Hast.Common/Extensions/MethodInfoExtensions.cs index e269549f..54f79e33 100644 --- a/src/Hastlayer/Hast.Common/Extensions/MethodInfoExtensions.cs +++ b/src/Hastlayer/Hast.Common/Extensions/MethodInfoExtensions.cs @@ -12,5 +12,5 @@ public static string GetFullName(this MethodInfo method) => method.ReturnType.FullName + " " + method.ReflectedType.FullName + "::" + method.Name + - "(" + string.Join(",", method.GetParameters().Select(parameter => parameter.ParameterType.FullName)) + ")"; + "(" + string.Join(',', method.GetParameters().Select(parameter => parameter.ParameterType.FullName)) + ")"; } diff --git a/src/Hastlayer/Hast.Console/Subcommands/VitisSubcommand.cs b/src/Hastlayer/Hast.Console/Subcommands/VitisSubcommand.cs index 39fd3249..350fde2f 100644 --- a/src/Hastlayer/Hast.Console/Subcommands/VitisSubcommand.cs +++ b/src/Hastlayer/Hast.Console/Subcommands/VitisSubcommand.cs @@ -37,7 +37,7 @@ public void Run() var result = Parser.Default.ParseArguments(_rawArguments); result .WithParsed(options => RunOptionsAsync(options, result, BuildLogger).Wait()) - .WithNotParsed(errors => WriteLine(string.Join("\n", errors))); + .WithNotParsed(errors => WriteLine(string.Join('\n', errors))); } private static async Task RunOptionsAsync( diff --git a/src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs b/src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs index cfdf8db5..7911a99b 100644 --- a/src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs +++ b/src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs @@ -55,7 +55,7 @@ Command Configure(Command command) _logger.LogInformation( "Starting program: {Executable} {Arguments} (working directory: {WorkingDirectory})", executable, - string.Join(" ", arguments), + string.Join(' ', arguments), hasWorkingDirectory ? workingDirectory : "."); return CliHelper.StreamAsync( executable, diff --git a/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameHelper.cs b/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameHelper.cs index c83e07f1..9346b206 100644 --- a/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameHelper.cs +++ b/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameHelper.cs @@ -28,7 +28,7 @@ public static string CreateIndexedComponentName(string componentName, int index) StringHelper.CreateInvariant($"{componentName}.{index}"); public static string CreatePrefixedSegmentedObjectName(string componentName, params string[] segments) => - CreatePrefixedObjectName(componentName, string.Join(".", segments)); + CreatePrefixedObjectName(componentName, string.Join('.', segments)); public static string CreatePrefixedObjectName(string componentName, string name) => CreatePrefixedExtendedVhdlId(componentName, "." + name); diff --git a/src/Hastlayer/Hast.Transformer/Extensions/MemberExtensions.cs b/src/Hastlayer/Hast.Transformer/Extensions/MemberExtensions.cs index dd04243e..435e8956 100644 --- a/src/Hastlayer/Hast.Transformer/Extensions/MemberExtensions.cs +++ b/src/Hastlayer/Hast.Transformer/Extensions/MemberExtensions.cs @@ -13,7 +13,7 @@ public static string GetFullName(this IMember member) if (member is IMethod method) { // There shouldn't be a space after commas so it follows Cecil naming conventions. - name += $"({string.Join(",", method.Parameters.Select(parameter => parameter.Type.GetFullName()))})"; + name += $"({string.Join(',', method.Parameters.Select(parameter => parameter.Type.GetFullName()))})"; } return name; diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/MultiCycleSdcStatementsAttributeExpression.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/MultiCycleSdcStatementsAttributeExpression.cs index 62e9e03e..61fc76dd 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/MultiCycleSdcStatementsAttributeExpression.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/MultiCycleSdcStatementsAttributeExpression.cs @@ -48,7 +48,7 @@ public void AddPath(string parentName, IDataObject pathReference, int clockCycle public string ToVhdl(IVhdlGenerationOptions vhdlGenerationOptions) => Terminated.Terminate( "\"" + - string.Join(";", _paths.Select(statement => statement.ToVhdl(vhdlGenerationOptions))) + + string.Join(';', _paths.Select(statement => statement.ToVhdl(vhdlGenerationOptions))) + "\"", vhdlGenerationOptions); diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/VhdlGenerationOptions.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/VhdlGenerationOptions.cs index ef87ed28..a8554822 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/VhdlGenerationOptions.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/VhdlGenerationOptions.cs @@ -96,7 +96,7 @@ private static string NameShortenerMatch(Match match) var (before, _, temporary) = shortName.Partition("("); var (arguments, _, after) = temporary.Partition(")"); - var shortenedParameters = string.Join(",", arguments + var shortenedParameters = string.Join(',', arguments .Split(',') .Select(parameter => parameter.Split('.').Last())); diff --git a/src/Hastlayer/Hast.Vitis/Models/AzureStorageConfiguration.cs b/src/Hastlayer/Hast.Vitis/Models/AzureStorageConfiguration.cs index 9cd35444..7b99dbfa 100644 --- a/src/Hastlayer/Hast.Vitis/Models/AzureStorageConfiguration.cs +++ b/src/Hastlayer/Hast.Vitis/Models/AzureStorageConfiguration.cs @@ -20,7 +20,7 @@ public class AzureStorageConfiguration public string GenerateStorageConnectionString() => string.Join( - separator: ";", + separator: ';', "DefaultEndpointsProtocol=https", $"AccountName={StorageAccountName}", $"AccountKey={StorageAccountKey}", diff --git a/src/Hastlayer/Hast.Vitis/Services/AzureHardwareImplementationComposerBuildProvider.cs b/src/Hastlayer/Hast.Vitis/Services/AzureHardwareImplementationComposerBuildProvider.cs index d0377235..3a7a7bb4 100644 --- a/src/Hastlayer/Hast.Vitis/Services/AzureHardwareImplementationComposerBuildProvider.cs +++ b/src/Hastlayer/Hast.Vitis/Services/AzureHardwareImplementationComposerBuildProvider.cs @@ -147,7 +147,7 @@ private async Task PerformAttestationAsync( } var outputString = outputList.Any() - ? string.Join("\n", outputList.Select(item => "- " + item.Trim())) + ? string.Join('\n', outputList.Select(item => "- " + item.Trim())) : "- Unknown issue"; _logger.LogError("Attestation failed:\n{OutputString}", outputString); diff --git a/src/Samples/Hast.Samples.Consumer/Attributes/HintAttribute.cs b/src/Samples/Hast.Samples.Consumer/Attributes/HintAttribute.cs index 9c2ff289..e51a5b80 100644 --- a/src/Samples/Hast.Samples.Consumer/Attributes/HintAttribute.cs +++ b/src/Samples/Hast.Samples.Consumer/Attributes/HintAttribute.cs @@ -11,5 +11,5 @@ public sealed class HintAttribute : Attribute { public string Text { get; } - public HintAttribute(params string[] text) => Text = string.Join(" ", text.Select(fragment => fragment.Trim())); + public HintAttribute(params string[] text) => Text = string.Join(' ', text.Select(fragment => fragment.Trim())); } From dfd880594269fc56cdc2958e1d670b57e9c4f7f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 12:52:52 +0200 Subject: [PATCH 04/53] Fix CA1852 (Type can be sealed because it has no subtypes in its containing assembly and is not externally visible). --- .../Hast.Common/Services/DependencyInterfaceContainer.cs | 2 +- src/Hastlayer/Hast.Console/Program.cs | 2 +- src/Hastlayer/Hast.Layer/Models/HardwareRepresentation.cs | 4 ++-- .../ArchitectureComponents/MemberStateMachine.cs | 4 ++-- .../Models/ArchitectureComponentResult.cs | 2 +- .../Hast.Transformer.Vhdl/Models/MemberTransformerResult.cs | 2 +- src/Hastlayer/Hast.Transformer/Models/ArraySize.cs | 4 ++-- src/Hastlayer/Hast.Transformer/Models/ArraySizeHolder.cs | 2 +- .../Hast.Transformer/Models/DeclarationReferenceMetadata.cs | 2 +- .../ConstantValuesMarkingVisitor.cs | 2 +- .../ConstantValuesSubstitutingAstProcessor.cs | 4 ++-- .../ConstantValuesSubstitutingVisitor.cs | 2 +- .../ConstantValuesSubstitution/ConstantValuesTable.cs | 2 +- .../GlobalValueHoldersHandlingVisitor.cs | 2 +- .../ObjectHoldersToSubstitutedConstructorsMappingVisitor.cs | 2 +- .../SampleRunners/FSharpParallelAlgorithmSampleRunner.cs | 2 +- .../SampleRunners/Fix64CalculatorSampleRunner.cs | 2 +- .../SampleRunners/GenomeMatcherSampleRunner.cs | 2 +- .../SampleRunners/ImageProcessingAlgorithmsSampleRunner.cs | 2 +- .../SampleRunners/ImageSharpSampleRunner.cs | 2 +- .../SampleRunners/LoopbackSampleRunner.cs | 2 +- .../SampleRunners/MemoryTestSampleRunner.cs | 2 +- .../SampleRunners/MonteCarloPiEstimatorSampleRunner.cs | 2 +- .../SampleRunners/ObjectOrientedShowcaseSampleRunner.cs | 2 +- .../SampleRunners/ParallelAlgorithmSampleRunner.cs | 2 +- .../SampleRunners/Posit32AdvancedCalculatorSampleRunner.cs | 2 +- .../SampleRunners/Posit32CalculatorSampleRunner.cs | 2 +- .../SampleRunners/Posit32FusedCalculatorSampleRunner.cs | 2 +- .../SampleRunners/PositCalculatorSampleRunner.cs | 2 +- .../SampleRunners/PrimeCalculatorSampleRunner.cs | 2 +- .../SampleRunners/RecursiveAlgorithmsSampleRunner.cs | 2 +- .../SampleRunners/SimdCalculatorSampleRunner.cs | 2 +- .../SampleRunners/UnumCalculatorSampleRunner.cs | 2 +- 33 files changed, 37 insertions(+), 37 deletions(-) diff --git a/src/Hastlayer/Hast.Common/Services/DependencyInterfaceContainer.cs b/src/Hastlayer/Hast.Common/Services/DependencyInterfaceContainer.cs index 2dc3286a..e4eff1a9 100644 --- a/src/Hastlayer/Hast.Common/Services/DependencyInterfaceContainer.cs +++ b/src/Hastlayer/Hast.Common/Services/DependencyInterfaceContainer.cs @@ -14,7 +14,7 @@ public static class DependencyInterfaceContainer { // This is necessary because .Net Core Dependency Injection does not resolve Lazy out of the box. // https://stackoverflow.com/questions/44934511/does-net-core-dependency-injection-support-lazyt - internal class Lazier : Lazy + internal sealed class Lazier : Lazy where T : class { public Lazier(IServiceProvider provider) diff --git a/src/Hastlayer/Hast.Console/Program.cs b/src/Hastlayer/Hast.Console/Program.cs index 2e9a2499..c4e62308 100644 --- a/src/Hastlayer/Hast.Console/Program.cs +++ b/src/Hastlayer/Hast.Console/Program.cs @@ -12,7 +12,7 @@ namespace Hast.Console; [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "This application is not localized.")] -internal class Program +internal sealed class Program { private static Dictionary _subcommands; diff --git a/src/Hastlayer/Hast.Layer/Models/HardwareRepresentation.cs b/src/Hastlayer/Hast.Layer/Models/HardwareRepresentation.cs index b0ec2a8d..5c1057d9 100644 --- a/src/Hastlayer/Hast.Layer/Models/HardwareRepresentation.cs +++ b/src/Hastlayer/Hast.Layer/Models/HardwareRepresentation.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace Hast.Layer.Models; -internal class HardwareRepresentation : IHardwareRepresentation +internal sealed class HardwareRepresentation : IHardwareRepresentation { public IEnumerable SoftAssemblyPaths { get; set; } public IHardwareDescription HardwareDescription { get; set; } diff --git a/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/MemberStateMachine.cs b/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/MemberStateMachine.cs index 3060b3fa..2259a784 100644 --- a/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/MemberStateMachine.cs +++ b/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/MemberStateMachine.cs @@ -6,7 +6,7 @@ namespace Hast.Transformer.Vhdl.ArchitectureComponents; -internal class MemberStateMachine : ArchitectureComponentBase, IMemberStateMachine +internal sealed class MemberStateMachine : ArchitectureComponentBase, IMemberStateMachine { private readonly Enum _statesEnum; private readonly Variable _stateVariable; @@ -132,7 +132,7 @@ public override IVhdlElement BuildBody() new LineComment(Name + " state machine end")); } - public class MemberStateMachineState : IMemberStateMachineState + public sealed class MemberStateMachineState : IMemberStateMachineState { public IBlockElement Body { get; set; } public decimal RequiredClockCycles { get; set; } diff --git a/src/Hastlayer/Hast.Transformer.Vhdl/Models/ArchitectureComponentResult.cs b/src/Hastlayer/Hast.Transformer.Vhdl/Models/ArchitectureComponentResult.cs index 98b09542..79aebb25 100644 --- a/src/Hastlayer/Hast.Transformer.Vhdl/Models/ArchitectureComponentResult.cs +++ b/src/Hastlayer/Hast.Transformer.Vhdl/Models/ArchitectureComponentResult.cs @@ -5,7 +5,7 @@ namespace Hast.Transformer.Vhdl.Models; -internal class ArchitectureComponentResult : IArchitectureComponentResult +internal sealed class ArchitectureComponentResult : IArchitectureComponentResult { public IArchitectureComponent ArchitectureComponent { get; set; } public IVhdlElement Declarations { get; set; } diff --git a/src/Hastlayer/Hast.Transformer.Vhdl/Models/MemberTransformerResult.cs b/src/Hastlayer/Hast.Transformer.Vhdl/Models/MemberTransformerResult.cs index b85d03ef..9eb1c588 100644 --- a/src/Hastlayer/Hast.Transformer.Vhdl/Models/MemberTransformerResult.cs +++ b/src/Hastlayer/Hast.Transformer.Vhdl/Models/MemberTransformerResult.cs @@ -3,7 +3,7 @@ namespace Hast.Transformer.Vhdl.Models; -internal class MemberTransformerResult : IMemberTransformerResult +internal sealed class MemberTransformerResult : IMemberTransformerResult { public EntityDeclaration Member { get; set; } public bool IsHardwareEntryPointMember { get; set; } diff --git a/src/Hastlayer/Hast.Transformer/Models/ArraySize.cs b/src/Hastlayer/Hast.Transformer/Models/ArraySize.cs index 475d9d1c..a972a67b 100644 --- a/src/Hastlayer/Hast.Transformer/Models/ArraySize.cs +++ b/src/Hastlayer/Hast.Transformer/Models/ArraySize.cs @@ -1,11 +1,11 @@ -using System; +using System; using System.Diagnostics; namespace Hast.Transformer.Models; [DebuggerDisplay("{ToString()}")] // Used in ArraySizeHolder. -internal class ArraySize : IArraySize +internal sealed class ArraySize : IArraySize { public int Length { get; set; } diff --git a/src/Hastlayer/Hast.Transformer/Models/ArraySizeHolder.cs b/src/Hastlayer/Hast.Transformer/Models/ArraySizeHolder.cs index 7eaff939..539d51ba 100644 --- a/src/Hastlayer/Hast.Transformer/Models/ArraySizeHolder.cs +++ b/src/Hastlayer/Hast.Transformer/Models/ArraySizeHolder.cs @@ -9,7 +9,7 @@ namespace Hast.Transformer.Models; -internal class ArraySizeHolder : IArraySizeHolder +internal sealed class ArraySizeHolder : IArraySizeHolder { private readonly Dictionary _arraySizes = new(); diff --git a/src/Hastlayer/Hast.Transformer/Models/DeclarationReferenceMetadata.cs b/src/Hastlayer/Hast.Transformer/Models/DeclarationReferenceMetadata.cs index 4390a637..8e6d9371 100644 --- a/src/Hastlayer/Hast.Transformer/Models/DeclarationReferenceMetadata.cs +++ b/src/Hastlayer/Hast.Transformer/Models/DeclarationReferenceMetadata.cs @@ -3,7 +3,7 @@ namespace Hast.Transformer.Models; -internal class DeclarationReferenceMetadata +internal sealed class DeclarationReferenceMetadata { public HashSet ReferencedFrom { get; private set; } public int ReferenceCount => ReferencedFrom.Count; diff --git a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesMarkingVisitor.cs b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesMarkingVisitor.cs index 10ac37f4..a1d4639d 100644 --- a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesMarkingVisitor.cs +++ b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesMarkingVisitor.cs @@ -9,7 +9,7 @@ namespace Hast.Transformer.Services.ConstantValuesSubstitution; -internal class ConstantValuesMarkingVisitor : DepthFirstAstVisitor +internal sealed class ConstantValuesMarkingVisitor : DepthFirstAstVisitor { private readonly ConstantValuesSubstitutingAstProcessor _constantValuesSubstitutingAstProcessor; private readonly IAstExpressionEvaluator _astExpressionEvaluator; diff --git a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingAstProcessor.cs b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingAstProcessor.cs index e55f099c..f2c9015f 100644 --- a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingAstProcessor.cs +++ b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingAstProcessor.cs @@ -5,7 +5,7 @@ namespace Hast.Transformer.Services.ConstantValuesSubstitution; -internal class ConstantValuesSubstitutingAstProcessor +internal sealed class ConstantValuesSubstitutingAstProcessor { public ConstantValuesTable ConstantValuesTable { get; } public ITypeDeclarationLookupTable TypeDeclarationLookupTable { get; } @@ -78,7 +78,7 @@ public void SubstituteConstantValuesInSubTree(AstNode rootNode, bool reUseOrigin } } - public class ConstructorReference + public sealed class ConstructorReference { public MethodDeclaration Constructor { get; set; } public Expression OriginalAssignmentTarget { get; set; } diff --git a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingVisitor.cs b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingVisitor.cs index c3776ccd..09aa8fc2 100644 --- a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingVisitor.cs +++ b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingVisitor.cs @@ -9,7 +9,7 @@ namespace Hast.Transformer.Services.ConstantValuesSubstitution; -internal class ConstantValuesSubstitutingVisitor : DepthFirstAstVisitor +internal sealed class ConstantValuesSubstitutingVisitor : DepthFirstAstVisitor { private readonly ConstantValuesSubstitutingAstProcessor _constantValuesSubstitutingAstProcessor; private readonly ConstantValuesTable _constantValuesTable; diff --git a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesTable.cs b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesTable.cs index 7e02f26c..6d6a203f 100644 --- a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesTable.cs +++ b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesTable.cs @@ -5,7 +5,7 @@ namespace Hast.Transformer.Services.ConstantValuesSubstitution; -internal class ConstantValuesTable +internal sealed class ConstantValuesTable { // The outer dictionary is keyed by value holder names. In the inner dictionary the scope is the key and the value // is the primitive value. diff --git a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/GlobalValueHoldersHandlingVisitor.cs b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/GlobalValueHoldersHandlingVisitor.cs index 028601bf..1dbf61ba 100644 --- a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/GlobalValueHoldersHandlingVisitor.cs +++ b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/GlobalValueHoldersHandlingVisitor.cs @@ -10,7 +10,7 @@ namespace Hast.Transformer.Services.ConstantValuesSubstitution; /// what's returned from a method can only be substituted if they have a globally unique value, since these are used not /// just from a single method (in contrast to variables). Thus these need special care, handling them here. /// -internal class GlobalValueHoldersHandlingVisitor : DepthFirstAstVisitor +internal sealed class GlobalValueHoldersHandlingVisitor : DepthFirstAstVisitor { private readonly ConstantValuesTable _constantValuesTable; private readonly ITypeDeclarationLookupTable _typeDeclarationLookupTable; diff --git a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ObjectHoldersToSubstitutedConstructorsMappingVisitor.cs b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ObjectHoldersToSubstitutedConstructorsMappingVisitor.cs index acc958c4..395afa1d 100644 --- a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ObjectHoldersToSubstitutedConstructorsMappingVisitor.cs +++ b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ObjectHoldersToSubstitutedConstructorsMappingVisitor.cs @@ -6,7 +6,7 @@ namespace Hast.Transformer.Services.ConstantValuesSubstitution; -internal class ObjectHoldersToSubstitutedConstructorsMappingVisitor : DepthFirstAstVisitor +internal sealed class ObjectHoldersToSubstitutedConstructorsMappingVisitor : DepthFirstAstVisitor { private readonly ConstantValuesSubstitutingAstProcessor _constantValuesSubstitutingAstProcessor; diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/FSharpParallelAlgorithmSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/FSharpParallelAlgorithmSampleRunner.cs index 41a0d6ba..c3642e41 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/FSharpParallelAlgorithmSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/FSharpParallelAlgorithmSampleRunner.cs @@ -5,7 +5,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class FSharpParallelAlgorithmSampleRunner : ISampleRunner +internal sealed class FSharpParallelAlgorithmSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) => configuration.AddHardwareEntryPointType(); diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/Fix64CalculatorSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/Fix64CalculatorSampleRunner.cs index 301a815f..b1d3f2f2 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/Fix64CalculatorSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/Fix64CalculatorSampleRunner.cs @@ -6,7 +6,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class Fix64CalculatorSampleRunner : ISampleRunner +internal sealed class Fix64CalculatorSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) => configuration.AddHardwareEntryPointType(); diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/GenomeMatcherSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/GenomeMatcherSampleRunner.cs index 9e3317f6..77308ccd 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/GenomeMatcherSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/GenomeMatcherSampleRunner.cs @@ -4,7 +4,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class GenomeMatcherSampleRunner : ISampleRunner +internal sealed class GenomeMatcherSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) => configuration.AddHardwareEntryPointType(); diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageProcessingAlgorithmsSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageProcessingAlgorithmsSampleRunner.cs index 3fb1c008..11c6adde 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageProcessingAlgorithmsSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageProcessingAlgorithmsSampleRunner.cs @@ -9,7 +9,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class ImageProcessingAlgorithmsSampleRunner : ISampleRunner +internal sealed class ImageProcessingAlgorithmsSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) => configuration.AddHardwareEntryPointType(); diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageSharpSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageSharpSampleRunner.cs index f8d70c27..946f0cf0 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageSharpSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/ImageSharpSampleRunner.cs @@ -10,7 +10,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class ImageSharpSampleRunner : ISampleRunner +internal sealed class ImageSharpSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) => configuration.AddHardwareEntryPointType(); diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/LoopbackSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/LoopbackSampleRunner.cs index b97cd6f3..bb003931 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/LoopbackSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/LoopbackSampleRunner.cs @@ -4,7 +4,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class LoopbackSampleRunner : ISampleRunner +internal sealed class LoopbackSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) => configuration.AddHardwareEntryPointType(); diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/MemoryTestSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/MemoryTestSampleRunner.cs index b70013a2..d5bf6185 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/MemoryTestSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/MemoryTestSampleRunner.cs @@ -4,7 +4,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class MemoryTestSampleRunner : ISampleRunner +internal sealed class MemoryTestSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) => configuration.AddHardwareEntryPointType(); diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/MonteCarloPiEstimatorSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/MonteCarloPiEstimatorSampleRunner.cs index 71d1a61a..6ec046c6 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/MonteCarloPiEstimatorSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/MonteCarloPiEstimatorSampleRunner.cs @@ -8,7 +8,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class MonteCarloPiEstimatorSampleRunner : ISampleRunner +internal sealed class MonteCarloPiEstimatorSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) { diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/ObjectOrientedShowcaseSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/ObjectOrientedShowcaseSampleRunner.cs index a66631a3..9d259f07 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/ObjectOrientedShowcaseSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/ObjectOrientedShowcaseSampleRunner.cs @@ -4,7 +4,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class ObjectOrientedShowcaseSampleRunner : ISampleRunner +internal sealed class ObjectOrientedShowcaseSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) => configuration.AddHardwareEntryPointType(); diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/ParallelAlgorithmSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/ParallelAlgorithmSampleRunner.cs index 89db7e7c..a5190755 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/ParallelAlgorithmSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/ParallelAlgorithmSampleRunner.cs @@ -7,7 +7,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class ParallelAlgorithmSampleRunner : ISampleRunner +internal sealed class ParallelAlgorithmSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) => configuration.AddHardwareEntryPointType(); diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/Posit32AdvancedCalculatorSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/Posit32AdvancedCalculatorSampleRunner.cs index 20edd15f..458de99b 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/Posit32AdvancedCalculatorSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/Posit32AdvancedCalculatorSampleRunner.cs @@ -11,7 +11,7 @@ namespace Hast.Samples.Consumer.SampleRunners; [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "This application is not localized.")] -internal class Posit32AdvancedCalculatorSampleRunner : ISampleRunner +internal sealed class Posit32AdvancedCalculatorSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) => configuration.AddHardwareEntryPointType(); diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/Posit32CalculatorSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/Posit32CalculatorSampleRunner.cs index 367df460..c9577b4a 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/Posit32CalculatorSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/Posit32CalculatorSampleRunner.cs @@ -9,7 +9,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class Posit32CalculatorSampleRunner : ISampleRunner +internal sealed class Posit32CalculatorSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) => configuration.AddHardwareEntryPointType(); diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/Posit32FusedCalculatorSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/Posit32FusedCalculatorSampleRunner.cs index fc51125c..2ff790ae 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/Posit32FusedCalculatorSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/Posit32FusedCalculatorSampleRunner.cs @@ -9,7 +9,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class Posit32FusedCalculatorSampleRunner : ISampleRunner +internal sealed class Posit32FusedCalculatorSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) { diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/PositCalculatorSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/PositCalculatorSampleRunner.cs index 96fe4281..9b548072 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/PositCalculatorSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/PositCalculatorSampleRunner.cs @@ -8,7 +8,7 @@ namespace Hast.Samples.Consumer.SampleRunners; /// /// See for a more usable example. /// -internal class PositCalculatorSampleRunner : ISampleRunner +internal sealed class PositCalculatorSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) { diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/PrimeCalculatorSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/PrimeCalculatorSampleRunner.cs index 813efad9..7aa855c7 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/PrimeCalculatorSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/PrimeCalculatorSampleRunner.cs @@ -8,7 +8,7 @@ namespace Hast.Samples.Consumer.SampleRunners; [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "This application is not localized.")] -internal class PrimeCalculatorSampleRunner : ISampleRunner +internal sealed class PrimeCalculatorSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) => // You can add complete types whose methods you'd like to invoke on the hardware from the outside like this. diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/RecursiveAlgorithmsSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/RecursiveAlgorithmsSampleRunner.cs index 6eabd767..54d05098 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/RecursiveAlgorithmsSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/RecursiveAlgorithmsSampleRunner.cs @@ -5,7 +5,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class RecursiveAlgorithmsSampleRunner : ISampleRunner +internal sealed class RecursiveAlgorithmsSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) { diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/SimdCalculatorSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/SimdCalculatorSampleRunner.cs index 483651fc..7a017fce 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/SimdCalculatorSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/SimdCalculatorSampleRunner.cs @@ -7,7 +7,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class SimdCalculatorSampleRunner : ISampleRunner +internal sealed class SimdCalculatorSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) => configuration.AddHardwareEntryPointType(); diff --git a/src/Samples/Hast.Samples.Consumer/SampleRunners/UnumCalculatorSampleRunner.cs b/src/Samples/Hast.Samples.Consumer/SampleRunners/UnumCalculatorSampleRunner.cs index 0e46fb40..15e10931 100644 --- a/src/Samples/Hast.Samples.Consumer/SampleRunners/UnumCalculatorSampleRunner.cs +++ b/src/Samples/Hast.Samples.Consumer/SampleRunners/UnumCalculatorSampleRunner.cs @@ -5,7 +5,7 @@ namespace Hast.Samples.Consumer.SampleRunners; -internal class UnumCalculatorSampleRunner : ISampleRunner +internal sealed class UnumCalculatorSampleRunner : ISampleRunner { public void Configure(HardwareGenerationConfiguration configuration) { From 161fb82604ae03ca601204b8e736d0c835bfa8ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 12:57:59 +0200 Subject: [PATCH 05/53] Fix CA1852 (Type can be sealed because it has no subtypes in its containing assembly and is not externally visible). --- .../Resize/HastlayerResizeProcessor{TPixel}.cs | 2 +- .../ImageSharpModifications/Resize/ResizeProcessor{TPixel}.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/HastlayerResizeProcessor{TPixel}.cs b/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/HastlayerResizeProcessor{TPixel}.cs index 92685945..b7b2180a 100644 --- a/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/HastlayerResizeProcessor{TPixel}.cs +++ b/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/HastlayerResizeProcessor{TPixel}.cs @@ -15,7 +15,7 @@ namespace Hast.Samples.SampleAssembly.ImageSharpModifications.Resize; -internal class HastlayerResizeProcessor : TransformProcessor, IResamplingTransformImageProcessor +internal sealed class HastlayerResizeProcessor : TransformProcessor, IResamplingTransformImageProcessor where TPixel : unmanaged, IPixel { private readonly int _destinationWidth; diff --git a/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/ResizeProcessor{TPixel}.cs b/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/ResizeProcessor{TPixel}.cs index c994c08f..08c97210 100644 --- a/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/ResizeProcessor{TPixel}.cs +++ b/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/ResizeProcessor{TPixel}.cs @@ -16,7 +16,7 @@ namespace Hast.Samples.SampleAssembly.ImageSharpModifications.Resize; -internal class ResizeProcessor : TransformProcessor, IResamplingTransformImageProcessor +internal sealed class ResizeProcessor : TransformProcessor, IResamplingTransformImageProcessor where TPixel : unmanaged, IPixel { private readonly int _destinationWidth; From 05383c500429c45223eabc260f9ca49157944309 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 13:40:56 +0200 Subject: [PATCH 06/53] Fix MA0075 (Do not use implicit culture-sensitive ToString). --- .../Services/EthernetCommunicationService.cs | 2 +- .../ConstantValuesSubstitutingAstProcessor.cs | 11 ++++++----- .../Hast.Transformer/Services/MethodInliner.cs | 7 ++++--- .../Representation/Declaration/String.cs | 3 ++- .../Hast.Samples.SampleAssembly/Fix64Calculator.cs | 6 +++--- .../Hast.Samples.SampleAssembly/Posit32Calculator.cs | 7 ++++--- 6 files changed, 20 insertions(+), 16 deletions(-) diff --git a/src/Hastlayer/Hast.Communication/Services/EthernetCommunicationService.cs b/src/Hastlayer/Hast.Communication/Services/EthernetCommunicationService.cs index cad3920b..91dfeba6 100644 --- a/src/Hastlayer/Hast.Communication/Services/EthernetCommunicationService.cs +++ b/src/Hastlayer/Hast.Communication/Services/EthernetCommunicationService.cs @@ -90,7 +90,7 @@ public override async Task ExecuteAsync( { throw new EthernetCommunicationException( "Awaited a ready signal from the FPGA after the execution byte was sent but received the following byte instead: " + - executionCommandTypeResponseByte[0]); + executionCommandTypeResponseByte[0].ToTechnicalString()); } // Here we put together the data stream. diff --git a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingAstProcessor.cs b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingAstProcessor.cs index f2c9015f..4877a31b 100644 --- a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingAstProcessor.cs +++ b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingAstProcessor.cs @@ -1,5 +1,6 @@ using Hast.Transformer.Models; using ICSharpCode.Decompiler.CSharp.Syntax; +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Collections.Generic; @@ -69,12 +70,12 @@ public void SubstituteConstantValuesInSubTree(AstNode rootNode, bool reUseOrigin constantValuesMarkingVisitor.HiddenlyUpdatedNodesUpdated.Count != hiddenlyUpdatedNodesUpdatedCount) && passCount < maxPassCount); - if (passCount == maxPassCount) + if (passCount >= maxPassCount) { - throw new InvalidOperationException( - "Constant substitution needs more than " + maxPassCount + - "passes through the syntax tree starting with the root node " + rootNode.GetFullName() + - ". This most possibly indicates some error or the assembly being processed is exceptionally big."); + throw new InvalidOperationException(StringHelper.CreateInvariant( + $"Constant substitution needs more than {maxPassCount} passes through the syntax tree starting with " + + $"the root node {rootNode.GetFullName()}. This most possibly indicates some error or the assembly " + + $"being processed is exceptionally big.")); } } diff --git a/src/Hastlayer/Hast.Transformer/Services/MethodInliner.cs b/src/Hastlayer/Hast.Transformer/Services/MethodInliner.cs index 23862be3..3753ef09 100644 --- a/src/Hastlayer/Hast.Transformer/Services/MethodInliner.cs +++ b/src/Hastlayer/Hast.Transformer/Services/MethodInliner.cs @@ -5,6 +5,7 @@ using Hast.Transformer.Models; using ICSharpCode.Decompiler.CSharp.Syntax; using ICSharpCode.Decompiler.TypeSystem; +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Collections.Generic; using System.Linq; @@ -79,9 +80,9 @@ public void Convert( if (passCount == maxPassCount) { - throw new InvalidOperationException( - "Method inlining needs more than " + maxPassCount + - " passes through the syntax tree. This most possibly indicates some error or the assembly being processed is exceptionally big."); + throw new InvalidOperationException(StringHelper.CreateInvariant( + $"Method inlining needs more than {maxPassCount} passes through the syntax tree. This most possibly " + + $"indicates some error or the assembly being processed is exceptionally big.")); } } diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/String.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/String.cs index b12971cb..824f1aae 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/String.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/String.cs @@ -1,3 +1,4 @@ +using Lombiq.HelpfulLibraries.Common.Utilities; using System.Diagnostics; namespace Hast.VhdlBuilder.Representation.Declaration; @@ -15,5 +16,5 @@ public String() } public override string ToVhdl(IVhdlGenerationOptions vhdlGenerationOptions) => - "string" + (Length > 0 ? "(1 to " + Length + ")" : string.Empty); + Length > 0 ? StringHelper.CreateInvariant($"string(1 to {Length})") : "string"; } diff --git a/src/Samples/Hast.Samples.SampleAssembly/Fix64Calculator.cs b/src/Samples/Hast.Samples.SampleAssembly/Fix64Calculator.cs index 879b1acc..9e6ba86f 100644 --- a/src/Samples/Hast.Samples.SampleAssembly/Fix64Calculator.cs +++ b/src/Samples/Hast.Samples.SampleAssembly/Fix64Calculator.cs @@ -1,6 +1,7 @@ using Hast.Algorithms; using Hast.Layer; using Hast.Transformer.SimpleMemory; +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Collections.Generic; using System.Threading.Tasks; @@ -101,9 +102,8 @@ public IEnumerable ParallelizedCalculateIntegerSumUpToNumbers( { if (numbers.Length != MaxDegreeOfParallelism) { - throw new ArgumentException( - $"Provide as many {nameof(numbers)} as the degree of parallelism of Fix64Calculator is (" + - MaxDegreeOfParallelism + ")"); + throw new ArgumentException(StringHelper.CreateInvariant( + $"Provide as many {nameof(numbers)} as the degree of parallelism of Fix64Calculator is ({MaxDegreeOfParallelism})")); } var memory = hastlayer is null ? diff --git a/src/Samples/Hast.Samples.SampleAssembly/Posit32Calculator.cs b/src/Samples/Hast.Samples.SampleAssembly/Posit32Calculator.cs index 03d7884a..828c5564 100644 --- a/src/Samples/Hast.Samples.SampleAssembly/Posit32Calculator.cs +++ b/src/Samples/Hast.Samples.SampleAssembly/Posit32Calculator.cs @@ -1,6 +1,7 @@ using Hast.Layer; using Hast.Transformer.SimpleMemory; using Lombiq.Arithmetics; +using Lombiq.HelpfulLibraries.Common.Utilities; using System; using System.Collections.Generic; using System.Threading.Tasks; @@ -154,9 +155,9 @@ public static IEnumerable ParallelizedCalculateIntegerSumUpToNumbers( { if (numbers.Length != Posit32Calculator.MaxDegreeOfParallelism) { - throw new ArgumentException( - $"Provide as many {nameof(numbers)} as the degree of parallelism of Posit32Calculator is (" + - Posit32Calculator.MaxDegreeOfParallelism + ")"); + throw new ArgumentException(StringHelper.CreateInvariant( + $"Provide as many {nameof(numbers)} as the degree of parallelism of Posit32Calculator is " + + $"({Posit32Calculator.MaxDegreeOfParallelism})")); } var memory = hastlayer is null From a218b320a855f1370a561c9740903cb686e9f07f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 14:04:49 +0200 Subject: [PATCH 07/53] Disable S2094 (Classes should not be empty). --- .../Hast.Catapult/Models/CatapultDeviceManifest.cs | 7 ++++++- .../Hast.Transformer/Extensions/AstNodeExtensions.cs | 5 +++++ src/Hastlayer/Hast.Xilinx/XilinxDeviceManifest.cs | 2 ++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/Hastlayer/Hast.Catapult/Models/CatapultDeviceManifest.cs b/src/Hastlayer/Hast.Catapult/Models/CatapultDeviceManifest.cs index 0f384810..5c376930 100644 --- a/src/Hastlayer/Hast.Catapult/Models/CatapultDeviceManifest.cs +++ b/src/Hastlayer/Hast.Catapult/Models/CatapultDeviceManifest.cs @@ -1,7 +1,12 @@ -using Hast.Synthesis.Models; +using Hast.Synthesis.Models; +using System.Diagnostics.CodeAnalysis; namespace Hast.Catapult.Models; +[SuppressMessage( + "Minor Code Smell", + "S2094:Classes should not be empty", + Justification = "The type is used to indetify the device.")] public class CatapultDeviceManifest : DeviceManifest { } diff --git a/src/Hastlayer/Hast.Transformer/Extensions/AstNodeExtensions.cs b/src/Hastlayer/Hast.Transformer/Extensions/AstNodeExtensions.cs index 90e6f3cb..a2a35012 100644 --- a/src/Hastlayer/Hast.Transformer/Extensions/AstNodeExtensions.cs +++ b/src/Hastlayer/Hast.Transformer/Extensions/AstNodeExtensions.cs @@ -4,6 +4,7 @@ using ICSharpCode.Decompiler.TypeSystem; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; @@ -345,6 +346,10 @@ private static string GetFullNameOfUnknownNode(AstNode node) return node.CreateNameForUnnamedNode(); } + [SuppressMessage( + "Minor Code Smell", + "S2094:Classes should not be empty", + Justification = "Only used for annotation.")] private sealed class WasRemoved { } diff --git a/src/Hastlayer/Hast.Xilinx/XilinxDeviceManifest.cs b/src/Hastlayer/Hast.Xilinx/XilinxDeviceManifest.cs index d7d9fc90..5c03bc4f 100644 --- a/src/Hastlayer/Hast.Xilinx/XilinxDeviceManifest.cs +++ b/src/Hastlayer/Hast.Xilinx/XilinxDeviceManifest.cs @@ -4,6 +4,8 @@ namespace Hast.Xilinx; +#pragma warning disable S2094 // Classes should not be empty, but here only the type is used to identify the device. + public class XilinxDeviceManifest : DeviceManifest { } From f58146484984c07b6f5c9888eab517baf6afbf4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 14:12:49 +0200 Subject: [PATCH 08/53] Fix CA1854 (Prefer a 'TryGetValue' call over a Dictionary indexer access guarded by a 'ContainsKey' check to avoid double lookup). --- src/Hastlayer/Hast.Catapult/CatapultLibrary.cs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs b/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs index f4005a32..0b898900 100644 --- a/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs +++ b/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs @@ -180,13 +180,9 @@ public static CatapultLibrary Create( ILogger logger, int endpointNumber = Constants.PcieHipNumber) { - var libraryPath = config.ContainsKey(Constants.ConfigKeys.LibraryPath) ? - config[Constants.ConfigKeys.LibraryPath] ?? Constants.DefaultLibraryPath : - Constants.DefaultLibraryPath; - var versionDefinitionsFile = config.ContainsKey(Constants.ConfigKeys.VersionDefinitionsFile) ? - config[Constants.ConfigKeys.VersionDefinitionsFile] : null; - var versionManifestFile = config.ContainsKey(Constants.ConfigKeys.VersionManifestFile) ? - config[Constants.ConfigKeys.VersionManifestFile] : null; + var libraryPath = GetOrDefault(config, Constants.ConfigKeys.LibraryPath, Constants.DefaultLibraryPath); + var versionDefinitionsFile = GetOrDefault(config, Constants.ConfigKeys.VersionDefinitionsFile); + var versionManifestFile = GetOrDefault(config, Constants.ConfigKeys.VersionManifestFile); return new CatapultLibrary( (string)libraryPath, @@ -551,4 +547,9 @@ private void LogLineInvariant(Constants.Log level, FormattableString text) => LogFunction?.Invoke((uint)level, text.ToString(CultureInfo.InvariantCulture) + Environment.NewLine); public override string ToString() => InstanceName; + + private static object GetOrDefault(IDictionary config, string key, object fallback = null) => + config.TryGetValue(key, out var result) + ? result ?? fallback + : fallback; } From 66ed7b2a108336a5bdacb1ddf892ff7206b13d77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 14:25:51 +0200 Subject: [PATCH 09/53] Fix S3878 (Remove this array creation and simply pass the elements). --- .../Testing/VhdlStructureAssertionFailedException.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Hastlayer/Hast.VhdlBuilder/Testing/VhdlStructureAssertionFailedException.cs b/src/Hastlayer/Hast.VhdlBuilder/Testing/VhdlStructureAssertionFailedException.cs index 3d86b52e..671f60a0 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Testing/VhdlStructureAssertionFailedException.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Testing/VhdlStructureAssertionFailedException.cs @@ -12,8 +12,7 @@ public class VhdlStructureAssertionFailedException : Exception public string CodeExcerpt { get; set; } - public override string Message => - string.Join(Environment.NewLine, new[] { Description, "Affected code:", CodeExcerpt }); + public override string Message => string.Join(Environment.NewLine, Description, "Affected code:", CodeExcerpt); public VhdlStructureAssertionFailedException() { } From 57c10980357d3390b771b012cfa05de0ab0e7d72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 14:28:17 +0200 Subject: [PATCH 10/53] Fix S6602 ("Find" method should be used instead of the "FirstOrDefault" extension method). --- src/Hastlayer/Hast.Communication.Tester/Program.cs | 6 +++--- src/Samples/Hast.Samples.Consumer/Program.cs | 7 +++---- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/Hastlayer/Hast.Communication.Tester/Program.cs b/src/Hastlayer/Hast.Communication.Tester/Program.cs index ce8215b4..fbffd402 100644 --- a/src/Hastlayer/Hast.Communication.Tester/Program.cs +++ b/src/Hastlayer/Hast.Communication.Tester/Program.cs @@ -65,9 +65,9 @@ private static async Task MainTaskAsync(IServiceProvider provider) } // Try to load selected device or pick the first available if none were selected. - if (string.IsNullOrEmpty(CommandLineOptions.DeviceName)) CommandLineOptions.DeviceName = devices.First().Name; - var selectedDevice = devices.FirstOrDefault(device => device.Name == CommandLineOptions.DeviceName); - if (selectedDevice == null) throw new InvalidOperationException($"Target device '{CommandLineOptions.DeviceName}' not found!"); + if (string.IsNullOrEmpty(CommandLineOptions.DeviceName)) CommandLineOptions.DeviceName = devices[0].Name; + var selectedDevice = devices.Find(device => device.Name == CommandLineOptions.DeviceName) ?? + throw new InvalidOperationException($"Target device '{CommandLineOptions.DeviceName}' not found!"); var channelName = selectedDevice.DefaultCommunicationChannelName; var prepend = Array.Empty(); diff --git a/src/Samples/Hast.Samples.Consumer/Program.cs b/src/Samples/Hast.Samples.Consumer/Program.cs index 91c115b9..e1361b7e 100644 --- a/src/Samples/Hast.Samples.Consumer/Program.cs +++ b/src/Samples/Hast.Samples.Consumer/Program.cs @@ -72,10 +72,9 @@ private static async Task MainTaskAsync(string[] args) if (devices == null || !devices.Any()) throw new InvalidOperationException("No devices are available!"); // Let's just use the first one that is available unless it's specified. - var targetDeviceName = consumerConfiguration.DeviceName.OrIfEmpty(devices.First().Name); - var selectedDevice = devices.FirstOrDefault(device => device.Name == targetDeviceName); - if (selectedDevice == null) throw new InvalidOperationException($"Target device '{targetDeviceName}' not found!"); - + var targetDeviceName = consumerConfiguration.DeviceName.OrIfEmpty(devices[0].Name); + var selectedDevice = devices.Find(device => device.Name == targetDeviceName) ?? + throw new InvalidOperationException($"Target device '{targetDeviceName}' not found!"); var configuration = new HardwareGenerationConfiguration(selectedDevice.Name, consumerConfiguration.HardwareFrameworkPath); var proxyConfiguration = new ProxyGenerationConfiguration { From da0e2ca89840fdededaf56b7c907599dcdd28644 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 14:30:15 +0200 Subject: [PATCH 11/53] Fix S6603 (The collection-specific "TrueForAll" method should be used instead of the "All" extension). --- src/Hastlayer/Hast.Layer/Extensions/ConfigurationExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Hastlayer/Hast.Layer/Extensions/ConfigurationExtensions.cs b/src/Hastlayer/Hast.Layer/Extensions/ConfigurationExtensions.cs index 305f3af9..b42b1665 100644 --- a/src/Hastlayer/Hast.Layer/Extensions/ConfigurationExtensions.cs +++ b/src/Hastlayer/Hast.Layer/Extensions/ConfigurationExtensions.cs @@ -62,7 +62,7 @@ private static void ReplaceWithArray(ExpandoObject parent, string keyInParent, E var keys = inputDictionary.Keys.ToArray(); // It's an array if all keys are integers. - if (keys.All(key => int.TryParse(key, out var index) && index >= 0 && index < keys.Length)) + if (keys.TrueForAll(key => int.TryParse(key, out var index) && index >= 0 && index < keys.Length)) { var array = new object[keys.Length]; foreach (var (key, value) in inputDictionary) From f61b91ae88c8696dfe56a8d08442dbc377810e97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 14:31:26 +0200 Subject: [PATCH 12/53] Fix S6605 (Collection-specific "Exists" method should be used instead of the "Any"). --- src/Hastlayer/Hast.Console/Program.cs | 2 +- src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs | 3 +-- .../InvocationProxyBuilders/InvocationProxyBuilder.cs | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Hastlayer/Hast.Console/Program.cs b/src/Hastlayer/Hast.Console/Program.cs index c4e62308..71f3e38e 100644 --- a/src/Hastlayer/Hast.Console/Program.cs +++ b/src/Hastlayer/Hast.Console/Program.cs @@ -40,7 +40,7 @@ private static void HandleParseError(IEnumerable errors) // This is from an interactive Console, we want to exit. #pragma warning disable S1147 // Exit methods should not be called - if (errorList.Any(error => error.Tag == ErrorType.HelpRequestedError)) Environment.Exit(0); + if (errorList.Exists(error => error.Tag == ErrorType.HelpRequestedError)) Environment.Exit(0); #pragma warning restore S1147 // Exit methods should not be called if (errorList.Any()) diff --git a/src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs b/src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs index 7911a99b..d6cce37f 100644 --- a/src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs +++ b/src/Hastlayer/Hast.Synthesis/Services/BuildLogger.cs @@ -8,7 +8,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Text; using System.Threading.Tasks; using static Lombiq.HelpfulLibraries.Common.Utilities.FileSystemHelper; @@ -124,7 +123,7 @@ private void Log(LogLevel logLevel, string name, object message, string buildLog } //// Raise the v++ status outputs like "[21:17:26] Phase 1 Build RT Design" trough the Progress event. - if (name == Vpp && text?.StartsWithOrdinal("[") == true && _vppStatusLogs.Any(fragment => text.Contains(fragment))) + if (name == Vpp && text?.StartsWithOrdinal("[") == true && _vppStatusLogs.Exists(text.Contains)) { if (logLevel < LogLevel.Information) logLevel = LogLevel.Information; _progressInvoker.InvokeProgress(new BuildProgressEventArgs(text)); diff --git a/src/Hastlayer/Hast.Transformer.Vhdl/InvocationProxyBuilders/InvocationProxyBuilder.cs b/src/Hastlayer/Hast.Transformer.Vhdl/InvocationProxyBuilders/InvocationProxyBuilder.cs index 22f9b758..1a1eb4d5 100644 --- a/src/Hastlayer/Hast.Transformer.Vhdl/InvocationProxyBuilders/InvocationProxyBuilder.cs +++ b/src/Hastlayer/Hast.Transformer.Vhdl/InvocationProxyBuilders/InvocationProxyBuilder.cs @@ -93,7 +93,7 @@ public IEnumerable BuildInternalProxy( // are a sufficient number of target components available? Then we can pair them together. var invocationsCanBePaired = !invokedFromSingleComponent && - !invokedFromComponents.Any(componentInvocation => componentInvocation.Value > 1) && + !invokedFromComponents.Exists(componentInvocation => componentInvocation.Value > 1) && invokedFromComponents.Sum(invokingComponent => invokingComponent.Value) <= targetComponentCount; if (invokedFromSingleComponent || invocationsCanBePaired) From aaf7b3a0356f417519fd6332127780b2195d2f1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 14:36:29 +0200 Subject: [PATCH 13/53] Fix S6608 (Indexing at 0 or ^1 should be used instead of the "Enumerable" extension method "First" or "Last"). --- .../Hast.Transformer.Vhdl/Helpers/BinaryChainBuilder.cs | 4 ++-- src/Hastlayer/Hast.Transformer/DefaultTransformer.cs | 2 +- .../Hast.VhdlBuilder/Representation/VhdlGenerationOptions.cs | 2 +- .../BasicHardwareStructureTests.cs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Hastlayer/Hast.Transformer.Vhdl/Helpers/BinaryChainBuilder.cs b/src/Hastlayer/Hast.Transformer.Vhdl/Helpers/BinaryChainBuilder.cs index 13bba310..bc91846d 100644 --- a/src/Hastlayer/Hast.Transformer.Vhdl/Helpers/BinaryChainBuilder.cs +++ b/src/Hastlayer/Hast.Transformer.Vhdl/Helpers/BinaryChainBuilder.cs @@ -13,14 +13,14 @@ public static IVhdlElement BuildBinaryChain(IEnumerable expression if (!expressionsList.Any()) return Empty.Instance; - var chainExpression = expressionsList.First(); + var chainExpression = expressionsList[0]; // Iteratively build a binary expression chain to. if (expressionsList.Count > 1) { var currentBinary = new Binary { - Left = expressionsList.Skip(1).First(), + Left = expressionsList[1], Operator = binaryOperator, }; diff --git a/src/Hastlayer/Hast.Transformer/DefaultTransformer.cs b/src/Hastlayer/Hast.Transformer/DefaultTransformer.cs index 63d5de70..c5a08c8e 100644 --- a/src/Hastlayer/Hast.Transformer/DefaultTransformer.cs +++ b/src/Hastlayer/Hast.Transformer/DefaultTransformer.cs @@ -214,7 +214,7 @@ await _transformationContextCacheService.ExecuteTransformationContextIfAnyAsync( } // Since this is about known (i.e. .NET built-in) types it doesn't matter which type system we use. - var knownTypeLookupTable = _knownTypeLookupTableFactory.Create(decompilers.First().TypeSystem); + var knownTypeLookupTable = _knownTypeLookupTableFactory.Create(decompilers[0].TypeSystem); var arraySizeHolder = ArraySizeHolder.FromConfiguration(configuration); var convertersByName = _converters.ToDictionary(converter => converter.Name ?? converter.GetType().Name); diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/VhdlGenerationOptions.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/VhdlGenerationOptions.cs index a8554822..9d46652e 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/VhdlGenerationOptions.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/VhdlGenerationOptions.cs @@ -98,7 +98,7 @@ private static string NameShortenerMatch(Match match) var shortenedParameters = string.Join(',', arguments .Split(',') - .Select(parameter => parameter.Split('.').Last())); + .Select(parameter => parameter.Split('.')[^1])); shortName = $"{before}({shortenedParameters}){after}"; } diff --git a/test/Hast.Transformer.Vhdl.Tests/BasicHardwareStructureTests.cs b/test/Hast.Transformer.Vhdl.Tests/BasicHardwareStructureTests.cs index 7c021280..0cb08f38 100644 --- a/test/Hast.Transformer.Vhdl.Tests/BasicHardwareStructureTests.cs +++ b/test/Hast.Transformer.Vhdl.Tests/BasicHardwareStructureTests.cs @@ -46,7 +46,7 @@ public Task BasicVhdlStructureIsCorrect() return Host.RunAsync(async transformer => { await TransformClassStrutureExamplesToVhdlAsync(transformer); - var topModule = (Module)manifest.Modules.Last(); + var topModule = (Module)manifest.Modules[^1]; var architecture = topModule.Architecture; architecture.Name.ShouldNotBeNullOrEmpty(); From 2431e70792a58b309ff4580356f1f53f0780dd20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 15:04:56 +0200 Subject: [PATCH 14/53] Fix S2589 (Change this condition so that it does not always evaluate to 'True'). --- src/Hastlayer/Hast.Algorithms/Fix64.cs | 8 +------- src/Hastlayer/Hast.Console/Program.cs | 2 +- .../ConstantValuesSubstitutingVisitor.cs | 2 +- src/Hastlayer/Hast.Transformer/Services/MethodInliner.cs | 2 +- src/Libraries/External/Lombiq.Arithmetics | 2 +- 5 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/Hastlayer/Hast.Algorithms/Fix64.cs b/src/Hastlayer/Hast.Algorithms/Fix64.cs index 2816d6bf..f855ca33 100644 --- a/src/Hastlayer/Hast.Algorithms/Fix64.cs +++ b/src/Hastlayer/Hast.Algorithms/Fix64.cs @@ -104,13 +104,7 @@ public int[] ToIntegers() /// Returns a number indicating the sign of a Fix64 number. Returns 1 if the value is positive, 0 if is 0, and -1 if /// it is negative. /// - public static int Sign(Fix64 value) => - value.RawValue switch - { - { } when value.RawValue < 0 => -1, - { } when value.RawValue > 0 => 1, - _ => 0, - }; + public static int Sign(Fix64 value) => Math.Sign(value.RawValue); /// /// Returns the absolute value of a Fix64 number. Note: Abs(Fix64.MinValue) == Fix64.MaxValue. diff --git a/src/Hastlayer/Hast.Console/Program.cs b/src/Hastlayer/Hast.Console/Program.cs index 71f3e38e..7d7f711e 100644 --- a/src/Hastlayer/Hast.Console/Program.cs +++ b/src/Hastlayer/Hast.Console/Program.cs @@ -24,7 +24,7 @@ private static void RunOptions(MainOptions mainOptions) WriteLine("Subcommands:\n* {0}", allSubcommands); } else if (mainOptions.Subcommand?.ToUpperInvariant() is { } name && - _subcommands.SingleOrDefault(sub => sub.Key.ToUpperInvariant() == name) is { }) + _subcommands.Any(sub => sub.Key.ToUpperInvariant() == name)) { WriteLine("Please put the subcommand name as the first argument!"); } diff --git a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingVisitor.cs b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingVisitor.cs index 09aa8fc2..8e06c31d 100644 --- a/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingVisitor.cs +++ b/src/Hastlayer/Hast.Transformer/Services/ConstantValuesSubstitution/ConstantValuesSubstitutingVisitor.cs @@ -421,7 +421,7 @@ public override void VisitAssignmentExpression(AssignmentExpression assignmentEx { ConstantValuesTable.MarkAsNonConstant(assignmentExpression.Left, _constructor); } - else if (right != null) + else { ConstantValuesTable.MarkAsPotentiallyConstant(assignmentExpression.Left, right, _constructor); } diff --git a/src/Hastlayer/Hast.Transformer/Services/MethodInliner.cs b/src/Hastlayer/Hast.Transformer/Services/MethodInliner.cs index 3753ef09..6c7af1ea 100644 --- a/src/Hastlayer/Hast.Transformer/Services/MethodInliner.cs +++ b/src/Hastlayer/Hast.Transformer/Services/MethodInliner.cs @@ -78,7 +78,7 @@ public void Convert( } while (codeOutput != syntaxTree.ToString() && passCount < maxPassCount); - if (passCount == maxPassCount) + if (passCount >= maxPassCount) { throw new InvalidOperationException(StringHelper.CreateInvariant( $"Method inlining needs more than {maxPassCount} passes through the syntax tree. This most possibly " + diff --git a/src/Libraries/External/Lombiq.Arithmetics b/src/Libraries/External/Lombiq.Arithmetics index cbe87516..c4a8611b 160000 --- a/src/Libraries/External/Lombiq.Arithmetics +++ b/src/Libraries/External/Lombiq.Arithmetics @@ -1 +1 @@ -Subproject commit cbe875166ce41de67e4839bec1f94532e9be7870 +Subproject commit c4a8611b2ef3ede558aa6b109c319ccfdb1c3c2a From e91f96c1078dd36922cb707e5efdeda694d8630f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Tue, 17 Oct 2023 17:21:03 +0200 Subject: [PATCH 15/53] Use the Lazier already in HL. --- .../Services/DependencyInterfaceContainer.cs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/Hastlayer/Hast.Common/Services/DependencyInterfaceContainer.cs b/src/Hastlayer/Hast.Common/Services/DependencyInterfaceContainer.cs index e4eff1a9..034e64a6 100644 --- a/src/Hastlayer/Hast.Common/Services/DependencyInterfaceContainer.cs +++ b/src/Hastlayer/Hast.Common/Services/DependencyInterfaceContainer.cs @@ -1,4 +1,5 @@ using Hast.Common.Interfaces; +using Lombiq.HelpfulLibraries.Common.DependencyInjection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; @@ -12,15 +13,6 @@ namespace Hast.Common.Services; public static class DependencyInterfaceContainer { - // This is necessary because .Net Core Dependency Injection does not resolve Lazy out of the box. - // https://stackoverflow.com/questions/44934511/does-net-core-dependency-injection-support-lazyt - internal sealed class Lazier : Lazy - where T : class - { - public Lazier(IServiceProvider provider) - : base(provider.GetRequiredService) { } - } - [SuppressMessage( "Major Code Smell", "S3885:\"Assembly.Load\" should be used", @@ -98,7 +90,7 @@ private static ServiceLifetime RegisterImplementation( public static IServiceCollection AddExternalHastlayerDependencies(this IServiceCollection services) { - services.AddScoped(typeof(Lazy<>), typeof(Lazier<>)); + services.AddLazyInjectionSupport(); services.AddLogging(); services.AddSingleton(provider => provider.GetService().CreateLogger("Hastlayer")); services.AddMemoryCache(); From be507f5ff74b94d33929af0cddce0f4c5d548cf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 05:06:47 +0200 Subject: [PATCH 16/53] Disable analyzers for existing libraries --- src/Libraries/External/Directory.Build.props | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Libraries/External/Directory.Build.props b/src/Libraries/External/Directory.Build.props index 4d8aaa94..1c9d2688 100644 --- a/src/Libraries/External/Directory.Build.props +++ b/src/Libraries/External/Directory.Build.props @@ -1,8 +1,10 @@ - + false + false - + + From 90af3c56a51dbe80247f82cca0f2861c341215d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 06:36:06 +0200 Subject: [PATCH 17/53] docs update --- tools/Lombiq.Analyzers | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/Lombiq.Analyzers b/tools/Lombiq.Analyzers index 67d6bce3..2fabc0f9 160000 --- a/tools/Lombiq.Analyzers +++ b/tools/Lombiq.Analyzers @@ -1 +1 @@ -Subproject commit 67d6bce3a0cc6f21211013f9622376e926d5cfb2 +Subproject commit 2fabc0f9d3aae1c42cdc4db19f912d5fce61d450 From 3ffe88e705d24cce1b3f4d3d800b31a83a49909e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 06:36:36 +0200 Subject: [PATCH 18/53] Fix CA1019 (Add a public read-only property accessor for positional argument fragments of Attribute). --- .../Hast.Samples.Consumer/Attributes/HintAttribute.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/Samples/Hast.Samples.Consumer/Attributes/HintAttribute.cs b/src/Samples/Hast.Samples.Consumer/Attributes/HintAttribute.cs index e51a5b80..43c05e0f 100644 --- a/src/Samples/Hast.Samples.Consumer/Attributes/HintAttribute.cs +++ b/src/Samples/Hast.Samples.Consumer/Attributes/HintAttribute.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Linq; namespace Hast.Samples.Consumer.Attributes; @@ -11,5 +12,10 @@ public sealed class HintAttribute : Attribute { public string Text { get; } - public HintAttribute(params string[] text) => Text = string.Join(' ', text.Select(fragment => fragment.Trim())); + [SuppressMessage( + "Design", + "CA1019:Define accessors for attribute arguments", + Justification = $"They are merged together into the {nameof(Text)} property.")] + public HintAttribute(params string[] fragments) => + Text = string.Join(' ', fragments.Select(fragment => fragment.Trim())); } From 90806eae7ea9fb473fb89d89cece0d2105477332 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 06:44:30 +0200 Subject: [PATCH 19/53] Fix CA1711 (Identifiers should not have incorrect suffix). --- src/Hastlayer/Hast.Catapult/ICatapultNativeLibrary.cs | 2 ++ .../Hast.VhdlBuilder/Representation/Declaration/Attribute.cs | 2 ++ .../Hast.VhdlBuilder/Representation/Declaration/Enum.cs | 3 +++ src/Hastlayer/Hast.Vitis/Interop/Enums/OpenCl.cs | 2 ++ 4 files changed, 9 insertions(+) diff --git a/src/Hastlayer/Hast.Catapult/ICatapultNativeLibrary.cs b/src/Hastlayer/Hast.Catapult/ICatapultNativeLibrary.cs index 391b2e5e..deda0bc3 100644 --- a/src/Hastlayer/Hast.Catapult/ICatapultNativeLibrary.cs +++ b/src/Hastlayer/Hast.Catapult/ICatapultNativeLibrary.cs @@ -5,6 +5,8 @@ namespace Hast.Catapult; +#pragma warning disable CA1711 // Identifiers should not have incorrect suffix, but the names in this file refer to external resources. + /// /// The function used by logging in FpgaCoreLib.dll and the CatapultLibrary class. /// diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Attribute.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Attribute.cs index 5a45f0fe..a06089f7 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Attribute.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Attribute.cs @@ -1,8 +1,10 @@ using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace Hast.VhdlBuilder.Representation.Declaration; [DebuggerDisplay("{ToVhdl(VhdlGenerationOptions.Debug)}")] +[SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix", Justification = "Represents an attribute data type.")] public class Attribute : DataType { public DataType ValueType { get; set; } diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Enum.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Enum.cs index a35811b0..70748af4 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Enum.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Enum.cs @@ -3,10 +3,13 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace Hast.VhdlBuilder.Representation.Declaration; [DebuggerDisplay("{ToVhdl(VhdlGenerationOptions.Debug)}")] +[SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix", Justification = "Represents an enum data type.")] +[SuppressMessage("Naming", "CA1716:Identifiers should not match keywords", Justification = "Represents an enum data type.")] public class Enum : DataType { public ICollection Values { get; } = new List(); diff --git a/src/Hastlayer/Hast.Vitis/Interop/Enums/OpenCl.cs b/src/Hastlayer/Hast.Vitis/Interop/Enums/OpenCl.cs index 3ac0b97f..4cc57331 100644 --- a/src/Hastlayer/Hast.Vitis/Interop/Enums/OpenCl.cs +++ b/src/Hastlayer/Hast.Vitis/Interop/Enums/OpenCl.cs @@ -161,6 +161,7 @@ public enum DeviceTypes : ulong "Minor Code Smell", "S2344:Enumeration type names should not have \"Flags\" or \"Enum\" suffixes", Justification = "This is the name in the original library and changing it would be confusing.")] +[SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix", Justification = "Same.")] [SuppressMessage("Design", "CA1028:Enum Storage should be Int32", Justification = "The external type is ulong.")] public enum MemoryFlags : ulong { @@ -227,6 +228,7 @@ public enum MemoryFlags : ulong "Minor Code Smell", "S2344:Enumeration type names should not have \"Flags\" or \"Enum\" suffixes", Justification = "This is the name in the original library and changing it would be confusing.")] +[SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix", Justification = "Same.")] [SuppressMessage("Design", "CA1028:Enum Storage should be Int32", Justification = "The external type is ulong.")] public enum MemoryMigrationFlags : ulong { From b679d25c595e8ad8f9815bd1abed507e43102dee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 06:45:27 +0200 Subject: [PATCH 20/53] Remove file containing unused delegates. --- .../Hast.Layer/Extensibility/Events/EventHandlers.cs | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 src/Hastlayer/Hast.Layer/Extensibility/Events/EventHandlers.cs diff --git a/src/Hastlayer/Hast.Layer/Extensibility/Events/EventHandlers.cs b/src/Hastlayer/Hast.Layer/Extensibility/Events/EventHandlers.cs deleted file mode 100644 index 156b4c72..00000000 --- a/src/Hastlayer/Hast.Layer/Extensibility/Events/EventHandlers.cs +++ /dev/null @@ -1,8 +0,0 @@ -using Hast.Communication.Extensibility; -using Hast.Communication.Extensibility.Events; - -namespace Hast.Layer.Extensibility.Events; - -public delegate void ExecutedOnHardwareEventHandler(IHastlayer sender, IMemberHardwareExecutionContext e); - -public delegate void InvokingEventHandler(IHastlayer sender, IMemberInvocationContext e); From e8b10e06f737d1926e27e0d0deea898fcae90034 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 07:00:30 +0200 Subject: [PATCH 21/53] Fix CA1716 (Identifiers should not match keywords). --- .../Hast.VhdlBuilder/GlobalSuppressions.cs | 17 +++++++++++++++++ .../Representation/Declaration/Attribute.cs | 2 -- .../Representation/Declaration/Enum.cs | 3 --- .../GlobalSuppressions.cs | 5 +++++ 4 files changed, 22 insertions(+), 5 deletions(-) create mode 100644 src/Hastlayer/Hast.VhdlBuilder/GlobalSuppressions.cs diff --git a/src/Hastlayer/Hast.VhdlBuilder/GlobalSuppressions.cs b/src/Hastlayer/Hast.VhdlBuilder/GlobalSuppressions.cs new file mode 100644 index 00000000..c6b9b3ba --- /dev/null +++ b/src/Hastlayer/Hast.VhdlBuilder/GlobalSuppressions.cs @@ -0,0 +1,17 @@ +// This file is used by Code Analysis to maintain SuppressMessage +// attributes that are applied to this project. +// Project-level suppressions either have no target or are given +// a specific target and scoped to a namespace, type, member, etc. + +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage( + "Naming", + "CA1716:Identifiers should not match keywords", + Justification = "This assembly contains representations of exactly those keywords.", + Scope = "module")] +[assembly: SuppressMessage( + "Naming", + "CA1711:Identifiers should not have incorrect suffix", + Justification = "This assembly contains representations of data types including those representing the types of the suffixes in question.", + Scope = "module")] diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Attribute.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Attribute.cs index a06089f7..5a45f0fe 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Attribute.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Attribute.cs @@ -1,10 +1,8 @@ using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; namespace Hast.VhdlBuilder.Representation.Declaration; [DebuggerDisplay("{ToVhdl(VhdlGenerationOptions.Debug)}")] -[SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix", Justification = "Represents an attribute data type.")] public class Attribute : DataType { public DataType ValueType { get; set; } diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Enum.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Enum.cs index 70748af4..a35811b0 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Enum.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/Enum.cs @@ -3,13 +3,10 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; namespace Hast.VhdlBuilder.Representation.Declaration; [DebuggerDisplay("{ToVhdl(VhdlGenerationOptions.Debug)}")] -[SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix", Justification = "Represents an enum data type.")] -[SuppressMessage("Naming", "CA1716:Identifiers should not match keywords", Justification = "Represents an enum data type.")] public class Enum : DataType { public ICollection Values { get; } = new List(); diff --git a/test/TestInputAssemblies/Hast.TestInputs.Static/GlobalSuppressions.cs b/test/TestInputAssemblies/Hast.TestInputs.Static/GlobalSuppressions.cs index 80ec9e8e..4e7b8bde 100644 --- a/test/TestInputAssemblies/Hast.TestInputs.Static/GlobalSuppressions.cs +++ b/test/TestInputAssemblies/Hast.TestInputs.Static/GlobalSuppressions.cs @@ -43,3 +43,8 @@ "Usage", "VSTHRD105:Avoid method overloads that assume TaskScheduler.Current", Justification = "Can't do it without passing CancellationToken which is not supported.")] +[assembly: SuppressMessage( + "Naming", + "CA1716:Identifiers should not match keywords", + Justification = "Using single word suffix 'Static' to fit the pattern of the other test assembly names.", + Scope = "module")] From a777de9882fa9c02a064f5100f8838c03da8786c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 13:15:55 +0200 Subject: [PATCH 22/53] Add .globalconfig file. --- .globalconfig | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 .globalconfig diff --git a/.globalconfig b/.globalconfig new file mode 100644 index 00000000..9b0fca76 --- /dev/null +++ b/.globalconfig @@ -0,0 +1,9 @@ +is_global = true +global_level = 10 + +# Code analysis rules for Hastlayer, extending Lombiq.Analyzers.globalconfig. + +# Microsoft.CodeAnalysis.NetAnalyzers rules +dotnet_diagnostic.CA1062.severity = silent +dotnet_diagnostic.CA1724.severity = silent +dotnet_diagnostic.CA2007.severity = silent From 1579e42adbab9aa4782563a307f78f64a6318150 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 16:05:10 +0200 Subject: [PATCH 23/53] Add .globalconfig to the solution. --- .globalconfig | 1 + Hastlayer.SDK.sln | 1 + 2 files changed, 2 insertions(+) diff --git a/.globalconfig b/.globalconfig index 9b0fca76..190c1183 100644 --- a/.globalconfig +++ b/.globalconfig @@ -6,4 +6,5 @@ global_level = 10 # Microsoft.CodeAnalysis.NetAnalyzers rules dotnet_diagnostic.CA1062.severity = silent dotnet_diagnostic.CA1724.severity = silent +dotnet_diagnostic.CA1848.severity = none dotnet_diagnostic.CA2007.severity = silent diff --git a/Hastlayer.SDK.sln b/Hastlayer.SDK.sln index 6fe4911b..723365d5 100644 --- a/Hastlayer.SDK.sln +++ b/Hastlayer.SDK.sln @@ -66,6 +66,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution NuGet.config = NuGet.config NuGetIcon.png = NuGetIcon.png Readme.md = Readme.md + .globalconfig = .globalconfig EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Hast.Samples.Demo", "src\Samples\Hast.Samples.Demo\Hast.Samples.Demo.csproj", "{CBAC105A-E50F-4202-A647-CFD674E6C0F8}" From 2c022bb56fcdc306496c1db5ae4c50b84165c6b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 16:19:54 +0200 Subject: [PATCH 24/53] submodule --- tools/Lombiq.Analyzers | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/Lombiq.Analyzers b/tools/Lombiq.Analyzers index 2fabc0f9..4d5451c4 160000 --- a/tools/Lombiq.Analyzers +++ b/tools/Lombiq.Analyzers @@ -1 +1 @@ -Subproject commit 2fabc0f9d3aae1c42cdc4db19f912d5fce61d450 +Subproject commit 4d5451c438d4187d619ff5cfeab101002fbaed8e From 4cdd475ad50b258fb262306bb1c85606aafb8d52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 16:24:46 +0200 Subject: [PATCH 25/53] Update HL to v8.0.2. --- src/Libraries/External/Lombiq.HelpfulLibraries | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Libraries/External/Lombiq.HelpfulLibraries b/src/Libraries/External/Lombiq.HelpfulLibraries index 57171a77..c3b73200 160000 --- a/src/Libraries/External/Lombiq.HelpfulLibraries +++ b/src/Libraries/External/Lombiq.HelpfulLibraries @@ -1 +1 @@ -Subproject commit 57171a77a08b1a7ee055bc2167322188ccccde6d +Subproject commit c3b732007142c53ec45258be957fc1172dcc157a From 87b31aa41d561df4f8d4e6e3f774c30973f22ad1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 16:27:13 +0200 Subject: [PATCH 26/53] Update HL nuget. --- src/Hastlayer/Hast.Common/Hast.Common.csproj | 4 ++-- src/Hastlayer/Hast.VhdlBuilder/Hast.VhdlBuilder.csproj | 6 +++--- src/Hastlayer/Hast.Vitis/Hast.Vitis.csproj | 2 +- .../Hast.Transformer.Vhdl.Tests.Common.csproj | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Hastlayer/Hast.Common/Hast.Common.csproj b/src/Hastlayer/Hast.Common/Hast.Common.csproj index 05b95e72..24e81cf7 100644 --- a/src/Hastlayer/Hast.Common/Hast.Common.csproj +++ b/src/Hastlayer/Hast.Common/Hast.Common.csproj @@ -7,7 +7,7 @@ Lombiq;Hastlayer;FPGA;HardwareAcceleration;Performance https://github.com/Lombiq/Hastlayer-SDK/tree/dev/src/Hastlayer/Hast.Common - + @@ -19,6 +19,6 @@ - + diff --git a/src/Hastlayer/Hast.VhdlBuilder/Hast.VhdlBuilder.csproj b/src/Hastlayer/Hast.VhdlBuilder/Hast.VhdlBuilder.csproj index 07d97f58..9bea5566 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Hast.VhdlBuilder.csproj +++ b/src/Hastlayer/Hast.VhdlBuilder/Hast.VhdlBuilder.csproj @@ -8,16 +8,16 @@ Lombiq;Hastlayer;FPGA;HardwareAcceleration;Performance;VHDL;AST https://github.com/Lombiq/Hastlayer-SDK/tree/dev/src/Hastlayer/Hast.VhdlBuilder - + - + - + diff --git a/src/Hastlayer/Hast.Vitis/Hast.Vitis.csproj b/src/Hastlayer/Hast.Vitis/Hast.Vitis.csproj index 70ea2f36..b07166f8 100644 --- a/src/Hastlayer/Hast.Vitis/Hast.Vitis.csproj +++ b/src/Hastlayer/Hast.Vitis/Hast.Vitis.csproj @@ -36,7 +36,7 @@ - + diff --git a/test/Hast.Transformer.Vhdl.Tests.Common/Hast.Transformer.Vhdl.Tests.Common.csproj b/test/Hast.Transformer.Vhdl.Tests.Common/Hast.Transformer.Vhdl.Tests.Common.csproj index bcc3ec96..4b2c4a44 100644 --- a/test/Hast.Transformer.Vhdl.Tests.Common/Hast.Transformer.Vhdl.Tests.Common.csproj +++ b/test/Hast.Transformer.Vhdl.Tests.Common/Hast.Transformer.Vhdl.Tests.Common.csproj @@ -15,7 +15,7 @@ - + - + From 221050fd79d58969d048d11cb4e35ef77d158d97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 16:42:13 +0200 Subject: [PATCH 27/53] Don't put non-trivial code inside pre-processor logic. It makes maintenance unreasonably hard as you get different compile time errors/warnings depending on the build type. --- .../SimpleMemory/SimpleMemory.cs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs b/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs index a6289ecd..c5bdfd9a 100644 --- a/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs +++ b/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs @@ -1,4 +1,5 @@ using Hast.Synthesis.Models; +using Lombiq.HelpfulLibraries.Common.Utilities; using Microsoft.Extensions.Logging; using System; using System.Runtime.InteropServices; @@ -21,6 +22,13 @@ public class SimpleMemory { public const int MemoryCellSizeBytes = sizeof(int); + private const bool IsDebug = +#if DEBUG + true; +#else + false; +#endif + /// /// Gets the span of memory at the cellIndex, the length is . /// @@ -94,10 +102,9 @@ internal SimpleMemory(Memory memory, int prefixCellCount, int alignment) { memory = memory.Slice(alignmentOffset, memory.Length - alignment); } - else + else if (IsDebug) { // This should never happen in production. -#if DEBUG Console.Error.WriteLine("Alignment failed!"); Console.Error.WriteLine(" 64-bit: {0}", Environment.Is64BitProcess); Console.Error.WriteLine(" address: {0}", address); @@ -106,7 +113,9 @@ internal SimpleMemory(Memory memory, int prefixCellCount, int alignment) Console.Error.WriteLine(" alignment: {0}", alignment); Console.Error.WriteLine(" alignmentOffset: {0}", alignmentOffset); Console.Error.WriteLine(" expectedLength: {0}", expectedLength); -#else + } + else + { throw new InvalidOperationException( "Alignment failed! (" + StringHelper.CreateInvariant($"64-bit: {Environment.Is64BitProcess}; ") + @@ -116,7 +125,6 @@ internal SimpleMemory(Memory memory, int prefixCellCount, int alignment) StringHelper.CreateInvariant($"alignment: {alignment}; ") + StringHelper.CreateInvariant($"alignmentOffset: {alignmentOffset}; ") + StringHelper.CreateInvariant($"expectedLength: {expectedLength})")); -#endif } } From 1a9cff3f706041227d7d9312db8290a7955f4203 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 17:04:31 +0200 Subject: [PATCH 28/53] Doing some roundabout things to avoid preprocessor madness. --- .../Hast.Communication/Services/DevicePoolManager.cs | 2 +- .../Hast.Transformer/SimpleMemory/SimpleMemory.cs | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Hastlayer/Hast.Communication/Services/DevicePoolManager.cs b/src/Hastlayer/Hast.Communication/Services/DevicePoolManager.cs index e481e0b4..bf3c53d1 100644 --- a/src/Hastlayer/Hast.Communication/Services/DevicePoolManager.cs +++ b/src/Hastlayer/Hast.Communication/Services/DevicePoolManager.cs @@ -94,7 +94,7 @@ void Disposer(ReservedDevice thisReservedDevice) var reservationCompletionSource = new TaskCompletionSource(); - _waitQueue.Enqueue(freedUpDevice => reservationCompletionSource.SetResult(freedUpDevice)); + _waitQueue.Enqueue(reservationCompletionSource.SetResult); return reservationCompletionSource.Task; } diff --git a/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs b/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs index c5bdfd9a..34164953 100644 --- a/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs +++ b/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs @@ -79,7 +79,7 @@ public class SimpleMemory /// The alignment value. If set to greater than 0, the starting address of the content is aligned to be a multiple /// of that number. It must be an integer and power of 2. /// - internal SimpleMemory(Memory memory, int prefixCellCount, int alignment) + internal SimpleMemory(Memory memory, int prefixCellCount, int alignment, bool isDebug) { if (alignment > 0) { @@ -102,7 +102,7 @@ internal SimpleMemory(Memory memory, int prefixCellCount, int alignment) { memory = memory.Slice(alignmentOffset, memory.Length - alignment); } - else if (IsDebug) + else if (isDebug) { // This should never happen in production. Console.Error.WriteLine("Alignment failed!"); @@ -174,7 +174,7 @@ public static SimpleMemory Create(IMemoryConfiguration memoryConfiguration, int { var memory = new byte[((cellCount + memoryConfiguration.MinimumPrefix) * MemoryCellSizeBytes) + memoryConfiguration.Alignment]; - return new SimpleMemory(memory, memoryConfiguration.MinimumPrefix, memoryConfiguration.Alignment); + return new SimpleMemory(memory, memoryConfiguration.MinimumPrefix, memoryConfiguration.Alignment, IsDebug); } /// @@ -209,7 +209,7 @@ public static SimpleMemory Create( withPrefixCells = memoryConfiguration.MinimumPrefix; } - return new SimpleMemory(memory, withPrefixCells, 0); + return new SimpleMemory(memory, withPrefixCells, 0, IsDebug); } /// @@ -219,7 +219,7 @@ public static SimpleMemory Create( /// The size of the usable memory. /// The instance with a byte[] of capacity for the require payload size. public static SimpleMemory CreateSoftwareMemory(int cellCount) => - new(new byte[cellCount * MemoryCellSizeBytes], 0, 0); + new(new byte[cellCount * MemoryCellSizeBytes], 0, 0, IsDebug); } /// From 2ed2383edc03641e032d5f9607662968ce3275fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 17:17:19 +0200 Subject: [PATCH 29/53] Update Hast nuget package versions. --- NuGetTest/Hast.NuGet.Console/Hast.NuGet.Console.csproj | 4 ++-- .../Hast.Samples.SampleAssembly.csproj | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/NuGetTest/Hast.NuGet.Console/Hast.NuGet.Console.csproj b/NuGetTest/Hast.NuGet.Console/Hast.NuGet.Console.csproj index a3f1a0de..211a603e 100644 --- a/NuGetTest/Hast.NuGet.Console/Hast.NuGet.Console.csproj +++ b/NuGetTest/Hast.NuGet.Console/Hast.NuGet.Console.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/src/Samples/Hast.Samples.SampleAssembly/Hast.Samples.SampleAssembly.csproj b/src/Samples/Hast.Samples.SampleAssembly/Hast.Samples.SampleAssembly.csproj index aa7029a8..01e90436 100644 --- a/src/Samples/Hast.Samples.SampleAssembly/Hast.Samples.SampleAssembly.csproj +++ b/src/Samples/Hast.Samples.SampleAssembly/Hast.Samples.SampleAssembly.csproj @@ -12,8 +12,8 @@ - - + + From 0d23e7ee80cbc62951f65304ad40e5f9182f06b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 17:17:50 +0200 Subject: [PATCH 30/53] Fix remaining warnings ni Hastlayer.SDK.NuGet. --- NuGetTest/Hast.NuGet.Console/Program.cs | 2 +- .../Hast.Samples.SampleAssembly/PrimeCalculator.cs | 4 ++-- src/Samples/Hast.Samples.SampleAssembly/SimdCalculator.cs | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/NuGetTest/Hast.NuGet.Console/Program.cs b/NuGetTest/Hast.NuGet.Console/Program.cs index f2448ecc..9994cae0 100644 --- a/NuGetTest/Hast.NuGet.Console/Program.cs +++ b/NuGetTest/Hast.NuGet.Console/Program.cs @@ -15,7 +15,7 @@ // To cross-compile, first run without any arguments (this will throw an exception during execution), then copy the // HardwareFramework directory to the remote device and pass the binary's path as the argument, e.g.: // dotnet Hast.NuGet.Console.dll HardwareFramework/bin/*.azure.xclbin -var binaryPath = Environment.GetCommandLineArgs().FirstOrDefault(item => item.EndsWithOrdinalIgnoreCase(".xclbin")); +var binaryPath = Environment.GetCommandLineArgs().Find(item => item.EndsWithOrdinalIgnoreCase(".xclbin")); if (File.Exists(binaryPath)) { configuration.SingleBinaryPath = binaryPath; diff --git a/src/Samples/Hast.Samples.SampleAssembly/PrimeCalculator.cs b/src/Samples/Hast.Samples.SampleAssembly/PrimeCalculator.cs index 58b4ec12..52c6a92d 100644 --- a/src/Samples/Hast.Samples.SampleAssembly/PrimeCalculator.cs +++ b/src/Samples/Hast.Samples.SampleAssembly/PrimeCalculator.cs @@ -192,10 +192,10 @@ public bool IsPrimeNumberSync(uint number, IHastlayer hastlayer = null, IHardwar RunIsPrimeNumberAsync(number, memory => Task.Run(() => IsPrimeNumberSync(memory)), hastlayer, configuration).Result; public Task IsPrimeNumberAsync(uint number, IHastlayer hastlayer = null, IHardwareGenerationConfiguration configuration = null) => - RunIsPrimeNumberAsync(number, memory => IsPrimeNumberAsync(memory), hastlayer, configuration); + RunIsPrimeNumberAsync(number, IsPrimeNumberAsync, hastlayer, configuration); public bool[] ArePrimeNumbers(uint[] numbers, IHastlayer hastlayer = null, IHardwareGenerationConfiguration configuration = null) => - RunArePrimeNumbersMethod(numbers, memory => ArePrimeNumbers(memory), hastlayer, configuration); + RunArePrimeNumbersMethod(numbers, ArePrimeNumbers, hastlayer, configuration); public bool[] ParallelizedArePrimeNumbers(uint[] numbers, IHastlayer hastlayer = null, IHardwareGenerationConfiguration configuration = null) { diff --git a/src/Samples/Hast.Samples.SampleAssembly/SimdCalculator.cs b/src/Samples/Hast.Samples.SampleAssembly/SimdCalculator.cs index 4185cb73..e5863abc 100644 --- a/src/Samples/Hast.Samples.SampleAssembly/SimdCalculator.cs +++ b/src/Samples/Hast.Samples.SampleAssembly/SimdCalculator.cs @@ -115,28 +115,28 @@ private void RunSimdOperation(SimpleMemory memory, SimdOperation operation) #region Helpers public int[] AddVectors(int[] vector1, int[] vector2, IHastlayer hastlayer = null, IHardwareGenerationConfiguration configuration = null) => - RunSimdOperation(vector1, vector2, memory => AddVectors(memory), hastlayer, configuration); + RunSimdOperation(vector1, vector2, AddVectors, hastlayer, configuration); public int[] SubtractVectors( int[] vector1, int[] vector2, IHastlayer hastlayer = null, IHardwareGenerationConfiguration configuration = null) => - RunSimdOperation(vector1, vector2, memory => SubtractVectors(memory), hastlayer, configuration); + RunSimdOperation(vector1, vector2, SubtractVectors, hastlayer, configuration); public int[] MultiplyVectors( int[] vector1, int[] vector2, IHastlayer hastlayer = null, IHardwareGenerationConfiguration configuration = null) => - RunSimdOperation(vector1, vector2, memory => MultiplyVectors(memory), hastlayer, configuration); + RunSimdOperation(vector1, vector2, MultiplyVectors, hastlayer, configuration); public int[] DivideVectors( int[] vector1, int[] vector2, IHastlayer hastlayer = null, IHardwareGenerationConfiguration configuration = null) => - RunSimdOperation(vector1, vector2, memory => DivideVectors(memory), hastlayer, configuration); + RunSimdOperation(vector1, vector2, DivideVectors, hastlayer, configuration); private int[] RunSimdOperation( int[] vector1, From b6fd19d61d4d2c73d89f12065f860a4b627012df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 21:08:46 +0200 Subject: [PATCH 31/53] Misc formatting. --- .../Resize/ResizeExtensions.cs | 13 +++++++++---- src/Samples/Hast.Samples.SampleAssembly/Loopback.cs | 3 +-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/ResizeExtensions.cs b/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/ResizeExtensions.cs index 13d8bfa1..221eedb3 100644 --- a/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/ResizeExtensions.cs +++ b/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/ResizeExtensions.cs @@ -7,6 +7,7 @@ using SixLabors.ImageSharp; using SixLabors.ImageSharp.Processing; using SixLabors.ImageSharp.Processing.Processors.Transforms; +using System.Diagnostics.CodeAnalysis; namespace Hast.Samples.SampleAssembly.ImageSharpModifications.Resize; @@ -92,9 +93,14 @@ public static IImageProcessingContext HastResize( /// The to perform the resampling. /// Parameters for Hastlayer. /// The to allow chaining of operations. - /// Passing zero for one of height or width will automatically preserve the aspect ratio of the - /// original image or the nearest possible ratio. -#pragma warning disable S107 // Methods should not have too many parameters + /// + /// Passing zero for one of height or width will automatically preserve the aspect ratio of the + /// original image or the nearest possible ratio. + /// + [SuppressMessage( + "Major Code Smell", + "S107:Methods should not have too many parameters", + Justification = "All of these are necessary and wrapping them in an object wouldn't improve readability.")] public static IImageProcessingContext HastResize( this IImageProcessingContext source, int width, @@ -105,7 +111,6 @@ public static IImageProcessingContext HastResize( IHardwareRepresentation hardwareRepresentation, IProxyGenerationConfiguration configuration) => HastResize( -#pragma warning restore S107 // Methods should not have too many parameters source, width, height, diff --git a/src/Samples/Hast.Samples.SampleAssembly/Loopback.cs b/src/Samples/Hast.Samples.SampleAssembly/Loopback.cs index 592b6e07..70c76e34 100644 --- a/src/Samples/Hast.Samples.SampleAssembly/Loopback.cs +++ b/src/Samples/Hast.Samples.SampleAssembly/Loopback.cs @@ -12,9 +12,8 @@ public class Loopback { private const int RunInputOutputInt32Index = 0; + // We add 1 to the input to verify that it actually runs instead of sending back the input as-is. public virtual void Run(SimpleMemory memory) => - // Adding 1 to the input so it's visible whether this actually has run, not just the untouched data was sent - // back. memory.WriteInt32(RunInputOutputInt32Index, memory.ReadInt32(RunInputOutputInt32Index) + 1); public int Run(int input, IHastlayer hastlayer = null, IHardwareGenerationConfiguration configuration = null) From 65a6e98dd3252b439e53c3e1d7ac67bd9327004a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 22:07:20 +0200 Subject: [PATCH 32/53] Fix formatting by switching from pragma to suppression attribute. --- .../Resize/ResizeExtensions.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/ResizeExtensions.cs b/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/ResizeExtensions.cs index 221eedb3..40aad345 100644 --- a/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/ResizeExtensions.cs +++ b/src/Samples/Hast.Samples.SampleAssembly/ImageSharpModifications/Resize/ResizeExtensions.cs @@ -137,9 +137,14 @@ public static IImageProcessingContext HastResize( /// during processing. /// Parameters for Hastlayer. /// The to allow chaining of operations. - /// Passing zero for one of height or width will automatically preserve the aspect ratio of the - /// original image or the nearest possible ratio. -#pragma warning disable S107 // Methods should not have too many parameters + /// + /// Passing zero for one of height or width will automatically preserve the aspect ratio of the original image or + /// the nearest possible ratio. + /// + [SuppressMessage( + "Major Code Smell", + "S107:Methods should not have too many parameters", + Justification = "All of these are necessary and wrapping them in an object wouldn't improve readability.")] public static IImageProcessingContext HastResize( this IImageProcessingContext source, int width, @@ -151,7 +156,6 @@ public static IImageProcessingContext HastResize( IHastlayer hastlayer, IHardwareRepresentation hardwareRepresentation, IProxyGenerationConfiguration configuration) -#pragma warning restore S107 // Methods should not have too many parameters { var options = new ResizeOptions { From 8b2ebc4c0f1e42ff60ffbb2325a134ba7115d3a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 22:39:43 +0200 Subject: [PATCH 33/53] Make stuff readonly. --- src/Hastlayer/Hast.Algorithms/Fix64.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Hastlayer/Hast.Algorithms/Fix64.cs b/src/Hastlayer/Hast.Algorithms/Fix64.cs index f855ca33..e3bc9ece 100644 --- a/src/Hastlayer/Hast.Algorithms/Fix64.cs +++ b/src/Hastlayer/Hast.Algorithms/Fix64.cs @@ -41,7 +41,7 @@ namespace Hast.Algorithms; /// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /// /// -public struct Fix64 : IEquatable, IComparable +public readonly struct Fix64 : IEquatable, IComparable { private const long MaxRawValue = long.MaxValue; private const long MinRawValue = long.MinValue; @@ -79,17 +79,17 @@ public struct Fix64 : IEquatable, IComparable #region Instance methods - public override int GetHashCode() => RawValue.GetHashCode(); + public override readonly int GetHashCode() => RawValue.GetHashCode(); - public override bool Equals(object obj) => obj is Fix64 fix64 && fix64.RawValue == RawValue; + public override readonly bool Equals(object obj) => obj is Fix64 fix64 && fix64.RawValue == RawValue; - public bool Equals(Fix64 other) => RawValue == other.RawValue; + public readonly bool Equals(Fix64 other) => RawValue == other.RawValue; - public int CompareTo(Fix64 other) => RawValue.CompareTo(other.RawValue); + public readonly int CompareTo(Fix64 other) => RawValue.CompareTo(other.RawValue); - public override string ToString() => ((decimal)this).ToString(CultureInfo.InvariantCulture); + public override readonly string ToString() => ((decimal)this).ToString(CultureInfo.InvariantCulture); - public int[] ToIntegers() + public readonly int[] ToIntegers() { var low = (int)(RawValue & uint.MaxValue); int high = (int)(RawValue >> 32); From af19fd05d59211972d3050584e89b01fe4a1f472 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 22:46:06 +0200 Subject: [PATCH 34/53] Fix other IDEXXXX warnings. --- .../MultiCycleSdcStatementsAttributeExpression.cs | 1 - .../Declaration/UnconstrainedArrayInstantiation.cs | 1 - .../Representation/Expression/VectorSlice.cs | 1 - .../Hast.TestInputs.Static/ObjectUsingCases.cs | 8 +++++--- 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/MultiCycleSdcStatementsAttributeExpression.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/MultiCycleSdcStatementsAttributeExpression.cs index 61fc76dd..3277da35 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/MultiCycleSdcStatementsAttributeExpression.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/MultiCycleSdcStatementsAttributeExpression.cs @@ -1,6 +1,5 @@ using Hast.VhdlBuilder.Extensions; using Lombiq.HelpfulLibraries.Common.Utilities; -using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/UnconstrainedArrayInstantiation.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/UnconstrainedArrayInstantiation.cs index 7410a2f1..f7ae7d1c 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/UnconstrainedArrayInstantiation.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Declaration/UnconstrainedArrayInstantiation.cs @@ -1,5 +1,4 @@ using Lombiq.HelpfulLibraries.Common.Utilities; -using System; using System.Diagnostics; namespace Hast.VhdlBuilder.Representation.Declaration; diff --git a/src/Hastlayer/Hast.VhdlBuilder/Representation/Expression/VectorSlice.cs b/src/Hastlayer/Hast.VhdlBuilder/Representation/Expression/VectorSlice.cs index 781c7a20..7095830a 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/Representation/Expression/VectorSlice.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/Representation/Expression/VectorSlice.cs @@ -1,5 +1,4 @@ using Lombiq.HelpfulLibraries.Common.Utilities; -using System; using System.Diagnostics; namespace Hast.VhdlBuilder.Representation.Expression; diff --git a/test/TestInputAssemblies/Hast.TestInputs.Static/ObjectUsingCases.cs b/test/TestInputAssemblies/Hast.TestInputs.Static/ObjectUsingCases.cs index ee0f3141..ae88e69e 100644 --- a/test/TestInputAssemblies/Hast.TestInputs.Static/ObjectUsingCases.cs +++ b/test/TestInputAssemblies/Hast.TestInputs.Static/ObjectUsingCases.cs @@ -1,13 +1,15 @@ +using System.Diagnostics.CodeAnalysis; + namespace Hast.TestInputs.Static; public class ObjectUsingCases { + [SuppressMessage("Style", "IDE0270:Use coalesce expression", Justification = "We want to test this specific syntax.")] + [SuppressMessage("Style", "IDE0074:Use compound assignment", Justification = "Same.")] + [SuppressMessage("Minor Code Smell", "S3240:The simplest possible condition syntax should be used", Justification = "Same.")] public void NullUsage() { var customObject = new MyClass { MyProperty = 5 }; - // We want to test this specific syntax. -#pragma warning disable S3240 // The simplest possible condition syntax should be used -#pragma warning disable IDE0074 // Use compound assignment if (customObject == null) { customObject = new MyClass(); From acd8f103b97a65d7b00bc4e7045d575883fcbfe2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 23:04:00 +0200 Subject: [PATCH 35/53] Fix IDE0270 (Null check can be simplified). --- .../Services/DependencyInterfaceContainer.cs | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/Hastlayer/Hast.Common/Services/DependencyInterfaceContainer.cs b/src/Hastlayer/Hast.Common/Services/DependencyInterfaceContainer.cs index 034e64a6..d13a85c4 100644 --- a/src/Hastlayer/Hast.Common/Services/DependencyInterfaceContainer.cs +++ b/src/Hastlayer/Hast.Common/Services/DependencyInterfaceContainer.cs @@ -73,17 +73,11 @@ private static ServiceLifetime RegisterImplementation( } var initializerName = implementationType.GetCustomAttribute()?.MemberName; - if (!string.IsNullOrEmpty(initializerName)) - { - var method = implementationType.GetMethod(initializerName, BindingFlags.Public | BindingFlags.Static); - if (method is null) - { - throw new ArgumentException( - $"The initializer method does not exist: '{implementationType.FullName}.{initializerName}'"); - } + if (string.IsNullOrEmpty(initializerName)) return lifetime; - method.Invoke(null, new object[] { services }); - } + var method = implementationType.GetMethod(initializerName, BindingFlags.Public | BindingFlags.Static) ?? + throw new ArgumentException($"The initializer method does not exist: '{implementationType.FullName}.{initializerName}'"); + method.Invoke(null, new object[] { services }); return lifetime; } From 1647f6b9984040c968a54a1d4319db220aea2646 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 23:18:19 +0200 Subject: [PATCH 36/53] Other IDE fixes. --- .../MemberReferenceExpressionExtensions.cs | 4 ++-- .../Extensions/MethodDeclarationExtensions.cs | 2 +- .../Models/IArraySizeHolder.cs | 21 ++++++------------- ...AndUnaryOperatorExpressionsCastAdjuster.cs | 4 ++-- 4 files changed, 11 insertions(+), 20 deletions(-) diff --git a/src/Hastlayer/Hast.Transformer/Extensions/MemberReferenceExpressionExtensions.cs b/src/Hastlayer/Hast.Transformer/Extensions/MemberReferenceExpressionExtensions.cs index bb034e55..3f086d92 100644 --- a/src/Hastlayer/Hast.Transformer/Extensions/MemberReferenceExpressionExtensions.cs +++ b/src/Hastlayer/Hast.Transformer/Extensions/MemberReferenceExpressionExtensions.cs @@ -82,8 +82,8 @@ public static TypeDeclaration FindTargetTypeDeclaration( // The member is in the base class (because of single class inheritance in C#, there can be only one base // class). return memberReferenceExpression.FindFirstParentTypeDeclaration().BaseTypes - .Select(type => typeDeclarationLookupTable.Lookup(type)) - .SingleOrDefault(typeDeclaration => typeDeclaration != null && typeDeclaration.ClassType == ClassType.Class); + .Select(typeDeclarationLookupTable.Lookup) + .SingleOrDefault(typeDeclaration => typeDeclaration is { ClassType: ClassType.Class }); } if (target is IdentifierExpression or IndexerExpression) diff --git a/src/Hastlayer/Hast.Transformer/Extensions/MethodDeclarationExtensions.cs b/src/Hastlayer/Hast.Transformer/Extensions/MethodDeclarationExtensions.cs index 6bb46806..33ac55fb 100644 --- a/src/Hastlayer/Hast.Transformer/Extensions/MethodDeclarationExtensions.cs +++ b/src/Hastlayer/Hast.Transformer/Extensions/MethodDeclarationExtensions.cs @@ -5,5 +5,5 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax; public static class MethodDeclarationExtensions { public static bool IsConstructor(this MethodDeclaration methodDeclaration) => - (methodDeclaration.GetMemberResolveResult()?.Member as IMethod)?.IsConstructor == true; + methodDeclaration.GetMemberResolveResult()?.Member is IMethod { IsConstructor: true }; } diff --git a/src/Hastlayer/Hast.Transformer/Models/IArraySizeHolder.cs b/src/Hastlayer/Hast.Transformer/Models/IArraySizeHolder.cs index 90cfc447..13c557f2 100644 --- a/src/Hastlayer/Hast.Transformer/Models/IArraySizeHolder.cs +++ b/src/Hastlayer/Hast.Transformer/Models/IArraySizeHolder.cs @@ -42,19 +42,10 @@ public interface IArraySizeHolder public static class ArraySizeHolderExtensions { - public static IArraySize GetSizeOrThrow(this IArraySizeHolder arraySizeHolder, AstNode arrayHolder) - { - var size = arraySizeHolder.GetSize(arrayHolder); - - if (size == null) - { - throw new NotSupportedException( - "The length of the array holder \"" + arrayHolder.GetFullName() + "\" couldn't be statically " + - "determined. Only arrays with dimensions defined at compile-time are supported. If the array size is " + - "actually static just Hastlayer can't figure it out for some reason then you can configure it " + - "manually via TransformerConfiguration by using the quoted full name."); - } - - return size; - } + public static IArraySize GetSizeOrThrow(this IArraySizeHolder arraySizeHolder, AstNode arrayHolder) => + arraySizeHolder.GetSize(arrayHolder) ?? throw new NotSupportedException( + $"The length of the array holder \"{arrayHolder.GetFullName()}\" couldn't be statically determined. Only " + + $"arrays with dimensions defined at compile-time are supported. If the array size is actually static " + + $"just Hastlayer can't figure it out for some reason then you can configure it manually via " + + $"TransformerConfiguration by using the quoted full name."); } diff --git a/src/Hastlayer/Hast.Transformer/Services/BinaryAndUnaryOperatorExpressionsCastAdjuster.cs b/src/Hastlayer/Hast.Transformer/Services/BinaryAndUnaryOperatorExpressionsCastAdjuster.cs index 97b1e611..72a11795 100644 --- a/src/Hastlayer/Hast.Transformer/Services/BinaryAndUnaryOperatorExpressionsCastAdjuster.cs +++ b/src/Hastlayer/Hast.Transformer/Services/BinaryAndUnaryOperatorExpressionsCastAdjuster.cs @@ -236,11 +236,11 @@ void Replace(IType newType) => Replace(_knownTypeLookupTable.Lookup(KnownTypeCode.Int64)); } else if (unaryOperatorExpression.Operator == UnaryOperatorType.Minus && - ((unaryOperatorExpression.Expression as CastExpression)?.Type as PrimitiveType)?.KnownTypeCode == KnownTypeCode.UInt32) + unaryOperatorExpression.Expression is CastExpression { Type: PrimitiveType { KnownTypeCode: KnownTypeCode.UInt32 } } castExpression) { // For an int value the AST can contain -(uint)value if the original code was (uint)-value. Fixing that // here. - unaryOperatorExpression.Expression.ReplaceWith(((CastExpression)unaryOperatorExpression.Expression).Expression); + castExpression.ReplaceWith(castExpression.Expression); } } From 1e1141a88f4f59a3ea8edb71a80bbba0f6300dbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 23:44:22 +0200 Subject: [PATCH 37/53] Reorganize CommandTypes to avoid weird IDE0230 (Use UTF-8 string literal) false positive. --- .../Hast.Communication/Constants/CommandTypes.cs | 6 +++--- .../MemberInvocationHandlerFactory.cs | 16 ++++------------ .../Services/EthernetCommunicationService.cs | 6 +++--- .../Services/FpgaIpEndpointFinder.cs | 14 +++++++++----- .../Services/SerialPortCommunicationService.cs | 4 ++-- 5 files changed, 21 insertions(+), 25 deletions(-) diff --git a/src/Hastlayer/Hast.Communication/Constants/CommandTypes.cs b/src/Hastlayer/Hast.Communication/Constants/CommandTypes.cs index 4b3a2644..13efc58a 100644 --- a/src/Hastlayer/Hast.Communication/Constants/CommandTypes.cs +++ b/src/Hastlayer/Hast.Communication/Constants/CommandTypes.cs @@ -1,7 +1,7 @@ namespace Hast.Communication.Constants; -public static class CommandTypes +internal static class CommandTypes { - public const char Execution = 'x'; - public const char WhoIsAvailable = 'w'; + public static readonly byte[] Execution = "x"u8.ToArray(); + public static readonly byte[] WhoIsAvailable = "w"u8.ToArray(); } diff --git a/src/Hastlayer/Hast.Communication/MemberInvocationHandlerFactory.cs b/src/Hastlayer/Hast.Communication/MemberInvocationHandlerFactory.cs index 0f914abb..d226b81d 100644 --- a/src/Hastlayer/Hast.Communication/MemberInvocationHandlerFactory.cs +++ b/src/Hastlayer/Hast.Communication/MemberInvocationHandlerFactory.cs @@ -118,13 +118,10 @@ private async Task InvocationHandlerAsync( "\" is not supported by the current device."); } - var memory = (SimpleMemory)invocation.Arguments.SingleOrDefault(argument => argument is SimpleMemory); - if (memory == null) - { + var memory = (SimpleMemory)invocation.Arguments.SingleOrDefault(argument => argument is SimpleMemory) ?? throw new NotSupportedException( - "Only SimpleMemory-using implementations are supported for hardware execution. " + - $"The {nameof(invocation)} didn't include a SimpleMemory argument."); - } + $"Only SimpleMemory-using implementations are supported for hardware execution. The " + + $"{nameof(invocation)} didn't include a SimpleMemory argument."); if (memoryResourceCheckers.Check(memory, hardwareRepresentation) is { } problem) { @@ -179,13 +176,8 @@ private async Task InvocationHandlerAsync( var communicationService = scope .ServiceProvider .GetService() - .GetCommunicationService(communicationChannelName); - - if (communicationService == null) - { - throw new InvalidOperationException( + .GetCommunicationService(communicationChannelName) ?? throw new InvalidOperationException( $"No communication service was found for the channel \"{communicationChannelName}\"."); - } _logger.LogInformation("Starting communication service execution..."); invocationContext.HardwareExecutionInformation = await communicationService diff --git a/src/Hastlayer/Hast.Communication/Services/EthernetCommunicationService.cs b/src/Hastlayer/Hast.Communication/Services/EthernetCommunicationService.cs index 91dfeba6..f3ecf90f 100644 --- a/src/Hastlayer/Hast.Communication/Services/EthernetCommunicationService.cs +++ b/src/Hastlayer/Hast.Communication/Services/EthernetCommunicationService.cs @@ -6,6 +6,7 @@ using Hast.Transformer.SimpleMemory; using Microsoft.Extensions.Logging; using System; +using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; @@ -48,7 +49,7 @@ public override async Task ExecuteAsync( _devicePoolPopulator.PopulateDevicePoolIfNew(async () => { // Get the IP addresses of the FPGA boards. - var fpgaEndpoints = await _fpgaIpEndpointFinder.FindFpgaEndpointsAsync(); + var fpgaEndpoints = (await _fpgaIpEndpointFinder.FindFpgaEndpointsAsync()).AsList(); if (!fpgaEndpoints.Any()) { @@ -81,8 +82,7 @@ public override async Task ExecuteAsync( using var stream = client.GetStream(); // We send an execution signal to make the FPGA ready to receive the data stream. - var executionCommandTypeByte = new[] { (byte)CommandTypes.Execution }; - await stream.WriteAsync(executionCommandTypeByte.AsMemory(0, executionCommandTypeByte.Length)); + await stream.WriteAsync(CommandTypes.Execution.AsMemory(0, CommandTypes.Execution.Length)); var executionCommandTypeResponseByte = await GetBytesFromStreamAsync(stream, 1); diff --git a/src/Hastlayer/Hast.Communication/Services/FpgaIpEndpointFinder.cs b/src/Hastlayer/Hast.Communication/Services/FpgaIpEndpointFinder.cs index 28b1e784..9fce9b05 100644 --- a/src/Hastlayer/Hast.Communication/Services/FpgaIpEndpointFinder.cs +++ b/src/Hastlayer/Hast.Communication/Services/FpgaIpEndpointFinder.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Net.NetworkInformation; @@ -28,10 +29,13 @@ public FpgaIpEndpointFinder(IClock clock, ILogger logger) _logger = logger; } + [SuppressMessage( + "Style", + "IDE0230:Use UTF-8 string literal", + Justification = "False positive, shouldn't replace the char constant with a literal.")] public async Task> FindFpgaEndpointsAsync() { var broadcastEndpoint = new IPEndPoint(IPAddress.Broadcast, Ethernet.Ports.WhoIsAvailableRequest); - var inputBuffer = new[] { (byte)CommandTypes.WhoIsAvailable }; // We need retries because somehow the FPGA doesn't always catch our request. _logger.LogInformation( @@ -45,21 +49,21 @@ public async Task> FindFpgaEndpointsAsync() var endpoints = new List(); // Send request to all broadcast addresses on all the supported network interfaces. - foreach (var suppertedNetworkInterface in NetworkInterface.GetAllNetworkInterfaces() + foreach (var supportedNetworkInterface in NetworkInterface.GetAllNetworkInterfaces() .Where(networkInterface => networkInterface.OperationalStatus == OperationalStatus.Up && networkInterface.SupportsMulticast)) { // Currently we are supporting only IPv4 addresses. - var ipv4AddressInformations = suppertedNetworkInterface.GetIPProperties().UnicastAddresses + var ipv4AddressInformation = supportedNetworkInterface.GetIPProperties().UnicastAddresses .Where(addressInformation => addressInformation.Address.AddressFamily == AddressFamily.InterNetwork); - endpoints.AddRange(ipv4AddressInformations.Select(addressInformation => + endpoints.AddRange(ipv4AddressInformation.Select(addressInformation => new IPEndPoint(addressInformation.Address, Ethernet.Ports.WhoIsAvailableResponse))); } // Sending requests to all the found IP endpoints at the same time. var currentReceiveResultLists = await Task.WhenAll(endpoints.Select(endpoint => EthernetCommunicationHelpers - .UdpSendAndReceiveAllAsync(inputBuffer, endpoint, broadcastEndpoint, AvailabilityCheckerTimeout))); + .UdpSendAndReceiveAllAsync(CommandTypes.WhoIsAvailable, endpoint, broadcastEndpoint, AvailabilityCheckerTimeout))); foreach (var currentReceiveResults in currentReceiveResultLists) { receiveResults = receiveResults.Union(currentReceiveResults, new UdpReceiveResultEqualityComparer()); diff --git a/src/Hastlayer/Hast.Communication/Services/SerialPortCommunicationService.cs b/src/Hastlayer/Hast.Communication/Services/SerialPortCommunicationService.cs index d43a05eb..3e4f58ba 100644 --- a/src/Hastlayer/Hast.Communication/Services/SerialPortCommunicationService.cs +++ b/src/Hastlayer/Hast.Communication/Services/SerialPortCommunicationService.cs @@ -98,7 +98,7 @@ public override async Task ExecuteAsync( // Execute Order 66. // Set command type - var commandType = (byte)CommandTypes.Execution; + var commandType = CommandTypes.Execution[0]; MemoryMarshal.Write(memory.Span, ref commandType); // Copying the input length, represented as bytes, to the output buffer. MemoryMarshal.Write(memory.Span.Slice(1, sizeof(int)), ref memoryLength); @@ -297,7 +297,7 @@ private void TryOpenSerialPort(SerialPort serialPort) try { serialPort.Open(); - serialPort.Write(CommandTypes.WhoIsAvailable); + serialPort.Write(CommandTypes.WhoIsAvailable, offset: 0, count: CommandTypes.WhoIsAvailable.Length); } catch (IOException ex) { From da21098879c39989562a2cd8c7806b9c0534a9ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 23:45:16 +0200 Subject: [PATCH 38/53] Use pattern matching. --- .../SubTransformers/DeclarableTypeCreator.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Hastlayer/Hast.Transformer.Vhdl/SubTransformers/DeclarableTypeCreator.cs b/src/Hastlayer/Hast.Transformer.Vhdl/SubTransformers/DeclarableTypeCreator.cs index 0a9c4642..974784f0 100644 --- a/src/Hastlayer/Hast.Transformer.Vhdl/SubTransformers/DeclarableTypeCreator.cs +++ b/src/Hastlayer/Hast.Transformer.Vhdl/SubTransformers/DeclarableTypeCreator.cs @@ -15,8 +15,7 @@ public class DeclarableTypeCreator : IDeclarableTypeCreator public DataType CreateDeclarableType(AstNode valueHolder, IType type, IVhdlTransformationContext context) { - if ((valueHolder.GetMemberResolveResult()?.Member.ReturnType as ITypeDefinition)? - .KnownTypeCode == KnownTypeCode.Void) + if (valueHolder.GetMemberResolveResult()?.Member.ReturnType is ITypeDefinition { KnownTypeCode: KnownTypeCode.Void }) { return _typeConverter.ConvertAstType(new PrimitiveType("void"), context); } From 3e0f22afec6ec11f8c3f3ff1e5f590985de49383 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 23:45:57 +0200 Subject: [PATCH 39/53] unusing --- .../ArchitectureComponentNameExtensions.cs | 1 - .../ArchitectureComponents/ArchitectureComponentNameHelper.cs | 1 - 2 files changed, 2 deletions(-) diff --git a/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameExtensions.cs b/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameExtensions.cs index 66509c5b..a74cdcb0 100644 --- a/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameExtensions.cs +++ b/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameExtensions.cs @@ -1,5 +1,4 @@ using Lombiq.HelpfulLibraries.Common.Utilities; -using System; using System.Linq; namespace Hast.Transformer.Vhdl.ArchitectureComponents; diff --git a/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameHelper.cs b/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameHelper.cs index 9346b206..11ab448f 100644 --- a/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameHelper.cs +++ b/src/Hastlayer/Hast.Transformer.Vhdl/ArchitectureComponents/ArchitectureComponentNameHelper.cs @@ -1,6 +1,5 @@ using Hast.VhdlBuilder.Extensions; using Lombiq.HelpfulLibraries.Common.Utilities; -using System; namespace Hast.Transformer.Vhdl.ArchitectureComponents; From 1faaf279a8dc3f1ff71f14062e619c5e3e5be59d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Wed, 18 Oct 2023 23:56:44 +0200 Subject: [PATCH 40/53] Fix IDE0270 (Null check can be simplified). --- src/Hastlayer/Hast.Vitis/Interop/Xrt.cs | 6 ++-- ...wareImplementationComposerBuildProvider.cs | 30 +++++-------------- 2 files changed, 11 insertions(+), 25 deletions(-) diff --git a/src/Hastlayer/Hast.Vitis/Interop/Xrt.cs b/src/Hastlayer/Hast.Vitis/Interop/Xrt.cs index 61b57f8c..8281fda9 100644 --- a/src/Hastlayer/Hast.Vitis/Interop/Xrt.cs +++ b/src/Hastlayer/Hast.Vitis/Interop/Xrt.cs @@ -37,12 +37,12 @@ public static XilinxMemoryExtension Create(IntPtr data, ulong bank) => Parameters = IntPtr.Zero, }; - public bool Equals(XilinxMemoryExtension other) => + public readonly bool Equals(XilinxMemoryExtension other) => Flags == other.Flags && Object.Equals(other.Object) && Parameters.Equals(other.Parameters); - public override bool Equals(object obj) => obj is XilinxMemoryExtension other && Equals(other); + public override readonly bool Equals(object obj) => obj is XilinxMemoryExtension other && Equals(other); - public override int GetHashCode() => base.GetHashCode(); + public override readonly int GetHashCode() => base.GetHashCode(); public static bool operator ==(XilinxMemoryExtension left, XilinxMemoryExtension right) => left.Equals(right); diff --git a/src/Hastlayer/Hast.Vitis/Services/VitisHardwareImplementationComposerBuildProvider.cs b/src/Hastlayer/Hast.Vitis/Services/VitisHardwareImplementationComposerBuildProvider.cs index 9b3b517b..e57fcf59 100644 --- a/src/Hastlayer/Hast.Vitis/Services/VitisHardwareImplementationComposerBuildProvider.cs +++ b/src/Hastlayer/Hast.Vitis/Services/VitisHardwareImplementationComposerBuildProvider.cs @@ -240,7 +240,8 @@ private static string GetPlatformFilePath( RecurseSubdirectories = true, MatchCasing = MatchCasing.CaseInsensitive, }; - var device = deviceManifest.SupportedPlatforms! + + return deviceManifest.SupportedPlatforms! .SelectMany(platformName => platformsDirectories .SelectMany(directoryInfo => directoryInfo .GetDirectories($"{platformName}*", caseInsensitiveEnumerationOptions) @@ -251,16 +252,9 @@ private static string GetPlatformFilePath( .OrderByDescending(fileInfo => fileInfo.FullName)) ) .FirstOrDefault()? - .FullName; - - if (device == null) - { - throw new FileNotFoundException( - "Unable to find the platform xpfm file. The supported platforms are: " + - string.Join(", ", deviceManifest.SupportedPlatforms)); - } - - return device; + .FullName ?? throw new FileNotFoundException( + "Unable to find the platform xpfm file. The supported platforms are: " + + string.Join(", ", deviceManifest.SupportedPlatforms)); } private void ProgressMajor(string message) @@ -432,12 +426,8 @@ private async Task CollectReportsAsync( var reportFilePath = Directory.GetFiles(reportSavePath, "*_bb_locked_power_routed.rpt").FirstOrDefault() ?? - Directory.GetFiles(reportSavePath, "*_power_routed.rpt").FirstOrDefault(); - if (reportFilePath == null) - { - throw new FileNotFoundException( - "The report file is missing. Utilization related verification is not performed."); - } + Directory.GetFiles(reportSavePath, "*_power_routed.rpt").FirstOrDefault() ?? + throw new FileNotFoundException("The report file is missing. Utilization related verification is not performed."); using var reader = File.OpenText(reportFilePath); var report = await XilinxReport.ParseAsync(reader); @@ -593,11 +583,7 @@ public static async Task GetExecutablePathAsync(string executable) { var executableName = (await CliHelper.WhichAsync(executable)) .FirstOrDefault(fileInfo => fileInfo.Exists)? - .FullName; - if (executableName == null) - { - throw new FileNotFoundException($"The {nameof(executable)} '{executable}' was not found. Is it in your PATH?"); - } + .FullName ?? throw new FileNotFoundException($"The {nameof(executable)} '{executable}' was not found. Is it in your PATH?"); return executableName; } From b82dcf54ac8bbce39538fd90e36bff205bdff25f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Thu, 19 Oct 2023 13:10:31 +0200 Subject: [PATCH 41/53] submodule --- src/Libraries/External/Lombiq.Arithmetics | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Libraries/External/Lombiq.Arithmetics b/src/Libraries/External/Lombiq.Arithmetics index c4a8611b..cbe87516 160000 --- a/src/Libraries/External/Lombiq.Arithmetics +++ b/src/Libraries/External/Lombiq.Arithmetics @@ -1 +1 @@ -Subproject commit c4a8611b2ef3ede558aa6b109c319ccfdb1c3c2a +Subproject commit cbe875166ce41de67e4839bec1f94532e9be7870 From 21c1e4b35c9a7e7354480192592468c8a864fde6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Thu, 19 Oct 2023 15:12:58 +0200 Subject: [PATCH 42/53] Some code cleanup. --- .globalconfig | 1 - .../Hast.TestInputs.Static/ObjectUsingCases.cs | 2 -- 2 files changed, 3 deletions(-) diff --git a/.globalconfig b/.globalconfig index 190c1183..da29b3eb 100644 --- a/.globalconfig +++ b/.globalconfig @@ -1,5 +1,4 @@ is_global = true -global_level = 10 # Code analysis rules for Hastlayer, extending Lombiq.Analyzers.globalconfig. diff --git a/test/TestInputAssemblies/Hast.TestInputs.Static/ObjectUsingCases.cs b/test/TestInputAssemblies/Hast.TestInputs.Static/ObjectUsingCases.cs index ae88e69e..5c7c5f2d 100644 --- a/test/TestInputAssemblies/Hast.TestInputs.Static/ObjectUsingCases.cs +++ b/test/TestInputAssemblies/Hast.TestInputs.Static/ObjectUsingCases.cs @@ -14,8 +14,6 @@ public void NullUsage() { customObject = new MyClass(); } -#pragma warning restore IDE0074 // Use compound assignment -#pragma warning restore S3240 // The simplest possible condition syntax should be used customObject = null; From 56a3ad49da1961ecff9f1b47b3ccd1df2c468e22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Thu, 19 Oct 2023 15:26:11 +0200 Subject: [PATCH 43/53] Don't use Math.Sign in code that will be transformed. --- src/Hastlayer/Hast.Algorithms/Fix64.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Hastlayer/Hast.Algorithms/Fix64.cs b/src/Hastlayer/Hast.Algorithms/Fix64.cs index e3bc9ece..2060279d 100644 --- a/src/Hastlayer/Hast.Algorithms/Fix64.cs +++ b/src/Hastlayer/Hast.Algorithms/Fix64.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.CompilerServices; @@ -104,7 +105,11 @@ public readonly int[] ToIntegers() /// Returns a number indicating the sign of a Fix64 number. Returns 1 if the value is positive, 0 if is 0, and -1 if /// it is negative. /// - public static int Sign(Fix64 value) => Math.Sign(value.RawValue); + [SuppressMessage( + "Major Code Smell", + "S3358:Ternary operators should not be nested", + Justification = "The generated code is simpler this way.")] + public static int Sign(Fix64 value) => value.RawValue == 0 ? 0 : (value.RawValue > 0 ? 1 : -1); /// /// Returns the absolute value of a Fix64 number. Note: Abs(Fix64.MinValue) == Fix64.MaxValue. From 66d1e27f846f4f8f5560449e3dbd94baa984b94f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Thu, 19 Oct 2023 15:30:16 +0200 Subject: [PATCH 44/53] Use GetMaybe instead. --- src/Hastlayer/Hast.Catapult/CatapultLibrary.cs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs b/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs index 0b898900..86eabb4a 100644 --- a/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs +++ b/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs @@ -180,9 +180,9 @@ public static CatapultLibrary Create( ILogger logger, int endpointNumber = Constants.PcieHipNumber) { - var libraryPath = GetOrDefault(config, Constants.ConfigKeys.LibraryPath, Constants.DefaultLibraryPath); - var versionDefinitionsFile = GetOrDefault(config, Constants.ConfigKeys.VersionDefinitionsFile); - var versionManifestFile = GetOrDefault(config, Constants.ConfigKeys.VersionManifestFile); + var libraryPath = config.GetMaybe(Constants.DefaultLibraryPath) ?? Constants.DefaultLibraryPath; + var versionDefinitionsFile = config.GetMaybe(Constants.ConfigKeys.VersionDefinitionsFile); + var versionManifestFile = config.GetMaybe(Constants.ConfigKeys.VersionManifestFile); return new CatapultLibrary( (string)libraryPath, @@ -547,9 +547,4 @@ private void LogLineInvariant(Constants.Log level, FormattableString text) => LogFunction?.Invoke((uint)level, text.ToString(CultureInfo.InvariantCulture) + Environment.NewLine); public override string ToString() => InstanceName; - - private static object GetOrDefault(IDictionary config, string key, object fallback = null) => - config.TryGetValue(key, out var result) - ? result ?? fallback - : fallback; } From 061414bc705088919efcedcef0d94b8bada8ec70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Thu, 19 Oct 2023 15:35:50 +0200 Subject: [PATCH 45/53] suppress --- .../Hast.Communication/Services/FpgaIpEndpointFinder.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Hastlayer/Hast.Communication/Services/FpgaIpEndpointFinder.cs b/src/Hastlayer/Hast.Communication/Services/FpgaIpEndpointFinder.cs index 9fce9b05..f2f57df7 100644 --- a/src/Hastlayer/Hast.Communication/Services/FpgaIpEndpointFinder.cs +++ b/src/Hastlayer/Hast.Communication/Services/FpgaIpEndpointFinder.cs @@ -29,6 +29,7 @@ public FpgaIpEndpointFinder(IClock clock, ILogger logger) _logger = logger; } + [SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "False positive in VS only.")] [SuppressMessage( "Style", "IDE0230:Use UTF-8 string literal", From 2bebd4196a8ffdda5b24e1f65fe8cd55b1890ac5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Thu, 19 Oct 2023 15:39:04 +0200 Subject: [PATCH 46/53] Update src/Hastlayer/Hast.Vitis/Services/VitisHardwareImplementationComposerBuildProvider.cs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Zoltán Lehóczky --- .../VitisHardwareImplementationComposerBuildProvider.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Hastlayer/Hast.Vitis/Services/VitisHardwareImplementationComposerBuildProvider.cs b/src/Hastlayer/Hast.Vitis/Services/VitisHardwareImplementationComposerBuildProvider.cs index e57fcf59..e4de0bbb 100644 --- a/src/Hastlayer/Hast.Vitis/Services/VitisHardwareImplementationComposerBuildProvider.cs +++ b/src/Hastlayer/Hast.Vitis/Services/VitisHardwareImplementationComposerBuildProvider.cs @@ -252,9 +252,10 @@ private static string GetPlatformFilePath( .OrderByDescending(fileInfo => fileInfo.FullName)) ) .FirstOrDefault()? - .FullName ?? throw new FileNotFoundException( - "Unable to find the platform xpfm file. The supported platforms are: " + - string.Join(", ", deviceManifest.SupportedPlatforms)); + .FullName ?? + throw new FileNotFoundException( + "Unable to find the platform xpfm file. The supported platforms are: " + + string.Join(", ", deviceManifest.SupportedPlatforms)); } private void ProgressMajor(string message) From 9ec59ff940c01c01c052d6a1f74e35927e072543 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Thu, 19 Oct 2023 15:54:37 +0200 Subject: [PATCH 47/53] It should be okay to use "none" instead of "silent". --- .globalconfig | 6 +++--- tools/Lombiq.Analyzers | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.globalconfig b/.globalconfig index da29b3eb..d10e1314 100644 --- a/.globalconfig +++ b/.globalconfig @@ -3,7 +3,7 @@ is_global = true # Code analysis rules for Hastlayer, extending Lombiq.Analyzers.globalconfig. # Microsoft.CodeAnalysis.NetAnalyzers rules -dotnet_diagnostic.CA1062.severity = silent -dotnet_diagnostic.CA1724.severity = silent +dotnet_diagnostic.CA1062.severity = none +dotnet_diagnostic.CA1724.severity = none dotnet_diagnostic.CA1848.severity = none -dotnet_diagnostic.CA2007.severity = silent +dotnet_diagnostic.CA2007.severity = none diff --git a/tools/Lombiq.Analyzers b/tools/Lombiq.Analyzers index 4d5451c4..9973430f 160000 --- a/tools/Lombiq.Analyzers +++ b/tools/Lombiq.Analyzers @@ -1 +1 @@ -Subproject commit 4d5451c438d4187d619ff5cfeab101002fbaed8e +Subproject commit 9973430f923a9fca34fd7ea813470ec5ccbc0184 From d39060d63993c574d297538e7987e95f70ef1bb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Thu, 19 Oct 2023 16:25:09 +0200 Subject: [PATCH 48/53] Rename Hast.Vitis.Constants.Extensions. --- .../Constants/{Extensions.cs => FileNameExtensions.cs} | 2 +- src/Hastlayer/Hast.Vitis/Services/OpenClCommunicationService.cs | 2 +- src/Hastlayer/Hast.Vitis/Services/VitisCommunicationService.cs | 2 +- .../VitisHardwareImplementationComposerBuildProvider.cs | 2 +- .../Hast.Vitis/Services/VitisHbmMemoryResourceChecker.cs | 2 +- .../Services/ZynqHardwareImplementationComposerBuildProvider.cs | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) rename src/Hastlayer/Hast.Vitis/Constants/{Extensions.cs => FileNameExtensions.cs} (87%) diff --git a/src/Hastlayer/Hast.Vitis/Constants/Extensions.cs b/src/Hastlayer/Hast.Vitis/Constants/FileNameExtensions.cs similarity index 87% rename from src/Hastlayer/Hast.Vitis/Constants/Extensions.cs rename to src/Hastlayer/Hast.Vitis/Constants/FileNameExtensions.cs index 2283131a..7a75b6e6 100644 --- a/src/Hastlayer/Hast.Vitis/Constants/Extensions.cs +++ b/src/Hastlayer/Hast.Vitis/Constants/FileNameExtensions.cs @@ -1,6 +1,6 @@ namespace Hast.Vitis.Constants; -public static class Extensions +public static class FileNameExtensions { public const string InfoFileExtension = ".info"; public const string NameExtension = ".name"; diff --git a/src/Hastlayer/Hast.Vitis/Services/OpenClCommunicationService.cs b/src/Hastlayer/Hast.Vitis/Services/OpenClCommunicationService.cs index 2201478a..ad048c31 100644 --- a/src/Hastlayer/Hast.Vitis/Services/OpenClCommunicationService.cs +++ b/src/Hastlayer/Hast.Vitis/Services/OpenClCommunicationService.cs @@ -17,7 +17,7 @@ using System.Text; using System.Threading.Tasks; using static Hast.Transformer.SimpleMemory.SimpleMemory; -using static Hast.Vitis.Constants.Extensions; +using static Hast.Vitis.Constants.FileNameExtensions; namespace Hast.Vitis.Services; diff --git a/src/Hastlayer/Hast.Vitis/Services/VitisCommunicationService.cs b/src/Hastlayer/Hast.Vitis/Services/VitisCommunicationService.cs index 0de96c87..b0e9f740 100644 --- a/src/Hastlayer/Hast.Vitis/Services/VitisCommunicationService.cs +++ b/src/Hastlayer/Hast.Vitis/Services/VitisCommunicationService.cs @@ -8,7 +8,7 @@ using System; using System.Buffers; using System.IO; -using static Hast.Vitis.Constants.Extensions; +using static Hast.Vitis.Constants.FileNameExtensions; namespace Hast.Vitis.Services; diff --git a/src/Hastlayer/Hast.Vitis/Services/VitisHardwareImplementationComposerBuildProvider.cs b/src/Hastlayer/Hast.Vitis/Services/VitisHardwareImplementationComposerBuildProvider.cs index e4de0bbb..5b313319 100644 --- a/src/Hastlayer/Hast.Vitis/Services/VitisHardwareImplementationComposerBuildProvider.cs +++ b/src/Hastlayer/Hast.Vitis/Services/VitisHardwareImplementationComposerBuildProvider.cs @@ -18,7 +18,7 @@ using System.IO; using System.Linq; using System.Threading.Tasks; -using static Hast.Vitis.Constants.Extensions; +using static Hast.Vitis.Constants.FileNameExtensions; using static Lombiq.HelpfulLibraries.Common.Utilities.FileSystemHelper; namespace Hast.Vitis.Services; diff --git a/src/Hastlayer/Hast.Vitis/Services/VitisHbmMemoryResourceChecker.cs b/src/Hastlayer/Hast.Vitis/Services/VitisHbmMemoryResourceChecker.cs index b5107c18..dcee1c73 100644 --- a/src/Hastlayer/Hast.Vitis/Services/VitisHbmMemoryResourceChecker.cs +++ b/src/Hastlayer/Hast.Vitis/Services/VitisHbmMemoryResourceChecker.cs @@ -6,7 +6,7 @@ using Hast.Vitis.Models; using Hast.Xilinx; using System.IO; -using static Hast.Vitis.Constants.Extensions; +using static Hast.Vitis.Constants.FileNameExtensions; namespace Hast.Vitis.Services; diff --git a/src/Hastlayer/Hast.Vitis/Services/ZynqHardwareImplementationComposerBuildProvider.cs b/src/Hastlayer/Hast.Vitis/Services/ZynqHardwareImplementationComposerBuildProvider.cs index 11c4b133..49d90dad 100644 --- a/src/Hastlayer/Hast.Vitis/Services/ZynqHardwareImplementationComposerBuildProvider.cs +++ b/src/Hastlayer/Hast.Vitis/Services/ZynqHardwareImplementationComposerBuildProvider.cs @@ -10,7 +10,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -using static Hast.Vitis.Constants.Extensions; +using static Hast.Vitis.Constants.FileNameExtensions; using static Hast.Vitis.Services.VitisHardwareImplementationComposerBuildProvider; using static Lombiq.HelpfulLibraries.Common.Utilities.FileSystemHelper; From c12cc8f1f8a47fd7e5d8dd8e3bea350a0eda8ed8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Thu, 19 Oct 2023 16:39:39 +0200 Subject: [PATCH 49/53] Rename Hast.Communication.Tester.Options and Hast.Samples.Consumer.Gui. --- .../{Options.cs => CommandLineOptions.cs} | 2 +- src/Hastlayer/Hast.Communication.Tester/Program.cs | 6 +++--- .../Hast.Samples.Consumer/{Gui.cs => ConfigurationGui.cs} | 8 ++++---- src/Samples/Hast.Samples.Consumer/Program.cs | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) rename src/Hastlayer/Hast.Communication.Tester/{Options.cs => CommandLineOptions.cs} (98%) rename src/Samples/Hast.Samples.Consumer/{Gui.cs => ConfigurationGui.cs} (98%) diff --git a/src/Hastlayer/Hast.Communication.Tester/Options.cs b/src/Hastlayer/Hast.Communication.Tester/CommandLineOptions.cs similarity index 98% rename from src/Hastlayer/Hast.Communication.Tester/Options.cs rename to src/Hastlayer/Hast.Communication.Tester/CommandLineOptions.cs index 476e3e1b..a282d372 100644 --- a/src/Hastlayer/Hast.Communication.Tester/Options.cs +++ b/src/Hastlayer/Hast.Communication.Tester/CommandLineOptions.cs @@ -5,7 +5,7 @@ namespace Hast.Communication.Tester; -public class Options +public class CommandLineOptions { // Be sure to update the when changing these! diff --git a/src/Hastlayer/Hast.Communication.Tester/Program.cs b/src/Hastlayer/Hast.Communication.Tester/Program.cs index fbffd402..a5fe24ba 100644 --- a/src/Hastlayer/Hast.Communication.Tester/Program.cs +++ b/src/Hastlayer/Hast.Communication.Tester/Program.cs @@ -36,7 +36,7 @@ public static class Program public const int HexDumpBlocksPerLine = 8; - public static Options CommandLineOptions { get; set; } + public static CommandLineOptions CommandLineOptions { get; set; } private static Hastlayer _hastlayer; @@ -223,7 +223,7 @@ private static async Task SaveFileAsync( case OutputFileType.Hexdump: if (string.IsNullOrEmpty(fileName)) fileName = fileNamePrefix + DefaultHexdumpFileName; Console.WriteLine("Saving {0} hexdump to '{1}'...", direction, fileName); - if (fileName == Options.OutputFileNameConsole) + if (fileName == CommandLineOptions.OutputFileNameConsole) { WriteHexdump(Console.Out, memory); } @@ -309,7 +309,7 @@ private static void Main(string[] args) { try { - Parser.Default.ParseArguments(args).WithParsed(options => CommandLineOptions = options); + Parser.Default.ParseArguments(args).WithParsed(options => CommandLineOptions = options); if (CommandLineOptions == null) return; var hastlayerConfiguration = new HastlayerConfiguration(); diff --git a/src/Samples/Hast.Samples.Consumer/Gui.cs b/src/Samples/Hast.Samples.Consumer/ConfigurationGui.cs similarity index 98% rename from src/Samples/Hast.Samples.Consumer/Gui.cs rename to src/Samples/Hast.Samples.Consumer/ConfigurationGui.cs index fad2aaeb..523e119a 100644 --- a/src/Samples/Hast.Samples.Consumer/Gui.cs +++ b/src/Samples/Hast.Samples.Consumer/ConfigurationGui.cs @@ -11,7 +11,7 @@ namespace Hast.Samples.Consumer; -public sealed class Gui : IDisposable +public sealed class ConfigurationGui : IDisposable { private readonly IDictionary _savedConfigurations; private readonly ListView _propertiesListView = new ListView { CanFocus = true }.Fill(); @@ -43,7 +43,7 @@ public sealed class Gui : IDisposable private ListView _list; private ScrollView _scrollView; - public Gui(IDictionary savedConfigurations) => + public ConfigurationGui(IDictionary savedConfigurations) => _savedConfigurations = savedConfigurations; public ConsumerConfiguration BuildConfiguration() @@ -173,7 +173,7 @@ public ConsumerConfiguration BuildConfiguration() { hastlayerTask .Result - .GetLogger() + .GetLogger() .LogError(exception, "an error during GUI operation"); _configuration = null; Console.WriteLine( @@ -472,7 +472,7 @@ public void Dispose() public static ConsumerConfiguration BuildConfiguration( IDictionary savedConfigurations) { - using var gui = new Gui(savedConfigurations); + using var gui = new ConfigurationGui(savedConfigurations); return gui.BuildConfiguration(); } diff --git a/src/Samples/Hast.Samples.Consumer/Program.cs b/src/Samples/Hast.Samples.Consumer/Program.cs index e1361b7e..379bc243 100644 --- a/src/Samples/Hast.Samples.Consumer/Program.cs +++ b/src/Samples/Hast.Samples.Consumer/Program.cs @@ -56,7 +56,7 @@ private static async Task MainTaskAsync(string[] args) var savedConfigurations = await ConsumerConfiguration.LoadConfigurationsAsync(); var consumerConfiguration = args.Any() ? ConsumerConfiguration.FromCommandLine(args, savedConfigurations) - : Gui.BuildConfiguration(savedConfigurations); + : ConfigurationGui.BuildConfiguration(savedConfigurations); if (consumerConfiguration == null) return ExitStatus.NothingToDo; // Initializing a Hastlayer shell. Since this is non-trivial to do you can cache this shell object while the From f94c2ea3288e32c8dccff37f6f989153329a31a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Thu, 19 Oct 2023 16:41:44 +0200 Subject: [PATCH 50/53] Rename Hast.Catapult.Constants. --- .../{Constants.cs => CatapultConstants.cs} | 2 +- .../Hast.Catapult/CatapultLibrary.cs | 76 +++++++-------- .../Hast.Catapult/Drivers/CatapultDriver.cs | 2 +- .../CatapultFunctionResultException.cs | 4 +- .../Hast.Catapult/ICatapultNativeLibrary.cs | 96 +++++++++---------- .../Services/CatapultCommunicationService.cs | 4 +- 6 files changed, 92 insertions(+), 92 deletions(-) rename src/Hastlayer/Hast.Catapult/{Constants.cs => CatapultConstants.cs} (99%) diff --git a/src/Hastlayer/Hast.Catapult/Constants.cs b/src/Hastlayer/Hast.Catapult/CatapultConstants.cs similarity index 99% rename from src/Hastlayer/Hast.Catapult/Constants.cs rename to src/Hastlayer/Hast.Catapult/CatapultConstants.cs index 7c3d12b2..29067047 100644 --- a/src/Hastlayer/Hast.Catapult/Constants.cs +++ b/src/Hastlayer/Hast.Catapult/CatapultConstants.cs @@ -3,7 +3,7 @@ namespace Hast.Catapult; -public static class Constants +public static class CatapultConstants { public const string Catapult = nameof(Catapult); public const string ChannelName = Catapult; diff --git a/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs b/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs index 86eabb4a..758d3d2b 100644 --- a/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs +++ b/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs @@ -11,8 +11,8 @@ using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; -using InputHeaderSizes = Hast.Catapult.Constants.InputHeaderSizes; -using OutputHeaderSizes = Hast.Catapult.Constants.OutputHeaderSizes; +using InputHeaderSizes = Hast.Catapult.CatapultConstants.InputHeaderSizes; +using OutputHeaderSizes = Hast.Catapult.CatapultConstants.OutputHeaderSizes; namespace Hast.Catapult; @@ -31,7 +31,7 @@ public sealed class CatapultLibrary : IDisposable /// /// Gets the name of the instance (Catapult:N where N is the PCIe endpoint number). /// - public string InstanceName => StringHelper.CreateInvariant($"{Constants.ChannelName}:{PcieEndpointNumber}"); + public string InstanceName => StringHelper.CreateInvariant($"{CatapultConstants.ChannelName}:{PcieEndpointNumber}"); /// /// Contains the latest tasks to be awaited when starting a new task. @@ -96,15 +96,15 @@ public bool PcieEnabled get { VerifyResult(NativeLibrary.ReadShellRegister(_handle, 0, out uint pcie)); - return (pcie & Constants.RegisterMaskPcieEnabled) != 0; + return (pcie & CatapultConstants.RegisterMaskPcieEnabled) != 0; } private set { VerifyResult(NativeLibrary.ReadShellRegister(_handle, 0, out uint pcie)); // Set control_register[6] - if (value) pcie |= Constants.RegisterMaskPcieEnabled; - else pcie &= ~Constants.RegisterMaskPcieEnabled; + if (value) pcie |= CatapultConstants.RegisterMaskPcieEnabled; + else pcie &= ~CatapultConstants.RegisterMaskPcieEnabled; VerifyResult(NativeLibrary.WriteShellRegister(_handle, 0, pcie)); } @@ -129,10 +129,10 @@ private set /// parameter and a string as its second. Note that the strings all end with newline character. /// public CatapultLibrary( - string libraryPath = Constants.DefaultLibraryPath, + string libraryPath = CatapultConstants.DefaultLibraryPath, string versionDefinitionsFile = null, string versionManifestFile = null, - int endpointNumber = Constants.PcieHipNumber, + int endpointNumber = CatapultConstants.PcieHipNumber, CatapultLogFunction logFunction = null) { LogFunction = logFunction; @@ -153,7 +153,7 @@ public CatapultLibrary( VerifyResult(createStatus); // Configure hardware settings & enable hardware. - SetSoftRegister(Constants.ConfigDram.Channel0, 0); + SetSoftRegister(CatapultConstants.ConfigDram.Channel0, 0); PcieEnabled = true; // Query device info. @@ -165,9 +165,9 @@ public CatapultLibrary( BufferSize = (int)count; // Load in configuration from the soft registers - var allowedSlots = (int)GetSoftRegister(Constants.SoftRegisters.AllowedSlots); + var allowedSlots = (int)GetSoftRegister(CatapultConstants.SoftRegisters.AllowedSlots); if (allowedSlots > 0 && allowedSlots < BufferCount) BufferCount = allowedSlots; - var bufferPayloadSize = (int)GetSoftRegister(Constants.SoftRegisters.BufferPayloadSize); + var bufferPayloadSize = (int)GetSoftRegister(CatapultConstants.SoftRegisters.BufferPayloadSize); if (bufferPayloadSize > 0 && bufferPayloadSize < BufferPayloadSize) BufferPayloadSize = bufferPayloadSize; // Set up the task tracker. @@ -178,11 +178,11 @@ public CatapultLibrary( public static CatapultLibrary Create( IDictionary config, ILogger logger, - int endpointNumber = Constants.PcieHipNumber) + int endpointNumber = CatapultConstants.PcieHipNumber) { - var libraryPath = config.GetMaybe(Constants.DefaultLibraryPath) ?? Constants.DefaultLibraryPath; - var versionDefinitionsFile = config.GetMaybe(Constants.ConfigKeys.VersionDefinitionsFile); - var versionManifestFile = config.GetMaybe(Constants.ConfigKeys.VersionManifestFile); + var libraryPath = config.GetMaybe(CatapultConstants.DefaultLibraryPath) ?? CatapultConstants.DefaultLibraryPath; + var versionDefinitionsFile = config.GetMaybe(CatapultConstants.ConfigKeys.VersionDefinitionsFile); + var versionManifestFile = config.GetMaybe(CatapultConstants.ConfigKeys.VersionManifestFile); return new CatapultLibrary( (string)libraryPath, @@ -191,28 +191,28 @@ public static CatapultLibrary Create( endpointNumber: endpointNumber, logFunction: (flagValue, text) => { - var flag = (Constants.Log)flagValue; + var flag = (CatapultConstants.Log)flagValue; // This function proxies special log entries so they can't be static. #pragma warning disable CA2254 // Template should be a static expression switch (flag) { - case Constants.Log.None: + case CatapultConstants.Log.None: return; - case Constants.Log.Info: + case CatapultConstants.Log.Info: logger.LogInformation(text); break; - case Constants.Log.Debug: - case Constants.Log.Verbose: + case CatapultConstants.Log.Debug: + case CatapultConstants.Log.Verbose: logger.LogDebug(text); break; - case Constants.Log.Error: + case CatapultConstants.Log.Error: logger.LogError(text); break; - case Constants.Log.Fatal: + case CatapultConstants.Log.Fatal: logger.LogCritical(text); break; - case Constants.Log.Warn: + case CatapultConstants.Log.Warn: logger.LogWarning(text); break; default: @@ -236,12 +236,12 @@ public void Dispose() // close the PICe connection via `PcieEnabled = false;` right after that anyway. } - LogLine(Constants.Log.Info, "Closing down the FPGA..."); + LogLine(CatapultConstants.Log.Info, "Closing down the FPGA..."); PcieEnabled = false; NativeLibrary.CloseHandle(Handle); NativeLibrary.Dispose(); - LogLine(Constants.Log.Info, "Closed down the FPGA..."); + LogLine(CatapultConstants.Log.Info, "Closed down the FPGA..."); _isDisposed = true; } @@ -261,9 +261,9 @@ public void WaitClean() /// /// The return value from the library function. /// Thrown when the status isn't SUCCESS. - public void VerifyResult(Constants.Status status) + public void VerifyResult(CatapultConstants.Status status) { - if (status == Constants.Status.Success) return; + if (status == CatapultConstants.Status.Success) return; var errorMessage = new StringBuilder(512); NativeLibrary.GetLastError(); @@ -436,7 +436,7 @@ private async Task> AssignMultiSliceJobAsync( /// The resulting output from the FPGA. private async Task> RunJobAsync(int bufferIndex, Memory inputData, bool ignoreResponse) { - LogLineInvariant(Constants.Log.Info, $"Job on slot #{bufferIndex} starting..."); + LogLineInvariant(CatapultConstants.Log.Info, $"Job on slot #{bufferIndex} starting..."); Debug.Assert( bufferIndex < BufferCount, StringHelper.CreateInvariant($"The buffer index is out of range. (current: {bufferIndex}, max: {BufferCount})")); @@ -459,16 +459,16 @@ private async Task> RunJobAsync(int bufferIndex, Memory input // If the input message isn't 64B aligned, pad it with zeros. var payloadBytes = inputData.Length - InputHeaderSizes.Total; - if (payloadBytes % Constants.BufferChunkBytes != 0) + if (payloadBytes % CatapultConstants.BufferChunkBytes != 0) { - int paddedPayloadSize = Constants.BufferChunkBytes * ((payloadBytes / Constants.BufferChunkBytes) + 1); + int paddedPayloadSize = CatapultConstants.BufferChunkBytes * ((payloadBytes / CatapultConstants.BufferChunkBytes) + 1); if (paddedPayloadSize <= BufferPayloadSize) { LogLine( - Constants.Log.Warn, + CatapultConstants.Log.Warn, StringHelper.Concatenate( - $"Incoming payload ({payloadBytes}B) must be aligned to {Constants.BufferChunkBytes}B! ", - $"Padding for {Constants.BufferChunkBytes - paddedPayloadSize}B...")); + $"Incoming payload ({payloadBytes}B) must be aligned to {CatapultConstants.BufferChunkBytes}B! ", + $"Padding for {CatapultConstants.BufferChunkBytes - paddedPayloadSize}B...")); var padded = new byte[paddedPayloadSize + InputHeaderSizes.Total]; inputData.CopyTo(padded); inputData = padded; @@ -478,7 +478,7 @@ private async Task> RunJobAsync(int bufferIndex, Memory input VerifyResult(NativeLibrary.GetInputBufferPointer(_handle, slot, out var inputBuffer)); LogLineInvariant( - Constants.Log.Debug, + CatapultConstants.Log.Debug, $"Buffer #{slot} @ {inputBuffer.ToInt64()} input start: {Marshal.PtrToStructure(inputBuffer)}"); // Upload data into input buffer. @@ -522,13 +522,13 @@ private async Task> ReceiveJobResultsAsync(uint slot) } LogLineInvariant( - Constants.Log.Debug, + CatapultConstants.Log.Debug, $"Buffer #{slot} @ {outputBuffer.ToInt64()} output start: {Marshal.PtrToStructure(outputBuffer)}"); // Signal that we are done. NativeLibrary.DiscardOutputBuffer(_handle, slot); - LogFunction?.Invoke((uint)Constants.Log.Info, $"Job on slot #{slot} finished!{Environment.NewLine}"); + LogFunction?.Invoke((uint)CatapultConstants.Log.Info, $"Job on slot #{slot} finished!{Environment.NewLine}"); return resultMemory; } @@ -540,10 +540,10 @@ private Task TesterWriteLineAsync(string format, params object[] objects) return TesterOutput.WriteLineAsync(format); } - private void LogLine(Constants.Log level, string text) => + private void LogLine(CatapultConstants.Log level, string text) => LogFunction?.Invoke((uint)level, text + Environment.NewLine); - private void LogLineInvariant(Constants.Log level, FormattableString text) => + private void LogLineInvariant(CatapultConstants.Log level, FormattableString text) => LogFunction?.Invoke((uint)level, text.ToString(CultureInfo.InvariantCulture) + Environment.NewLine); public override string ToString() => InstanceName; diff --git a/src/Hastlayer/Hast.Catapult/Drivers/CatapultDriver.cs b/src/Hastlayer/Hast.Catapult/Drivers/CatapultDriver.cs index 8fc4848c..80445cea 100644 --- a/src/Hastlayer/Hast.Catapult/Drivers/CatapultDriver.cs +++ b/src/Hastlayer/Hast.Catapult/Drivers/CatapultDriver.cs @@ -11,7 +11,7 @@ namespace Hast.Catapult.Drivers; public class CatapultDriver : IDeviceDriver { - public const string DeviceName = Constants.Catapult; + public const string DeviceName = CatapultConstants.Catapult; private readonly ITimingReportParser _timingReportParser; private readonly object _timingReportParserLock = new(); diff --git a/src/Hastlayer/Hast.Catapult/Exceptions/CatapultFunctionResultException.cs b/src/Hastlayer/Hast.Catapult/Exceptions/CatapultFunctionResultException.cs index 26680ca4..286d927a 100644 --- a/src/Hastlayer/Hast.Catapult/Exceptions/CatapultFunctionResultException.cs +++ b/src/Hastlayer/Hast.Catapult/Exceptions/CatapultFunctionResultException.cs @@ -12,11 +12,11 @@ public class CatapultFunctionResultException : Exception /// /// Gets the status returned by the native function call. /// - public Constants.Status Status { get; private set; } + public CatapultConstants.Status Status { get; private set; } public CatapultFunctionResultException() { } - public CatapultFunctionResultException(Constants.Status status, string message) + public CatapultFunctionResultException(CatapultConstants.Status status, string message) : this(string.IsNullOrWhiteSpace(message) ? status.ToString() : message) => Status = status; public CatapultFunctionResultException(string message) diff --git a/src/Hastlayer/Hast.Catapult/ICatapultNativeLibrary.cs b/src/Hastlayer/Hast.Catapult/ICatapultNativeLibrary.cs index deda0bc3..4fda691f 100644 --- a/src/Hastlayer/Hast.Catapult/ICatapultNativeLibrary.cs +++ b/src/Hastlayer/Hast.Catapult/ICatapultNativeLibrary.cs @@ -11,8 +11,8 @@ namespace Hast.Catapult; /// The function used by logging in FpgaCoreLib.dll and the CatapultLibrary class. /// /// -/// The value of a flag enum converted into uint. This can be used to filter out specific -/// types of messages, eg . +/// The value of a flag enum converted into uint. This can be used to filter out specific +/// types of messages, eg . /// /// The log message. Ends with newline so Write should be used instead of WriteLine. [UnmanagedFunctionPointer(CallingConvention.Cdecl)] @@ -30,37 +30,37 @@ public interface ICatapultNativeLibrary : IDisposable /// /// This function retrieves the total number of shell registers. /// - Constants.Status GetNumberShellRegisters(IntPtr fpgaHandle, out uint numShellRegs); + CatapultConstants.Status GetNumberShellRegisters(IntPtr fpgaHandle, out uint numShellRegs); /// /// This function allows users to read shell registers. It is both multithreaded- and multiprocesss-safe. /// - Constants.Status ReadShellRegister(IntPtr fpgaHandle, uint registerNumber, out uint readValue); + CatapultConstants.Status ReadShellRegister(IntPtr fpgaHandle, uint registerNumber, out uint readValue); /// /// This function allows users to write shell registers. It is both multithreaded- and multiprocess-safe. /// - Constants.Status WriteShellRegister(IntPtr fpgaHandle, uint registerNumber, uint writeValue); + CatapultConstants.Status WriteShellRegister(IntPtr fpgaHandle, uint registerNumber, uint writeValue); /// /// This functions returns whether the loaded FPGA image is a Golden image or not. /// - Constants.Status IsGoldenImage(IntPtr fpgaHandle, out bool isGolden, out uint roleID, out uint roleVersion); + CatapultConstants.Status IsGoldenImage(IntPtr fpgaHandle, out bool isGolden, out uint roleID, out uint roleVersion); /// /// This function returns the RSU Image ID. /// - Constants.Status ReadRsuImageId(IntPtr fpgaHandle, out uint pImageId); + CatapultConstants.Status ReadRsuImageId(IntPtr fpgaHandle, out uint pImageId); /// /// This function forces FPGA reconfiguration. It is not multithreaded- or multiprocess-safe. The act of /// re-configuration will cause the existing FPGA handles to be closed. /// - Constants.Status Reconfig(IntPtr[] fpgaHandles, uint numHandles, bool reconfigToGolden); + CatapultConstants.Status Reconfig(IntPtr[] fpgaHandles, uint numHandles, bool reconfigToGolden); /// /// This function is used to update the flash images on the FPGA. It can either be used to update the golden or app - /// image. Writing to the golden image requires explicitly passing in + /// image. Writing to the golden image requires explicitly passing in /// during handle creation. WARNING: writing a bad golden image to the FPGA is a career-limiting move and can cause /// irreparable damage. This function is protected by an internal mutex against other calls to /// WriteFlashImage(IntPtr, bool, string) c>, , @@ -71,12 +71,12 @@ public interface ICatapultNativeLibrary : IDisposable /// Determines how long to wait in milliseconds for acquiring the mutex. The default wait time is set according to /// the worst-case flash write time multiplied by 2 (five minutes). Setting it to INFINITE removes the timeout. /// - /// When a timeout is triggered, it returns . - Constants.Status WriteFlashImageEx( + /// When a timeout is triggered, it returns . + CatapultConstants.Status WriteFlashImageEx( IntPtr fpgaHandle, bool writeToGolden, string rpdFilename, - uint timeoutInMs = Constants.DefaultFlashAccessTimeoutInMilliseconds); + uint timeoutInMs = CatapultConstants.DefaultFlashAccessTimeoutInMilliseconds); /// /// This function is used to read the flash images from the FPGA to a file. It can either be used to read the golden @@ -88,77 +88,77 @@ Constants.Status WriteFlashImageEx( /// Determines how long to wait in milliseconds for acquiring the mutex. The default wait time is set according to /// the worst-case flash write time multiplied by 2 (five minutes). Setting it to INFINITE removes the timeout. /// - Constants.Status CaptureFlashImageEx( + CatapultConstants.Status CaptureFlashImageEx( IntPtr fpgaHandle, bool isGolden, string rpdFilename, - uint timeoutInMs = Constants.DefaultFlashAccessTimeoutInMilliseconds); + uint timeoutInMs = CatapultConstants.DefaultFlashAccessTimeoutInMilliseconds); /// /// Disable non-maskable interrupt error reporting. Needed during FPGA reconfiguration. It is not multithreaded- or /// multiprocess-safe. /// - Constants.Status DisableNmi(IntPtr fpgaHandle); + CatapultConstants.Status DisableNmi(IntPtr fpgaHandle); /// /// Sanity check: FPGA reconfig often fails simply because the FPGA vendor/device ID changed after reconfig Will /// need to use RSU -rootportReload first in order to restore the ability to open an FPGA handle. /// - Constants.Status ReadVendorDeviceId(IntPtr fpgaHandle, out uint vendorId, out uint deviceId); + CatapultConstants.Status ReadVendorDeviceId(IntPtr fpgaHandle, out uint vendorId, out uint deviceId); /// /// Disables and re-enables instances of only the port filter driver that are believed to be upstream of the FPGA. /// May not target all needed instances, but this should definitely not target network or GPU or other things that /// sometimes make crash the machine. /// - Constants.Status ReviveRootportNoDriver(); + CatapultConstants.Status ReviveRootportNoDriver(); /// /// Disables and re-enables all instances of the root port filter driver. Useful if the FPGA device fails to start /// after reconfig, potentially saves a reboot. /// - Constants.Status CycleRootportEnabledNoDriver(); + CatapultConstants.Status CycleRootportEnabledNoDriver(); /// /// Disables and re-enables the FPGA in device manager with no driver installed (?). It is not multithreaded- or /// multiprocess-safe. /// - Constants.Status CycleDeviceEnabledNoDriver(); + CatapultConstants.Status CycleDeviceEnabledNoDriver(); /// /// Used in JTAG-based reconfiguration. Call this function before JTAG reconfiguration to disable AER and error /// reporting. It is not multithreaded- or multiprocess-safe. /// - Constants.Status PrepForReconfig(IntPtr[] fpgaHandles, uint numHandles); + CatapultConstants.Status PrepForReconfig(IntPtr[] fpgaHandles, uint numHandles); /// /// Used in JTAG-based reconfiguration. Call this function after JTAG reconfiguration to re-enable AER and error /// reporting. It is not multithreaded- or multiprocess-safe. /// - Constants.Status ResetAfterReconfig(IntPtr[] fpgaHandles, uint numHandles); + CatapultConstants.Status ResetAfterReconfig(IntPtr[] fpgaHandles, uint numHandles); /// /// Retrieves FPGA shell statistics. /// - Constants.Status ReadStatistic(IntPtr fpgaHandle, uint statType, out uint value); + CatapultConstants.Status ReadStatistic(IntPtr fpgaHandle, uint statType, out uint value); /// /// This function enables or disables network bypass mode Setting 'forceBypass' to TRUE will disable the soft shell /// network and cause all network traffic to go through the shell bridge. /// - Constants.Status SetNetworkBypass(IntPtr fpgaHandle, bool forceBypass); + CatapultConstants.Status SetNetworkBypass(IntPtr fpgaHandle, bool forceBypass); /// /// Trigger soft reset. /// - Constants.Status TriggerSoftReset(IntPtr fpgaHandle, uint resetType); + CatapultConstants.Status TriggerSoftReset(IntPtr fpgaHandle, uint resetType); /// /// Attempt to set the slot size and number of slots. Will fail if requested settings are invalid or cannot be /// attained. Bytes per slot must be a multiple of 4096. Number of slots cannot be larger than that supported by the /// hardware. /// - Constants.Status SetSlotSize(IntPtr[] fpgaHandles, uint numHandles, uint bytesPerSlot, uint numSlots); + CatapultConstants.Status SetSlotSize(IntPtr[] fpgaHandles, uint numHandles, uint bytesPerSlot, uint numSlots); #endregion FPGAManagementLib @@ -184,15 +184,15 @@ Constants.Status CaptureFlashImageEx( /// /// The optional last argument allows the user to specify a logging callback function. The user-defined function /// must accept a 'loglevel' argument, which classifies the log entry (e.g., verbose, informational, debug, etc) and - /// an ANSI string, which contains a single log entry. The enumeration is derived from + /// an ANSI string, which contains a single log entry. The enumeration is derived from /// the FPGA_LOG_* flags in the original library define all the possible (and non-mutually-exclusive) severity /// levels. /// /// - /// if the device is present or if the device is not present. + /// if the device is present or if the device is not present. /// - Constants.Status IsDevicePresent( + CatapultConstants.Status IsDevicePresent( string pchVerManifestFile, [MarshalAs(UnmanagedType.FunctionPtr)] CatapultLogFunction logFunc); @@ -217,7 +217,7 @@ Constants.Status IsDevicePresent( /// files are searched relative to the DLL path. /// /// Optional logging callback function. - Constants.Status CreateHandle( + CatapultConstants.Status CreateHandle( out IntPtr fpgaHandle, uint endpointNumber, uint flags, @@ -231,32 +231,32 @@ Constants.Status CreateHandle( /// cref="CreateHandle(out IntPtr, uint, uint, StringBuilder, StringBuilder, CatapultLogFunction)"/>. By default, /// the definitions are listed in VersionDefinitions.ini. /// - Constants.Status GetVersion(IntPtr fpgaHandle, string pchVerKey, out uint pVersion); + CatapultConstants.Status GetVersion(IntPtr fpgaHandle, string pchVerKey, out uint pVersion); /// /// This function should be called to release and close an FPGA handle. /// - Constants.Status CloseHandle(IntPtr fpgaHandle); + CatapultConstants.Status CloseHandle(IntPtr fpgaHandle); /// /// This function retrieves the total number of PCIe buffers available for host-to-FPGA communication. /// - Constants.Status GetNumberBuffers(IntPtr fpgaHandle, out uint numBuffers); + CatapultConstants.Status GetNumberBuffers(IntPtr fpgaHandle, out uint numBuffers); /// /// This function retrieves the total number of bytes available to use, per FPGA PCIe buffer. /// - Constants.Status GetBufferSize(IntPtr fpgaHandle, out uint bufferBytes); + CatapultConstants.Status GetBufferSize(IntPtr fpgaHandle, out uint bufferBytes); /// /// Returns the last error occurred. /// - Constants.Status GetLastError(); + CatapultConstants.Status GetLastError(); /// /// Provides error string for the last error occurred. /// - Constants.Status GetLastErrorText([MarshalAs(UnmanagedType.LPStr)] StringBuilder pErrorTextBuf, int cbBufSize); + CatapultConstants.Status GetLastErrorText([MarshalAs(UnmanagedType.LPStr)] StringBuilder pErrorTextBuf, int cbBufSize); /// /// This function retrieves a user-mapped pointer to a pinned region of kernel memory that is typically written by @@ -264,14 +264,14 @@ Constants.Status CreateHandle( /// cref="GetBufferSize(IntPtr, out uint)"/>. The total number of buffers available can be queried using . /// - Constants.Status GetInputBufferPointer(IntPtr fpgaHandle, uint whichBuffer, out IntPtr inputBufferPtr); + CatapultConstants.Status GetInputBufferPointer(IntPtr fpgaHandle, uint whichBuffer, out IntPtr inputBufferPtr); /// /// This function retrieves a user-mapped pointer to a pinned region of kernel memory that is typically written by /// the FPGA, and read by the host system. The available buffer capacity is finite and should be queried using . /// - Constants.Status GetOutputBufferPointer(IntPtr fpgaHandle, uint whichBuffer, out IntPtr outputBufferPtr); + CatapultConstants.Status GetOutputBufferPointer(IntPtr fpgaHandle, uint whichBuffer, out IntPtr outputBufferPtr); /// /// This function retrieves a user-mapped pointer to a pinned region of kernel memory that is typically written by @@ -279,30 +279,30 @@ Constants.Status CreateHandle( /// received on the output buffer. Currently, the result buffer will store the total number of bytes received from /// the FPGA. /// - Constants.Status GetResultBufferPointer(IntPtr fpgaHandle, uint whichBuffer, out IntPtr resultBufferPtr); + CatapultConstants.Status GetResultBufferPointer(IntPtr fpgaHandle, uint whichBuffer, out IntPtr resultBufferPtr); /// /// This function allows users to read soft shell registers. This function is thread- and multiprocess-safe; however /// the current implementation of this API uses multiple non-atomic PIOs to the shell protected by a software named /// global mutex. /// - Constants.Status ReadSoftRegister(IntPtr fpgaHandle, uint address, out ulong readValue); + CatapultConstants.Status ReadSoftRegister(IntPtr fpgaHandle, uint address, out ulong readValue); /// /// This function allows users to write soft shell registers. The same conditions described in apply here as well. /// - Constants.Status WriteSoftRegister(IntPtr fpgaHandle, uint address, ulong writeValue); + CatapultConstants.Status WriteSoftRegister(IntPtr fpgaHandle, uint address, ulong writeValue); /// /// This function indicates whether an input buffer is full and unavailable for writing by the host. /// - Constants.Status GetInputBufferFull(IntPtr fpgaHandle, uint whichBuffer, out bool isFull); + CatapultConstants.Status GetInputBufferFull(IntPtr fpgaHandle, uint whichBuffer, out bool isFull); /// /// This function indicates whether an output buffer was written by the FPGA and available for reading by the host. /// - Constants.Status GetOutputBufferDone(IntPtr fpgaHandle, uint whichBuffer, out bool isDone); + CatapultConstants.Status GetOutputBufferDone(IntPtr fpgaHandle, uint whichBuffer, out bool isDone); /// /// This function initiates a send operation that transfers the contents of a specified input buffer to the FPGA. @@ -314,7 +314,7 @@ Constants.Status CreateHandle( /// responsible for verifying that the input buffer is available for use prior to calling this function, e.g., by /// checking the return value of . /// - Constants.Status SendInputBuffer(IntPtr fpgaHandle, uint whichBuffer, uint sizeBytes, bool useInterrupt = true); + CatapultConstants.Status SendInputBuffer(IntPtr fpgaHandle, uint whichBuffer, uint sizeBytes, bool useInterrupt = true); /// /// This function blocks the calling thread until a message is received from the FPGA for a given output buffer. The @@ -328,14 +328,14 @@ Constants.Status CreateHandle( /// specified duration (in seconds). Setting the timeout to zero will result in an INFINITE wait. /// /// - /// if on timeout, otherwise . + /// if on timeout, otherwise . /// - Constants.Status WaitOutputBuffer( + CatapultConstants.Status WaitOutputBuffer( IntPtr fpgaHandle, uint whichBuffer, out uint pBytesReceived, bool useInterrupt = true, - double timeoutInSeconds = Constants.WaitOutputBufferTimeoutDefaultSeconds); + double timeoutInSeconds = CatapultConstants.WaitOutputBufferTimeoutDefaultSeconds); /// /// This function allows a user to discard a particular output buffer after its contents have already been consumed @@ -343,7 +343,7 @@ Constants.Status WaitOutputBuffer( /// waiting on an output buffer using . It is /// harmless to call this function even if no data is expected from the FPGA. /// - Constants.Status DiscardOutputBuffer(IntPtr fpgaHandle, uint whichBuffer); + CatapultConstants.Status DiscardOutputBuffer(IntPtr fpgaHandle, uint whichBuffer); #endregion FPGACoreLib } diff --git a/src/Hastlayer/Hast.Catapult/Services/CatapultCommunicationService.cs b/src/Hastlayer/Hast.Catapult/Services/CatapultCommunicationService.cs index 05bfb113..ce1a2cc0 100644 --- a/src/Hastlayer/Hast.Catapult/Services/CatapultCommunicationService.cs +++ b/src/Hastlayer/Hast.Catapult/Services/CatapultCommunicationService.cs @@ -8,7 +8,7 @@ using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; -using static Hast.Catapult.Constants; +using static Hast.Catapult.CatapultConstants; namespace Hast.Catapult.Services; @@ -21,7 +21,7 @@ public class CatapultCommunicationService : CommunicationServiceBase private readonly IDevicePoolManager _devicePoolManager; private readonly ILogger _catapultLibraryLogger; - public override string ChannelName => Constants.ChannelName; + public override string ChannelName => CatapultConstants.ChannelName; public CatapultCommunicationService( IDevicePoolPopulator devicePoolPopulator, From 7f419d444ff9e2a0fd77eecf4da8f0b54067aca2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Thu, 19 Oct 2023 17:04:21 +0200 Subject: [PATCH 51/53] Fix remaining CA1724 (Type Names Should Not Match Namespaces). --- .globalconfig | 2 +- .../Hast.Catapult/CatapultLibrary.cs | 76 ++++++------- .../Catapult.cs} | 12 ++- .../Hast.Catapult/Drivers/CatapultDriver.cs | 2 +- .../CatapultFunctionResultException.cs | 4 +- .../Hast.Catapult/ICatapultNativeLibrary.cs | 102 +++++++++--------- .../Services/CatapultCommunicationService.cs | 4 +- .../Hast.Communication/Constants/Ethernet.cs | 12 --- .../Constants/EthernetPorts.cs | 7 ++ .../Constants/EthernetSignals.cs | 7 ++ .../Services/EthernetCommunicationService.cs | 2 +- .../Services/FpgaIpEndpointFinder.cs | 4 +- .../SimpleMemory/SimpleMemory.cs | 2 + .../Hast.VhdlBuilder/GlobalSuppressions.cs | 9 +- .../Services/VitisCommunicationService.cs | 2 +- src/Hastlayer/Hast.Xilinx/Constants.cs | 6 -- src/Hastlayer/Hast.Xilinx/Constants/Vitis.cs | 6 ++ .../Drivers/VitisDeviceDriverBase.cs | 3 +- .../Hast.Xilinx/Drivers/ZynqDriverBase.cs | 3 +- 19 files changed, 140 insertions(+), 125 deletions(-) rename src/Hastlayer/Hast.Catapult/{CatapultConstants.cs => Constants/Catapult.cs} (96%) create mode 100644 src/Hastlayer/Hast.Communication/Constants/EthernetPorts.cs create mode 100644 src/Hastlayer/Hast.Communication/Constants/EthernetSignals.cs delete mode 100644 src/Hastlayer/Hast.Xilinx/Constants.cs create mode 100644 src/Hastlayer/Hast.Xilinx/Constants/Vitis.cs diff --git a/.globalconfig b/.globalconfig index d10e1314..f657e179 100644 --- a/.globalconfig +++ b/.globalconfig @@ -4,6 +4,6 @@ is_global = true # Microsoft.CodeAnalysis.NetAnalyzers rules dotnet_diagnostic.CA1062.severity = none -dotnet_diagnostic.CA1724.severity = none + dotnet_diagnostic.CA1848.severity = none dotnet_diagnostic.CA2007.severity = none diff --git a/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs b/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs index 758d3d2b..812a2d4d 100644 --- a/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs +++ b/src/Hastlayer/Hast.Catapult/CatapultLibrary.cs @@ -11,8 +11,8 @@ using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; -using InputHeaderSizes = Hast.Catapult.CatapultConstants.InputHeaderSizes; -using OutputHeaderSizes = Hast.Catapult.CatapultConstants.OutputHeaderSizes; +using InputHeaderSizes = Hast.Catapult.Constants.Catapult.InputHeaderSizes; +using OutputHeaderSizes = Hast.Catapult.Constants.Catapult.OutputHeaderSizes; namespace Hast.Catapult; @@ -31,7 +31,7 @@ public sealed class CatapultLibrary : IDisposable /// /// Gets the name of the instance (Catapult:N where N is the PCIe endpoint number). /// - public string InstanceName => StringHelper.CreateInvariant($"{CatapultConstants.ChannelName}:{PcieEndpointNumber}"); + public string InstanceName => StringHelper.CreateInvariant($"{Constants.Catapult.ChannelName}:{PcieEndpointNumber}"); /// /// Contains the latest tasks to be awaited when starting a new task. @@ -96,15 +96,15 @@ public bool PcieEnabled get { VerifyResult(NativeLibrary.ReadShellRegister(_handle, 0, out uint pcie)); - return (pcie & CatapultConstants.RegisterMaskPcieEnabled) != 0; + return (pcie & Constants.Catapult.RegisterMaskPcieEnabled) != 0; } private set { VerifyResult(NativeLibrary.ReadShellRegister(_handle, 0, out uint pcie)); // Set control_register[6] - if (value) pcie |= CatapultConstants.RegisterMaskPcieEnabled; - else pcie &= ~CatapultConstants.RegisterMaskPcieEnabled; + if (value) pcie |= Constants.Catapult.RegisterMaskPcieEnabled; + else pcie &= ~Constants.Catapult.RegisterMaskPcieEnabled; VerifyResult(NativeLibrary.WriteShellRegister(_handle, 0, pcie)); } @@ -129,10 +129,10 @@ private set /// parameter and a string as its second. Note that the strings all end with newline character. /// public CatapultLibrary( - string libraryPath = CatapultConstants.DefaultLibraryPath, + string libraryPath = Constants.Catapult.DefaultLibraryPath, string versionDefinitionsFile = null, string versionManifestFile = null, - int endpointNumber = CatapultConstants.PcieHipNumber, + int endpointNumber = Constants.Catapult.PcieHipNumber, CatapultLogFunction logFunction = null) { LogFunction = logFunction; @@ -153,7 +153,7 @@ public CatapultLibrary( VerifyResult(createStatus); // Configure hardware settings & enable hardware. - SetSoftRegister(CatapultConstants.ConfigDram.Channel0, 0); + SetSoftRegister(Constants.Catapult.ConfigDram.Channel0, 0); PcieEnabled = true; // Query device info. @@ -165,9 +165,9 @@ public CatapultLibrary( BufferSize = (int)count; // Load in configuration from the soft registers - var allowedSlots = (int)GetSoftRegister(CatapultConstants.SoftRegisters.AllowedSlots); + var allowedSlots = (int)GetSoftRegister(Constants.Catapult.SoftRegisters.AllowedSlots); if (allowedSlots > 0 && allowedSlots < BufferCount) BufferCount = allowedSlots; - var bufferPayloadSize = (int)GetSoftRegister(CatapultConstants.SoftRegisters.BufferPayloadSize); + var bufferPayloadSize = (int)GetSoftRegister(Constants.Catapult.SoftRegisters.BufferPayloadSize); if (bufferPayloadSize > 0 && bufferPayloadSize < BufferPayloadSize) BufferPayloadSize = bufferPayloadSize; // Set up the task tracker. @@ -178,11 +178,11 @@ public CatapultLibrary( public static CatapultLibrary Create( IDictionary config, ILogger logger, - int endpointNumber = CatapultConstants.PcieHipNumber) + int endpointNumber = Constants.Catapult.PcieHipNumber) { - var libraryPath = config.GetMaybe(CatapultConstants.DefaultLibraryPath) ?? CatapultConstants.DefaultLibraryPath; - var versionDefinitionsFile = config.GetMaybe(CatapultConstants.ConfigKeys.VersionDefinitionsFile); - var versionManifestFile = config.GetMaybe(CatapultConstants.ConfigKeys.VersionManifestFile); + var libraryPath = config.GetMaybe(Constants.Catapult.DefaultLibraryPath) ?? Constants.Catapult.DefaultLibraryPath; + var versionDefinitionsFile = config.GetMaybe(Constants.Catapult.ConfigKeys.VersionDefinitionsFile); + var versionManifestFile = config.GetMaybe(Constants.Catapult.ConfigKeys.VersionManifestFile); return new CatapultLibrary( (string)libraryPath, @@ -191,28 +191,28 @@ public static CatapultLibrary Create( endpointNumber: endpointNumber, logFunction: (flagValue, text) => { - var flag = (CatapultConstants.Log)flagValue; + var flag = (Constants.Catapult.Log)flagValue; // This function proxies special log entries so they can't be static. #pragma warning disable CA2254 // Template should be a static expression switch (flag) { - case CatapultConstants.Log.None: + case Constants.Catapult.Log.None: return; - case CatapultConstants.Log.Info: + case Constants.Catapult.Log.Info: logger.LogInformation(text); break; - case CatapultConstants.Log.Debug: - case CatapultConstants.Log.Verbose: + case Constants.Catapult.Log.Debug: + case Constants.Catapult.Log.Verbose: logger.LogDebug(text); break; - case CatapultConstants.Log.Error: + case Constants.Catapult.Log.Error: logger.LogError(text); break; - case CatapultConstants.Log.Fatal: + case Constants.Catapult.Log.Fatal: logger.LogCritical(text); break; - case CatapultConstants.Log.Warn: + case Constants.Catapult.Log.Warn: logger.LogWarning(text); break; default: @@ -236,12 +236,12 @@ public void Dispose() // close the PICe connection via `PcieEnabled = false;` right after that anyway. } - LogLine(CatapultConstants.Log.Info, "Closing down the FPGA..."); + LogLine(Constants.Catapult.Log.Info, "Closing down the FPGA..."); PcieEnabled = false; NativeLibrary.CloseHandle(Handle); NativeLibrary.Dispose(); - LogLine(CatapultConstants.Log.Info, "Closed down the FPGA..."); + LogLine(Constants.Catapult.Log.Info, "Closed down the FPGA..."); _isDisposed = true; } @@ -261,9 +261,9 @@ public void WaitClean() /// /// The return value from the library function. /// Thrown when the status isn't SUCCESS. - public void VerifyResult(CatapultConstants.Status status) + public void VerifyResult(Constants.Catapult.Status status) { - if (status == CatapultConstants.Status.Success) return; + if (status == Constants.Catapult.Status.Success) return; var errorMessage = new StringBuilder(512); NativeLibrary.GetLastError(); @@ -436,7 +436,7 @@ private async Task> AssignMultiSliceJobAsync( /// The resulting output from the FPGA. private async Task> RunJobAsync(int bufferIndex, Memory inputData, bool ignoreResponse) { - LogLineInvariant(CatapultConstants.Log.Info, $"Job on slot #{bufferIndex} starting..."); + LogLineInvariant(Constants.Catapult.Log.Info, $"Job on slot #{bufferIndex} starting..."); Debug.Assert( bufferIndex < BufferCount, StringHelper.CreateInvariant($"The buffer index is out of range. (current: {bufferIndex}, max: {BufferCount})")); @@ -459,16 +459,16 @@ private async Task> RunJobAsync(int bufferIndex, Memory input // If the input message isn't 64B aligned, pad it with zeros. var payloadBytes = inputData.Length - InputHeaderSizes.Total; - if (payloadBytes % CatapultConstants.BufferChunkBytes != 0) + if (payloadBytes % Constants.Catapult.BufferChunkBytes != 0) { - int paddedPayloadSize = CatapultConstants.BufferChunkBytes * ((payloadBytes / CatapultConstants.BufferChunkBytes) + 1); + int paddedPayloadSize = Constants.Catapult.BufferChunkBytes * ((payloadBytes / Constants.Catapult.BufferChunkBytes) + 1); if (paddedPayloadSize <= BufferPayloadSize) { LogLine( - CatapultConstants.Log.Warn, + Constants.Catapult.Log.Warn, StringHelper.Concatenate( - $"Incoming payload ({payloadBytes}B) must be aligned to {CatapultConstants.BufferChunkBytes}B! ", - $"Padding for {CatapultConstants.BufferChunkBytes - paddedPayloadSize}B...")); + $"Incoming payload ({payloadBytes}B) must be aligned to {Constants.Catapult.BufferChunkBytes}B! ", + $"Padding for {Constants.Catapult.BufferChunkBytes - paddedPayloadSize}B...")); var padded = new byte[paddedPayloadSize + InputHeaderSizes.Total]; inputData.CopyTo(padded); inputData = padded; @@ -478,7 +478,7 @@ private async Task> RunJobAsync(int bufferIndex, Memory input VerifyResult(NativeLibrary.GetInputBufferPointer(_handle, slot, out var inputBuffer)); LogLineInvariant( - CatapultConstants.Log.Debug, + Constants.Catapult.Log.Debug, $"Buffer #{slot} @ {inputBuffer.ToInt64()} input start: {Marshal.PtrToStructure(inputBuffer)}"); // Upload data into input buffer. @@ -522,13 +522,13 @@ private async Task> ReceiveJobResultsAsync(uint slot) } LogLineInvariant( - CatapultConstants.Log.Debug, + Constants.Catapult.Log.Debug, $"Buffer #{slot} @ {outputBuffer.ToInt64()} output start: {Marshal.PtrToStructure(outputBuffer)}"); // Signal that we are done. NativeLibrary.DiscardOutputBuffer(_handle, slot); - LogFunction?.Invoke((uint)CatapultConstants.Log.Info, $"Job on slot #{slot} finished!{Environment.NewLine}"); + LogFunction?.Invoke((uint)Constants.Catapult.Log.Info, $"Job on slot #{slot} finished!{Environment.NewLine}"); return resultMemory; } @@ -540,10 +540,10 @@ private Task TesterWriteLineAsync(string format, params object[] objects) return TesterOutput.WriteLineAsync(format); } - private void LogLine(CatapultConstants.Log level, string text) => + private void LogLine(Constants.Catapult.Log level, string text) => LogFunction?.Invoke((uint)level, text + Environment.NewLine); - private void LogLineInvariant(CatapultConstants.Log level, FormattableString text) => + private void LogLineInvariant(Constants.Catapult.Log level, FormattableString text) => LogFunction?.Invoke((uint)level, text.ToString(CultureInfo.InvariantCulture) + Environment.NewLine); public override string ToString() => InstanceName; diff --git a/src/Hastlayer/Hast.Catapult/CatapultConstants.cs b/src/Hastlayer/Hast.Catapult/Constants/Catapult.cs similarity index 96% rename from src/Hastlayer/Hast.Catapult/CatapultConstants.cs rename to src/Hastlayer/Hast.Catapult/Constants/Catapult.cs index 29067047..7e73b655 100644 --- a/src/Hastlayer/Hast.Catapult/CatapultConstants.cs +++ b/src/Hastlayer/Hast.Catapult/Constants/Catapult.cs @@ -1,12 +1,16 @@ using System; using System.Diagnostics.CodeAnalysis; -namespace Hast.Catapult; +namespace Hast.Catapult.Constants; -public static class CatapultConstants +[SuppressMessage( + "Naming", + "CA1724: Type names should not match namespaces", + Justification = "This class contains the Catapult-specific constants so this is an appropriate name.")] +public static class Catapult { - public const string Catapult = nameof(Catapult); - public const string ChannelName = Catapult; + public const string DeviceName = nameof(Catapult); + public const string ChannelName = DeviceName; public const string DefaultLibraryPath = "FpgaCoreLib"; diff --git a/src/Hastlayer/Hast.Catapult/Drivers/CatapultDriver.cs b/src/Hastlayer/Hast.Catapult/Drivers/CatapultDriver.cs index 80445cea..820a0bba 100644 --- a/src/Hastlayer/Hast.Catapult/Drivers/CatapultDriver.cs +++ b/src/Hastlayer/Hast.Catapult/Drivers/CatapultDriver.cs @@ -11,7 +11,7 @@ namespace Hast.Catapult.Drivers; public class CatapultDriver : IDeviceDriver { - public const string DeviceName = CatapultConstants.Catapult; + public const string DeviceName = Constants.Catapult.DeviceName; private readonly ITimingReportParser _timingReportParser; private readonly object _timingReportParserLock = new(); diff --git a/src/Hastlayer/Hast.Catapult/Exceptions/CatapultFunctionResultException.cs b/src/Hastlayer/Hast.Catapult/Exceptions/CatapultFunctionResultException.cs index 286d927a..c780939c 100644 --- a/src/Hastlayer/Hast.Catapult/Exceptions/CatapultFunctionResultException.cs +++ b/src/Hastlayer/Hast.Catapult/Exceptions/CatapultFunctionResultException.cs @@ -12,11 +12,11 @@ public class CatapultFunctionResultException : Exception /// /// Gets the status returned by the native function call. /// - public CatapultConstants.Status Status { get; private set; } + public Constants.Catapult.Status Status { get; private set; } public CatapultFunctionResultException() { } - public CatapultFunctionResultException(CatapultConstants.Status status, string message) + public CatapultFunctionResultException(Constants.Catapult.Status status, string message) : this(string.IsNullOrWhiteSpace(message) ? status.ToString() : message) => Status = status; public CatapultFunctionResultException(string message) diff --git a/src/Hastlayer/Hast.Catapult/ICatapultNativeLibrary.cs b/src/Hastlayer/Hast.Catapult/ICatapultNativeLibrary.cs index 4fda691f..e94b76d6 100644 --- a/src/Hastlayer/Hast.Catapult/ICatapultNativeLibrary.cs +++ b/src/Hastlayer/Hast.Catapult/ICatapultNativeLibrary.cs @@ -2,6 +2,7 @@ using System; using System.Runtime.InteropServices; using System.Text; +using static Hast.Catapult.Constants.Catapult; namespace Hast.Catapult; @@ -11,8 +12,8 @@ namespace Hast.Catapult; /// The function used by logging in FpgaCoreLib.dll and the CatapultLibrary class. /// /// -/// The value of a flag enum converted into uint. This can be used to filter out specific -/// types of messages, eg . +/// The value of a flag enum converted into uint. This can be used to filter out specific +/// types of messages, eg . /// /// The log message. Ends with newline so Write should be used instead of WriteLine. [UnmanagedFunctionPointer(CallingConvention.Cdecl)] @@ -30,38 +31,38 @@ public interface ICatapultNativeLibrary : IDisposable /// /// This function retrieves the total number of shell registers. /// - CatapultConstants.Status GetNumberShellRegisters(IntPtr fpgaHandle, out uint numShellRegs); + Status GetNumberShellRegisters(IntPtr fpgaHandle, out uint numShellRegs); /// /// This function allows users to read shell registers. It is both multithreaded- and multiprocesss-safe. /// - CatapultConstants.Status ReadShellRegister(IntPtr fpgaHandle, uint registerNumber, out uint readValue); + Status ReadShellRegister(IntPtr fpgaHandle, uint registerNumber, out uint readValue); /// /// This function allows users to write shell registers. It is both multithreaded- and multiprocess-safe. /// - CatapultConstants.Status WriteShellRegister(IntPtr fpgaHandle, uint registerNumber, uint writeValue); + Status WriteShellRegister(IntPtr fpgaHandle, uint registerNumber, uint writeValue); /// /// This functions returns whether the loaded FPGA image is a Golden image or not. /// - CatapultConstants.Status IsGoldenImage(IntPtr fpgaHandle, out bool isGolden, out uint roleID, out uint roleVersion); + Status IsGoldenImage(IntPtr fpgaHandle, out bool isGolden, out uint roleID, out uint roleVersion); /// /// This function returns the RSU Image ID. /// - CatapultConstants.Status ReadRsuImageId(IntPtr fpgaHandle, out uint pImageId); + Status ReadRsuImageId(IntPtr fpgaHandle, out uint pImageId); /// /// This function forces FPGA reconfiguration. It is not multithreaded- or multiprocess-safe. The act of /// re-configuration will cause the existing FPGA handles to be closed. /// - CatapultConstants.Status Reconfig(IntPtr[] fpgaHandles, uint numHandles, bool reconfigToGolden); + Status Reconfig(IntPtr[] fpgaHandles, uint numHandles, bool reconfigToGolden); /// /// This function is used to update the flash images on the FPGA. It can either be used to update the golden or app - /// image. Writing to the golden image requires explicitly passing in - /// during handle creation. WARNING: writing a bad golden image to the FPGA is a career-limiting move and can cause + /// image. Writing to the golden image requires explicitly passing in during + /// handle creation. WARNING: writing a bad golden image to the FPGA is a career-limiting move and can cause /// irreparable damage. This function is protected by an internal mutex against other calls to /// WriteFlashImage(IntPtr, bool, string) c>, , /// CaptureFlashImage (IntPtr, bool, string) and - /// When a timeout is triggered, it returns . - CatapultConstants.Status WriteFlashImageEx( + /// When a timeout is triggered, it returns . + Status WriteFlashImageEx( IntPtr fpgaHandle, bool writeToGolden, string rpdFilename, - uint timeoutInMs = CatapultConstants.DefaultFlashAccessTimeoutInMilliseconds); + uint timeoutInMs = DefaultFlashAccessTimeoutInMilliseconds); /// /// This function is used to read the flash images from the FPGA to a file. It can either be used to read the golden @@ -88,77 +89,77 @@ CatapultConstants.Status WriteFlashImageEx( /// Determines how long to wait in milliseconds for acquiring the mutex. The default wait time is set according to /// the worst-case flash write time multiplied by 2 (five minutes). Setting it to INFINITE removes the timeout. /// - CatapultConstants.Status CaptureFlashImageEx( + Status CaptureFlashImageEx( IntPtr fpgaHandle, bool isGolden, string rpdFilename, - uint timeoutInMs = CatapultConstants.DefaultFlashAccessTimeoutInMilliseconds); + uint timeoutInMs = DefaultFlashAccessTimeoutInMilliseconds); /// /// Disable non-maskable interrupt error reporting. Needed during FPGA reconfiguration. It is not multithreaded- or /// multiprocess-safe. /// - CatapultConstants.Status DisableNmi(IntPtr fpgaHandle); + Status DisableNmi(IntPtr fpgaHandle); /// /// Sanity check: FPGA reconfig often fails simply because the FPGA vendor/device ID changed after reconfig Will /// need to use RSU -rootportReload first in order to restore the ability to open an FPGA handle. /// - CatapultConstants.Status ReadVendorDeviceId(IntPtr fpgaHandle, out uint vendorId, out uint deviceId); + Status ReadVendorDeviceId(IntPtr fpgaHandle, out uint vendorId, out uint deviceId); /// /// Disables and re-enables instances of only the port filter driver that are believed to be upstream of the FPGA. /// May not target all needed instances, but this should definitely not target network or GPU or other things that /// sometimes make crash the machine. /// - CatapultConstants.Status ReviveRootportNoDriver(); + Status ReviveRootportNoDriver(); /// /// Disables and re-enables all instances of the root port filter driver. Useful if the FPGA device fails to start /// after reconfig, potentially saves a reboot. /// - CatapultConstants.Status CycleRootportEnabledNoDriver(); + Status CycleRootportEnabledNoDriver(); /// /// Disables and re-enables the FPGA in device manager with no driver installed (?). It is not multithreaded- or /// multiprocess-safe. /// - CatapultConstants.Status CycleDeviceEnabledNoDriver(); + Status CycleDeviceEnabledNoDriver(); /// /// Used in JTAG-based reconfiguration. Call this function before JTAG reconfiguration to disable AER and error /// reporting. It is not multithreaded- or multiprocess-safe. /// - CatapultConstants.Status PrepForReconfig(IntPtr[] fpgaHandles, uint numHandles); + Status PrepForReconfig(IntPtr[] fpgaHandles, uint numHandles); /// /// Used in JTAG-based reconfiguration. Call this function after JTAG reconfiguration to re-enable AER and error /// reporting. It is not multithreaded- or multiprocess-safe. /// - CatapultConstants.Status ResetAfterReconfig(IntPtr[] fpgaHandles, uint numHandles); + Status ResetAfterReconfig(IntPtr[] fpgaHandles, uint numHandles); /// /// Retrieves FPGA shell statistics. /// - CatapultConstants.Status ReadStatistic(IntPtr fpgaHandle, uint statType, out uint value); + Status ReadStatistic(IntPtr fpgaHandle, uint statType, out uint value); /// /// This function enables or disables network bypass mode Setting 'forceBypass' to TRUE will disable the soft shell /// network and cause all network traffic to go through the shell bridge. /// - CatapultConstants.Status SetNetworkBypass(IntPtr fpgaHandle, bool forceBypass); + Status SetNetworkBypass(IntPtr fpgaHandle, bool forceBypass); /// /// Trigger soft reset. /// - CatapultConstants.Status TriggerSoftReset(IntPtr fpgaHandle, uint resetType); + Status TriggerSoftReset(IntPtr fpgaHandle, uint resetType); /// /// Attempt to set the slot size and number of slots. Will fail if requested settings are invalid or cannot be /// attained. Bytes per slot must be a multiple of 4096. Number of slots cannot be larger than that supported by the /// hardware. /// - CatapultConstants.Status SetSlotSize(IntPtr[] fpgaHandles, uint numHandles, uint bytesPerSlot, uint numSlots); + Status SetSlotSize(IntPtr[] fpgaHandles, uint numHandles, uint bytesPerSlot, uint numSlots); #endregion FPGAManagementLib @@ -184,15 +185,14 @@ CatapultConstants.Status CaptureFlashImageEx( /// /// The optional last argument allows the user to specify a logging callback function. The user-defined function /// must accept a 'loglevel' argument, which classifies the log entry (e.g., verbose, informational, debug, etc) and - /// an ANSI string, which contains a single log entry. The enumeration is derived from - /// the FPGA_LOG_* flags in the original library define all the possible (and non-mutually-exclusive) severity - /// levels. + /// an ANSI string, which contains a single log entry. The enumeration is derived from the + /// FPGA_LOG_* flags in the original library define all the possible (and non-mutually-exclusive) severity levels. /// /// - /// if the device is present or if the device is not present. + /// if the device is present or if the device + /// is not present. /// - CatapultConstants.Status IsDevicePresent( + Status IsDevicePresent( string pchVerManifestFile, [MarshalAs(UnmanagedType.FunctionPtr)] CatapultLogFunction logFunc); @@ -217,7 +217,7 @@ CatapultConstants.Status IsDevicePresent( /// files are searched relative to the DLL path. /// /// Optional logging callback function. - CatapultConstants.Status CreateHandle( + Status CreateHandle( out IntPtr fpgaHandle, uint endpointNumber, uint flags, @@ -231,32 +231,32 @@ CatapultConstants.Status CreateHandle( /// cref="CreateHandle(out IntPtr, uint, uint, StringBuilder, StringBuilder, CatapultLogFunction)"/>. By default, /// the definitions are listed in VersionDefinitions.ini. /// - CatapultConstants.Status GetVersion(IntPtr fpgaHandle, string pchVerKey, out uint pVersion); + Status GetVersion(IntPtr fpgaHandle, string pchVerKey, out uint pVersion); /// /// This function should be called to release and close an FPGA handle. /// - CatapultConstants.Status CloseHandle(IntPtr fpgaHandle); + Status CloseHandle(IntPtr fpgaHandle); /// /// This function retrieves the total number of PCIe buffers available for host-to-FPGA communication. /// - CatapultConstants.Status GetNumberBuffers(IntPtr fpgaHandle, out uint numBuffers); + Status GetNumberBuffers(IntPtr fpgaHandle, out uint numBuffers); /// /// This function retrieves the total number of bytes available to use, per FPGA PCIe buffer. /// - CatapultConstants.Status GetBufferSize(IntPtr fpgaHandle, out uint bufferBytes); + Status GetBufferSize(IntPtr fpgaHandle, out uint bufferBytes); /// /// Returns the last error occurred. /// - CatapultConstants.Status GetLastError(); + Status GetLastError(); /// /// Provides error string for the last error occurred. /// - CatapultConstants.Status GetLastErrorText([MarshalAs(UnmanagedType.LPStr)] StringBuilder pErrorTextBuf, int cbBufSize); + Status GetLastErrorText([MarshalAs(UnmanagedType.LPStr)] StringBuilder pErrorTextBuf, int cbBufSize); /// /// This function retrieves a user-mapped pointer to a pinned region of kernel memory that is typically written by @@ -264,14 +264,14 @@ CatapultConstants.Status CreateHandle( /// cref="GetBufferSize(IntPtr, out uint)"/>. The total number of buffers available can be queried using . /// - CatapultConstants.Status GetInputBufferPointer(IntPtr fpgaHandle, uint whichBuffer, out IntPtr inputBufferPtr); + Status GetInputBufferPointer(IntPtr fpgaHandle, uint whichBuffer, out IntPtr inputBufferPtr); /// /// This function retrieves a user-mapped pointer to a pinned region of kernel memory that is typically written by /// the FPGA, and read by the host system. The available buffer capacity is finite and should be queried using . /// - CatapultConstants.Status GetOutputBufferPointer(IntPtr fpgaHandle, uint whichBuffer, out IntPtr outputBufferPtr); + Status GetOutputBufferPointer(IntPtr fpgaHandle, uint whichBuffer, out IntPtr outputBufferPtr); /// /// This function retrieves a user-mapped pointer to a pinned region of kernel memory that is typically written by @@ -279,30 +279,30 @@ CatapultConstants.Status CreateHandle( /// received on the output buffer. Currently, the result buffer will store the total number of bytes received from /// the FPGA. /// - CatapultConstants.Status GetResultBufferPointer(IntPtr fpgaHandle, uint whichBuffer, out IntPtr resultBufferPtr); + Status GetResultBufferPointer(IntPtr fpgaHandle, uint whichBuffer, out IntPtr resultBufferPtr); /// /// This function allows users to read soft shell registers. This function is thread- and multiprocess-safe; however /// the current implementation of this API uses multiple non-atomic PIOs to the shell protected by a software named /// global mutex. /// - CatapultConstants.Status ReadSoftRegister(IntPtr fpgaHandle, uint address, out ulong readValue); + Status ReadSoftRegister(IntPtr fpgaHandle, uint address, out ulong readValue); /// /// This function allows users to write soft shell registers. The same conditions described in apply here as well. /// - CatapultConstants.Status WriteSoftRegister(IntPtr fpgaHandle, uint address, ulong writeValue); + Status WriteSoftRegister(IntPtr fpgaHandle, uint address, ulong writeValue); /// /// This function indicates whether an input buffer is full and unavailable for writing by the host. /// - CatapultConstants.Status GetInputBufferFull(IntPtr fpgaHandle, uint whichBuffer, out bool isFull); + Status GetInputBufferFull(IntPtr fpgaHandle, uint whichBuffer, out bool isFull); /// /// This function indicates whether an output buffer was written by the FPGA and available for reading by the host. /// - CatapultConstants.Status GetOutputBufferDone(IntPtr fpgaHandle, uint whichBuffer, out bool isDone); + Status GetOutputBufferDone(IntPtr fpgaHandle, uint whichBuffer, out bool isDone); /// /// This function initiates a send operation that transfers the contents of a specified input buffer to the FPGA. @@ -314,7 +314,7 @@ CatapultConstants.Status CreateHandle( /// responsible for verifying that the input buffer is available for use prior to calling this function, e.g., by /// checking the return value of . /// - CatapultConstants.Status SendInputBuffer(IntPtr fpgaHandle, uint whichBuffer, uint sizeBytes, bool useInterrupt = true); + Status SendInputBuffer(IntPtr fpgaHandle, uint whichBuffer, uint sizeBytes, bool useInterrupt = true); /// /// This function blocks the calling thread until a message is received from the FPGA for a given output buffer. The @@ -328,14 +328,14 @@ CatapultConstants.Status CreateHandle( /// specified duration (in seconds). Setting the timeout to zero will result in an INFINITE wait. /// /// - /// if on timeout, otherwise . + /// if on timeout, otherwise . /// - CatapultConstants.Status WaitOutputBuffer( + Status WaitOutputBuffer( IntPtr fpgaHandle, uint whichBuffer, out uint pBytesReceived, bool useInterrupt = true, - double timeoutInSeconds = CatapultConstants.WaitOutputBufferTimeoutDefaultSeconds); + double timeoutInSeconds = WaitOutputBufferTimeoutDefaultSeconds); /// /// This function allows a user to discard a particular output buffer after its contents have already been consumed @@ -343,7 +343,7 @@ CatapultConstants.Status WaitOutputBuffer( /// waiting on an output buffer using . It is /// harmless to call this function even if no data is expected from the FPGA. /// - CatapultConstants.Status DiscardOutputBuffer(IntPtr fpgaHandle, uint whichBuffer); + Status DiscardOutputBuffer(IntPtr fpgaHandle, uint whichBuffer); #endregion FPGACoreLib } diff --git a/src/Hastlayer/Hast.Catapult/Services/CatapultCommunicationService.cs b/src/Hastlayer/Hast.Catapult/Services/CatapultCommunicationService.cs index ce1a2cc0..9e61ccc1 100644 --- a/src/Hastlayer/Hast.Catapult/Services/CatapultCommunicationService.cs +++ b/src/Hastlayer/Hast.Catapult/Services/CatapultCommunicationService.cs @@ -8,7 +8,7 @@ using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; -using static Hast.Catapult.CatapultConstants; +using static Hast.Catapult.Constants.Catapult; namespace Hast.Catapult.Services; @@ -21,7 +21,7 @@ public class CatapultCommunicationService : CommunicationServiceBase private readonly IDevicePoolManager _devicePoolManager; private readonly ILogger _catapultLibraryLogger; - public override string ChannelName => CatapultConstants.ChannelName; + public override string ChannelName => Constants.Catapult.ChannelName; public CatapultCommunicationService( IDevicePoolPopulator devicePoolPopulator, diff --git a/src/Hastlayer/Hast.Communication/Constants/Ethernet.cs b/src/Hastlayer/Hast.Communication/Constants/Ethernet.cs index 558843b8..fc05a8ac 100644 --- a/src/Hastlayer/Hast.Communication/Constants/Ethernet.cs +++ b/src/Hastlayer/Hast.Communication/Constants/Ethernet.cs @@ -3,16 +3,4 @@ public static class Ethernet { public const string ChannelName = nameof(Ethernet); - - public static class Ports - { - public const int WhoIsAvailableRequest = 34_050; - public const int WhoIsAvailableResponse = 33_000; - } - - public static class Signals - { - public const char Busy = 'b'; - public const char Ready = 'r'; - } } diff --git a/src/Hastlayer/Hast.Communication/Constants/EthernetPorts.cs b/src/Hastlayer/Hast.Communication/Constants/EthernetPorts.cs new file mode 100644 index 00000000..112a9b1d --- /dev/null +++ b/src/Hastlayer/Hast.Communication/Constants/EthernetPorts.cs @@ -0,0 +1,7 @@ +namespace Hast.Communication.Constants.CommunicationConstants; + +public static class EthernetPorts +{ + public const int WhoIsAvailableRequest = 34_050; + public const int WhoIsAvailableResponse = 33_000; +} diff --git a/src/Hastlayer/Hast.Communication/Constants/EthernetSignals.cs b/src/Hastlayer/Hast.Communication/Constants/EthernetSignals.cs new file mode 100644 index 00000000..1bf78ae1 --- /dev/null +++ b/src/Hastlayer/Hast.Communication/Constants/EthernetSignals.cs @@ -0,0 +1,7 @@ +namespace Hast.Communication.Constants.CommunicationConstants; + +public static class EthernetSignals +{ + public const char Busy = 'b'; + public const char Ready = 'r'; +} diff --git a/src/Hastlayer/Hast.Communication/Services/EthernetCommunicationService.cs b/src/Hastlayer/Hast.Communication/Services/EthernetCommunicationService.cs index f3ecf90f..1a370970 100644 --- a/src/Hastlayer/Hast.Communication/Services/EthernetCommunicationService.cs +++ b/src/Hastlayer/Hast.Communication/Services/EthernetCommunicationService.cs @@ -86,7 +86,7 @@ public override async Task ExecuteAsync( var executionCommandTypeResponseByte = await GetBytesFromStreamAsync(stream, 1); - if (executionCommandTypeResponseByte[0] != Ethernet.Signals.Ready) + if (executionCommandTypeResponseByte[0] != EthernetSignals.Ready) { throw new EthernetCommunicationException( "Awaited a ready signal from the FPGA after the execution byte was sent but received the following byte instead: " + diff --git a/src/Hastlayer/Hast.Communication/Services/FpgaIpEndpointFinder.cs b/src/Hastlayer/Hast.Communication/Services/FpgaIpEndpointFinder.cs index f2f57df7..14ab3099 100644 --- a/src/Hastlayer/Hast.Communication/Services/FpgaIpEndpointFinder.cs +++ b/src/Hastlayer/Hast.Communication/Services/FpgaIpEndpointFinder.cs @@ -36,7 +36,7 @@ public FpgaIpEndpointFinder(IClock clock, ILogger logger) Justification = "False positive, shouldn't replace the char constant with a literal.")] public async Task> FindFpgaEndpointsAsync() { - var broadcastEndpoint = new IPEndPoint(IPAddress.Broadcast, Ethernet.Ports.WhoIsAvailableRequest); + var broadcastEndpoint = new IPEndPoint(IPAddress.Broadcast, EthernetPorts.WhoIsAvailableRequest); // We need retries because somehow the FPGA doesn't always catch our request. _logger.LogInformation( @@ -59,7 +59,7 @@ public async Task> FindFpgaEndpointsAsync() .Where(addressInformation => addressInformation.Address.AddressFamily == AddressFamily.InterNetwork); endpoints.AddRange(ipv4AddressInformation.Select(addressInformation => - new IPEndPoint(addressInformation.Address, Ethernet.Ports.WhoIsAvailableResponse))); + new IPEndPoint(addressInformation.Address, EthernetPorts.WhoIsAvailableResponse))); } // Sending requests to all the found IP endpoints at the same time. diff --git a/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs b/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs index 34164953..726ec6a7 100644 --- a/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs +++ b/src/Hastlayer/Hast.Transformer/SimpleMemory/SimpleMemory.cs @@ -2,6 +2,7 @@ using Lombiq.HelpfulLibraries.Common.Utilities; using Microsoft.Extensions.Logging; using System; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace Hast.Transformer.SimpleMemory; @@ -18,6 +19,7 @@ namespace Hast.Transformer.SimpleMemory; /// be changed (i.e. no renames, new or re-ordered arguments) without making adequate changes to the VHDL library too. /// /// +[SuppressMessage("Naming", "CA1724: Type names should not match namespaces", Justification = "This name may not be changed.")] public class SimpleMemory { public const int MemoryCellSizeBytes = sizeof(int); diff --git a/src/Hastlayer/Hast.VhdlBuilder/GlobalSuppressions.cs b/src/Hastlayer/Hast.VhdlBuilder/GlobalSuppressions.cs index c6b9b3ba..87cf6607 100644 --- a/src/Hastlayer/Hast.VhdlBuilder/GlobalSuppressions.cs +++ b/src/Hastlayer/Hast.VhdlBuilder/GlobalSuppressions.cs @@ -8,10 +8,15 @@ [assembly: SuppressMessage( "Naming", "CA1716:Identifiers should not match keywords", - Justification = "This assembly contains representations of exactly those keywords.", + Justification = "This assembly contains representations of .NET/C# code, so partial or full overlap with magic words is expected.", Scope = "module")] [assembly: SuppressMessage( "Naming", "CA1711:Identifiers should not have incorrect suffix", - Justification = "This assembly contains representations of data types including those representing the types of the suffixes in question.", + Justification = "Same.", + Scope = "module")] +[assembly: SuppressMessage( + "Naming", + "CA1724: Type names should not match namespaces", + Justification = "Same.", Scope = "module")] diff --git a/src/Hastlayer/Hast.Vitis/Services/VitisCommunicationService.cs b/src/Hastlayer/Hast.Vitis/Services/VitisCommunicationService.cs index b0e9f740..9fded3da 100644 --- a/src/Hastlayer/Hast.Vitis/Services/VitisCommunicationService.cs +++ b/src/Hastlayer/Hast.Vitis/Services/VitisCommunicationService.cs @@ -15,7 +15,7 @@ namespace Hast.Vitis.Services; public class VitisCommunicationService : OpenClCommunicationService { private const int HbmSizeBytes = (int)Constants.Limits.HbmSizeBytes; - public override string ChannelName { get; } = Xilinx.Constants.VitisCommunicationChannelName; + public override string ChannelName { get; } = Xilinx.Constants.Vitis.CommunicationChannelName; public VitisCommunicationService( IDevicePoolPopulator devicePoolPopulator, diff --git a/src/Hastlayer/Hast.Xilinx/Constants.cs b/src/Hastlayer/Hast.Xilinx/Constants.cs deleted file mode 100644 index 921c9ba3..00000000 --- a/src/Hastlayer/Hast.Xilinx/Constants.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Hast.Xilinx; - -public static class Constants -{ - public const string VitisCommunicationChannelName = "Vitis"; -} diff --git a/src/Hastlayer/Hast.Xilinx/Constants/Vitis.cs b/src/Hastlayer/Hast.Xilinx/Constants/Vitis.cs new file mode 100644 index 00000000..d8a6c45e --- /dev/null +++ b/src/Hastlayer/Hast.Xilinx/Constants/Vitis.cs @@ -0,0 +1,6 @@ +namespace Hast.Xilinx.Constants; + +public static class Vitis +{ + public const string CommunicationChannelName = "Vitis"; +} diff --git a/src/Hastlayer/Hast.Xilinx/Drivers/VitisDeviceDriverBase.cs b/src/Hastlayer/Hast.Xilinx/Drivers/VitisDeviceDriverBase.cs index e65a567b..dd84bfab 100644 --- a/src/Hastlayer/Hast.Xilinx/Drivers/VitisDeviceDriverBase.cs +++ b/src/Hastlayer/Hast.Xilinx/Drivers/VitisDeviceDriverBase.cs @@ -1,6 +1,7 @@ using Hast.Layer; using Hast.Synthesis.Models; using Hast.Synthesis.Services; +using Hast.Xilinx.Constants; using Hast.Xilinx.Helpers; using System; using static Hast.Common.Constants.DataSize; @@ -24,7 +25,7 @@ protected IDeviceManifest InitializeManifest(VitisDeviceManifest manifest) { manifest.Name = DeviceName; manifest.ClockFrequencyHz = ClockFrequencyMhz * Mhz; - manifest.SupportedCommunicationChannelNames = new[] { Constants.VitisCommunicationChannelName }; + manifest.SupportedCommunicationChannelNames = new[] { Vitis.CommunicationChannelName }; // While there is much more DDR RAM on the device, the max object size in .NET is 2GB. So until we add // paging to SimpleMemory the limit is 2GB, see: https://github.com/Lombiq/Hastlayer-SDK/issues/27. manifest.AvailableMemoryBytes = 2 * GigaByte; diff --git a/src/Hastlayer/Hast.Xilinx/Drivers/ZynqDriverBase.cs b/src/Hastlayer/Hast.Xilinx/Drivers/ZynqDriverBase.cs index 3b99a61e..37be0e9b 100644 --- a/src/Hastlayer/Hast.Xilinx/Drivers/ZynqDriverBase.cs +++ b/src/Hastlayer/Hast.Xilinx/Drivers/ZynqDriverBase.cs @@ -1,6 +1,7 @@ using Hast.Layer; using Hast.Synthesis.Models; using Hast.Synthesis.Services; +using Hast.Xilinx.Constants; using Hast.Xilinx.Helpers; using System; using static Hast.Common.Constants.DataSize; @@ -18,7 +19,7 @@ protected ZynqDriverBase(ITimingReportParser timingReportParser) { Name = DeviceName, ClockFrequencyHz = 150 * Mhz, - SupportedCommunicationChannelNames = new[] { Constants.VitisCommunicationChannelName }, + SupportedCommunicationChannelNames = new[] { Vitis.CommunicationChannelName }, AvailableMemoryBytes = 1 * GigaByte, SupportsHbm = false, SupportedPlatforms = new[] From e73a72f66a0b3d8a2fd50cdca81f2578b81f5745 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20El-Saig?= Date: Thu, 19 Oct 2023 17:35:03 +0200 Subject: [PATCH 52/53] Add documentation to globalconfig. --- .globalconfig | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.globalconfig b/.globalconfig index f657e179..add9f55e 100644 --- a/.globalconfig +++ b/.globalconfig @@ -3,7 +3,17 @@ is_global = true # Code analysis rules for Hastlayer, extending Lombiq.Analyzers.globalconfig. # Microsoft.CodeAnalysis.NetAnalyzers rules + +# CA1062: Validate arguments of public methods. We disabled it, because it makes the code bloated and doesn't support +# `ArgumentNullException.ThrowIfNull()` either. dotnet_diagnostic.CA1062.severity = none +# CA1848: Use the LoggerMessage delegates. While this might slightly improve performance, it deters logging by turning +# it into a huge chore by breaking up the code flow and creating an unreasonable amount of boilerplate. dotnet_diagnostic.CA1848.severity = none + +# CA2007 : Consider calling ConfigureAwait on the awaited task. This warning is relevant to desktop apps that have a GUI +# thread. While Hastlayer can be used in GUI applications, itself does not operate a user interface so this warning is +# not relevant internally. A consumer of the library may call ConfigureAwait on one of the asynchronous public API +# methods if needed. dotnet_diagnostic.CA2007.severity = none From 96f3db9a61f6d78fffcb515bd44ab0dda49b2bc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Leh=C3=B3czky?= Date: Thu, 19 Oct 2023 18:42:09 +0200 Subject: [PATCH 53/53] Updating submodules to merged dev [skip ci] --- tools/Lombiq.Analyzers | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/Lombiq.Analyzers b/tools/Lombiq.Analyzers index 9973430f..4883e67c 160000 --- a/tools/Lombiq.Analyzers +++ b/tools/Lombiq.Analyzers @@ -1 +1 @@ -Subproject commit 9973430f923a9fca34fd7ea813470ec5ccbc0184 +Subproject commit 4883e67c5b9850e6eaf415d6718a6da146c9c3b9