From 9083135f76a6c80b4c1ec8806ce04348a62f11a8 Mon Sep 17 00:00:00 2001 From: Rian Drake Date: Thu, 15 Oct 2026 14:29:37 +1300 Subject: [PATCH] SOURCE DUMP v2 --- .../Brutal.Core.Analyzers/FixedAnalyzer.cs | 1032 ----------------- .../OperatingSystemAnalyzer.cs | 54 - .../Brutal.Core.Analyzers/Resources.cs | 66 -- .../Brutal.Core.Analyzers/VarAnalyzer.cs | 180 --- .../OperatingSystemFixProvider.cs | 76 -- .../Brutal.Core.CodeFixes/VarFixProvider.cs | 192 --- .../Brutal.FreeType/cmake/FindFreetype.cmake | 41 - .../RocketWerkz.Brutal.FreeType.targets | 10 - .../BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt | 175 +++ .../InteropHandleGenerator.cs | 58 - .../RocketWerkz.Brutal.Monitor.Host.targets | 29 - .../Brutal.Numerics.Analyzers/Resources.cs | 39 - .../RgbToGrayAnalyzer.cs | 143 --- .../SystemDrawingAnalyzer.cs | 73 -- .../SystemNumericsAnalyzer.cs | 68 -- .../RgbToGrayFixProvider.cs | 215 ---- .../PreferString8OverloadAnalyzer.cs | 188 --- .../Brutal.Strings.Analyzers/Resources.cs | 37 - .../SpanToStringAnalyzer.cs | 70 -- .../Brutal.Strings.Analyzers/Utility.cs | 17 - .../PreferString8OverloadFixProvider.cs | 74 -- .../SpanToStringFixProvider.cs | 67 -- .../SyntaxFactoryExtensions.cs | 26 - brutal.zlib/Brutal.ZLib/cmake/FindZLIB.cmake | 41 - .../msbuild/RocketWerkz.Brutal.ZLib.targets | 10 - 25 files changed, 175 insertions(+), 2806 deletions(-) delete mode 100644 brutal.core/Brutal.Core.Analyzers/FixedAnalyzer.cs delete mode 100644 brutal.core/Brutal.Core.Analyzers/OperatingSystemAnalyzer.cs delete mode 100644 brutal.core/Brutal.Core.Analyzers/Resources.cs delete mode 100644 brutal.core/Brutal.Core.Analyzers/VarAnalyzer.cs delete mode 100644 brutal.core/Brutal.Core.CodeFixes/OperatingSystemFixProvider.cs delete mode 100644 brutal.core/Brutal.Core.CodeFixes/VarFixProvider.cs delete mode 100644 brutal.freetype/Brutal.FreeType/cmake/FindFreetype.cmake delete mode 100644 brutal.freetype/Brutal.FreeType/msbuild/RocketWerkz.Brutal.FreeType.targets create mode 100644 brutal.imgui/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt delete mode 100644 brutal.interop/Brutal.Interop.SourceGenerators/Brutal.Interop.SourceGenerators/InteropHandleGenerator.cs delete mode 100644 brutal.monitor/Brutal.Monitor.Host/buildTransitive/RocketWerkz.Brutal.Monitor.Host.targets delete mode 100644 brutal.numerics/Brutal.Numerics.Analyzers/Resources.cs delete mode 100644 brutal.numerics/Brutal.Numerics.Analyzers/RgbToGrayAnalyzer.cs delete mode 100644 brutal.numerics/Brutal.Numerics.Analyzers/SystemDrawingAnalyzer.cs delete mode 100644 brutal.numerics/Brutal.Numerics.Analyzers/SystemNumericsAnalyzer.cs delete mode 100644 brutal.numerics/Brutal.Numerics.CodeFixes/RgbToGrayFixProvider.cs delete mode 100644 brutal.strings/Brutal.Strings.Analyzers/PreferString8OverloadAnalyzer.cs delete mode 100644 brutal.strings/Brutal.Strings.Analyzers/Resources.cs delete mode 100644 brutal.strings/Brutal.Strings.Analyzers/SpanToStringAnalyzer.cs delete mode 100644 brutal.strings/Brutal.Strings.Analyzers/Utility.cs delete mode 100644 brutal.strings/Brutal.Strings.CodeFixes/PreferString8OverloadFixProvider.cs delete mode 100644 brutal.strings/Brutal.Strings.CodeFixes/SpanToStringFixProvider.cs delete mode 100644 brutal.strings/Brutal.Strings.CodeFixes/SyntaxFactoryExtensions.cs delete mode 100644 brutal.zlib/Brutal.ZLib/cmake/FindZLIB.cmake delete mode 100644 brutal.zlib/Brutal.ZLib/msbuild/RocketWerkz.Brutal.ZLib.targets diff --git a/brutal.core/Brutal.Core.Analyzers/FixedAnalyzer.cs b/brutal.core/Brutal.Core.Analyzers/FixedAnalyzer.cs deleted file mode 100644 index ae3380d..0000000 --- a/brutal.core/Brutal.Core.Analyzers/FixedAnalyzer.cs +++ /dev/null @@ -1,1032 +0,0 @@ -using System.Collections.Concurrent; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.FlowAnalysis; -using Microsoft.CodeAnalysis.Operations; - -namespace Brutal.Core.Analyzers; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public class FixedAnalyzer : DiagnosticAnalyzer -{ - // Keep in mind: you have to list your rules here. - public override ImmutableArray SupportedDiagnostics { get; } = - [Resources.ExpectsFixedBrutalCore0009, Resources.ExpectsFixedBrutalCore0010, Resources.LosesFixedBrutalCore0012]; - - public override void Initialize(AnalysisContext context) - { - context.EnableConcurrentExecution(); - context.ConfigureGeneratedCodeAnalysis( - GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics - ); - - context.RegisterCompilationStartAction(static compilationContext => - { - var analysis = new CompilationAnalysis(); - compilationContext.RegisterOperationBlockAction(analysis.AnalyzeOperationBlock); - compilationContext.RegisterOperationAction( - analysis.AnalyzeDelegateCreation, - OperationKind.DelegateCreation - ); - }); - } - - /// One instance per compilation, so the attribute lookups (which walk override chains and - /// interface implementations) are computed once per symbol instead of once per use site. - private sealed class CompilationAnalysis - { - private readonly ConcurrentDictionary _fixedParameters = new(SymbolEqualityComparer.Default); - private readonly ConcurrentDictionary _fixedReturns = new(SymbolEqualityComparer.Default); - private readonly ConcurrentDictionary _fixedProperties = new(SymbolEqualityComparer.Default); - - public void AnalyzeOperationBlock(OperationBlockAnalysisContext context) - { - foreach (var operationBlock in context.OperationBlocks) - { - if (!IsControlFlowGraphRoot(operationBlock)) - continue; - if (!ContainsFixedSink(operationBlock)) - continue; - - var graph = context.GetControlFlowGraph(operationBlock); - AnalyzeGraph(context, graph, context.OwningSymbol as IMethodSymbol); - } - } - - /// A delegate whose parameter is unmarked erases an effective [Fixed] on the converted - /// method: every later call is checked against the delegate's signature, so the - /// conversion is the only place the loss is still visible. - public void AnalyzeDelegateCreation(OperationAnalysisContext context) - { - var creation = (IDelegateCreationOperation)context.Operation; - - var source = creation.Target switch - { - IMethodReferenceOperation methodReference => methodReference.Method, - IAnonymousFunctionOperation anonymousFunction => anonymousFunction.Symbol, - _ => null, - }; - if (source == null) - return; - if (creation.Type is not INamedTypeSymbol { DelegateInvokeMethod: { } invoke } delegateType) - return; - - // A closed extension-method group binds the receiver at creation, so the source has - // one parameter the delegate does not; align positionally from the end. The bound - // receiver parameter itself, if [Fixed], is erased outright. - var offset = source.Parameters.Length - invoke.Parameters.Length; - if (offset is not (0 or 1)) - return; - - if (offset == 1 && ParameterIsFixed(source.Parameters[0])) - { - ReportLoss(context, creation, delegateType, source, source.Parameters[0]); - return; - } - - for (var i = 0; i < invoke.Parameters.Length; i++) - { - if (!ParameterIsFixed(source.Parameters[i + offset]) || ParameterIsFixed(invoke.Parameters[i])) - continue; - - ReportLoss(context, creation, delegateType, source, source.Parameters[i + offset]); - return; - } - } - - private static void ReportLoss( - OperationAnalysisContext context, - IDelegateCreationOperation creation, - INamedTypeSymbol delegateType, - IMethodSymbol source, - IParameterSymbol lostParameter - ) - { - var sourceName = source.MethodKind is MethodKind.AnonymousFunction or MethodKind.LambdaMethod - ? "the lambda expression" - : $"'{source.Name}'"; - - context.ReportDiagnostic( - Diagnostic.Create( - Resources.LosesFixedBrutalCore0012, - creation.Target.Syntax.GetLocation(), - sourceName, - delegateType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), - lostParameter.Name - ) - ); - } - - private static bool IsControlFlowGraphRoot(IOperation operation) => - operation.Kind - is OperationKind.Block - or OperationKind.MethodBody - or OperationKind.ConstructorBody - or OperationKind.FieldInitializer - or OperationKind.PropertyInitializer - or OperationKind.ParameterInitializer; - - /// The flow pass is priced into every consumer build, so bodies without a [Fixed] sink skip it. - private bool ContainsFixedSink(IOperation root) - { - foreach (var operation in EnumerateOperations(root)) - { - if (operation is IArgumentOperation argument && ParameterIsFixed(argument.Parameter)) - return true; - if ( - operation is IConversionOperation { OperatorMethod: { } operatorMethod } - && operatorMethod.Parameters.Length > 0 - && ParameterIsFixed(operatorMethod.Parameters[0]) - ) - return true; - } - - return false; - } - - private static IEnumerable EnumerateOperations(IOperation root) - { - var pending = new Stack(); - pending.Push(root); - while (pending.Count > 0) - { - var operation = pending.Pop(); - yield return operation; - foreach (var child in operation.ChildOperations) - pending.Push(child); - } - } - - private void AnalyzeGraph(OperationBlockAnalysisContext context, ControlFlowGraph graph, IMethodSymbol? owner) - { - var blocks = graph.Blocks; - var flows = new BlockFlow[blocks.Length]; - for (var i = 0; i < flows.Length; i++) - flows[i] = new BlockFlow(); - - var initial = new FlowState(); - if (owner != null) - { - foreach (var parameter in owner.Parameters) - initial.Symbols[parameter] = ParameterIsFixed(parameter); - } - - // Forward dataflow to fixpoint. The lattice per variable is { Fixed, NotFixed } with - // meet = AND, so every update is monotonically downward and the loop terminates. - bool changed; - do - { - changed = false; - foreach (var block in blocks) - { - var flow = flows[block.Ordinal]; - var entry = ComputeEntry(block, blocks, flows, initial); - if (entry == null) - continue; - - if (!FlowState.Equal(entry, flow.Entry)) - { - flow.Entry = entry; - changed = true; - } - - var transfer = Transfer(block, flow.Entry!.Clone(), report: null); - - if (!FlowState.Equal(transfer.State, flow.Exit)) - { - flow.Exit = transfer.State; - changed = true; - } - - flow.ExceptionMeet = transfer.ExceptionMeet; - } - } while (changed); - - foreach (var block in blocks) - { - var flow = flows[block.Ordinal]; - if (flow.Entry == null) - continue; - - Transfer(block, flow.Entry.Clone(), context.ReportDiagnostic); - } - - foreach (var localFunction in graph.LocalFunctions) - AnalyzeGraph(context, graph.GetLocalFunctionControlFlowGraph(localFunction), localFunction); - - foreach (var block in blocks) - { - foreach (var rootOperation in BlockRoots(block)) - { - foreach (var operation in EnumerateOperations(rootOperation)) - { - if (operation is IFlowAnonymousFunctionOperation anonymousFunction) - AnalyzeGraph( - context, - graph.GetAnonymousFunctionControlFlowGraph(anonymousFunction), - anonymousFunction.Symbol - ); - } - } - } - } - - private static IEnumerable BlockRoots(BasicBlock block) - { - foreach (var operation in block.Operations) - yield return operation; - if (block.BranchValue != null) - yield return block.BranchValue; - } - - private FlowState? ComputeEntry( - BasicBlock block, - ImmutableArray blocks, - BlockFlow[] flows, - FlowState initial - ) - { - if (block.Kind == BasicBlockKind.Entry) - return initial.Clone(); - - FlowState? entry = null; - - foreach (var branch in block.Predecessors) - { - var predecessorExit = flows[branch.Source.Ordinal].Exit; - if (predecessorExit == null) - continue; - - var carried = predecessorExit; - foreach (var finallyRegion in branch.FinallyRegions) - carried = ApplyFinallyRegion(carried, finallyRegion, blocks); - - entry = entry == null ? carried.Clone() : FlowState.Meet(entry, carried); - } - - // A handler has no explicit predecessor edges: an exception can surface it from any point - // inside the paired try region, so its entry is the meet over every state observed there. - for ( - var region = block.EnclosingRegion; - region != null && region.FirstBlockOrdinal == block.Ordinal; - region = region.EnclosingRegion - ) - { - if ( - region.Kind - is not ( - ControlFlowRegionKind.Catch - or ControlFlowRegionKind.Filter - or ControlFlowRegionKind.FilterAndHandler - or ControlFlowRegionKind.Finally - ) - ) - continue; - - var tryRegion = FindPairedTryRegion(region); - if (tryRegion == null) - continue; - - for (var ordinal = tryRegion.FirstBlockOrdinal; ordinal <= tryRegion.LastBlockOrdinal; ordinal++) - { - var observed = flows[ordinal].ExceptionMeet; - if (observed == null) - continue; - entry = entry == null ? observed.Clone() : FlowState.Meet(entry, observed); - } - } - - return entry; - } - - private static ControlFlowRegion? FindPairedTryRegion(ControlFlowRegion handlerRegion) - { - for (var region = handlerRegion.EnclosingRegion; region != null; region = region.EnclosingRegion) - { - if (region.Kind is ControlFlowRegionKind.TryAndCatch or ControlFlowRegionKind.TryAndFinally) - return region.NestedRegions[0]; - } - - return null; - } - - /// A branch that leaves through a finally region carries the finally's effects with it. - /// The region is re-run on the carried state (a local fixpoint over its blocks), so the - /// normal path keeps its own verdicts instead of inheriting the exception-context meet. - private FlowState ApplyFinallyRegion( - FlowState carried, - ControlFlowRegion finallyRegion, - ImmutableArray blocks - ) - { - var first = finallyRegion.FirstBlockOrdinal; - var last = finallyRegion.LastBlockOrdinal; - var entries = new FlowState?[last - first + 1]; - var exits = new FlowState?[last - first + 1]; - - bool changed; - do - { - changed = false; - for (var ordinal = first; ordinal <= last; ordinal++) - { - FlowState? entry; - if (ordinal == first) - { - entry = carried.Clone(); - } - else - { - entry = null; - foreach (var branch in blocks[ordinal].Predecessors) - { - var sourceOrdinal = branch.Source.Ordinal; - if (sourceOrdinal < first || sourceOrdinal > last) - continue; - var predecessorExit = exits[sourceOrdinal - first]; - if (predecessorExit == null) - continue; - - var inner = predecessorExit; - foreach (var nested in branch.FinallyRegions) - inner = ApplyFinallyRegion(inner, nested, blocks); - - entry = entry == null ? inner.Clone() : FlowState.Meet(entry, inner); - } - } - - if (entry == null) - continue; - - if (!FlowState.Equal(entry, entries[ordinal - first])) - { - entries[ordinal - first] = entry; - changed = true; - } - - var transfer = Transfer(blocks[ordinal], entries[ordinal - first]!.Clone(), report: null); - if (!FlowState.Equal(transfer.State, exits[ordinal - first])) - { - exits[ordinal - first] = transfer.State; - changed = true; - } - } - } while (changed); - - return exits[last - first] ?? carried; - } - - private TransferContext Transfer(BasicBlock block, FlowState state, Action? report) - { - var context = new TransferContext(state, report); - - foreach (var rootOperation in BlockRoots(block)) - Visit(rootOperation, context); - - return context; - } - - private void Visit(IOperation operation, TransferContext context) - { - foreach (var child in operation.ChildOperations) - Visit(child, context); - - var state = context.State; - - switch (operation) - { - case IFlowCaptureOperation capture: - { - state.Captures[capture.Id] = Evaluate(capture.Value, state); - switch (capture.Value) - { - case ILocalReferenceOperation local: - state.CaptureTargets[capture.Id] = local.Local; - break; - case IParameterReferenceOperation parameter: - state.CaptureTargets[capture.Id] = parameter.Parameter; - break; - } - context.NoteMutation(); - break; - } - - case ISimpleAssignmentOperation assignment: - if (assignment.IsRef) - BindRefLocal(assignment.Target, assignment.Value, state); - else - TrackAssignment(assignment.Target, Evaluate(assignment.Value, state), state); - context.NoteMutation(); - break; - - case IVariableDeclaratorOperation declarator: - { - var initializer = declarator.GetVariableInitializer(); - if (initializer == null) - break; - if (declarator.Symbol.IsRef) - state.RefTargets[declarator.Symbol] = ExtractRefTargets(initializer.Value, state); - else - state.Symbols[declarator.Symbol] = Evaluate(initializer.Value, state); - context.NoteMutation(); - break; - } - - case IArgumentOperation argument: - { - if ( - context.Report != null - && ParameterIsFixed(argument.Parameter) - && !Evaluate(argument.Value, state) - ) - { - var invocation = argument.Parent as IInvocationOperation; - var functionName = invocation is not null ? $"'{invocation.TargetMethod.Name}'" : "function"; - var parameterName = argument.Parameter?.Name ?? ""; - - context.Report( - Diagnostic.Create( - Resources.ExpectsFixedBrutalCore0009, - argument.Syntax.GetLocation(), - functionName, - parameterName - ) - ); - } - - // The callee can reassign anything it receives by ref/out, [Fixed] or not: - // the attribute promises what goes in, not what the callee leaves behind. - if (argument.Parameter?.RefKind is RefKind.Ref or RefKind.Out) - { - KillThroughReference(argument.Value, state); - context.NoteMutation(); - } - break; - } - - case IConversionOperation { OperatorMethod: { } operatorMethod } conversion - when context.Report != null - && operatorMethod.Parameters.Length > 0 - && ParameterIsFixed(operatorMethod.Parameters[0]): - { - if (!Evaluate(conversion.Operand, state)) - { - context.Report( - Diagnostic.Create( - Resources.ExpectsFixedBrutalCore0010, - conversion.Syntax.GetLocation(), - conversion.Operand.Type, - conversion.Type - ) - ); - } - break; - } - } - } - - private static void TrackAssignment(IOperation target, bool verdict, FlowState state) - { - switch (target) - { - case ILocalReferenceOperation { Local.IsRef: true } refLocal: - WriteThroughRefLocal(refLocal.Local, verdict, state); - break; - case ILocalReferenceOperation local: - state.Symbols[local.Local] = verdict; - break; - case IParameterReferenceOperation parameter: - state.Symbols[parameter.Parameter] = verdict; - break; - case IFlowCaptureReferenceOperation captureReference: - state.Captures[captureReference.Id] = verdict; - // Lowering assigns through a capture of the lvalue (`x ??= e`, conditional - // access): the write must reach the captured symbol, not just the capture. - if (state.CaptureTargets.TryGetValue(captureReference.Id, out var captured)) - { - if (captured is ILocalSymbol { IsRef: true } capturedRefLocal) - WriteThroughRefLocal(capturedRefLocal, verdict, state); - else - state.Symbols[captured] = verdict; - } - break; - } - } - - private static void BindRefLocal(IOperation target, IOperation value, FlowState state) - { - if (target is ILocalReferenceOperation { Local.IsRef: true } refLocal) - state.RefTargets[refLocal.Local] = ExtractRefTargets(value, state); - } - - /// null means the referent is unknown (a ref return, a ref field): reads through it are - /// movable, and writes through it cannot be attributed to any tracked symbol. - private static HashSet? ExtractRefTargets(IOperation value, FlowState state) => - value switch - { - ILocalReferenceOperation { Local.IsRef: true } refLocal => state.RefTargets.TryGetValue( - refLocal.Local, - out var existing - ) - && existing != null - ? new HashSet(existing, SymbolEqualityComparer.Default) - : null, - ILocalReferenceOperation local => new HashSet(SymbolEqualityComparer.Default) { local.Local }, - IParameterReferenceOperation parameter => new HashSet(SymbolEqualityComparer.Default) - { - parameter.Parameter, - }, - _ => null, - }; - - /// A write through a ref local with one candidate referent is a strong update; with several, - /// only a movable verdict is applied (to every candidate), because a fixed verdict landed in - /// exactly one of them and we cannot tell which. - private static void WriteThroughRefLocal(ILocalSymbol refLocal, bool verdict, FlowState state) - { - if (!state.RefTargets.TryGetValue(refLocal, out var targets) || targets == null) - return; - if (targets.Count != 1 && verdict) - return; - - foreach (var target in targets) - state.Symbols[target] = verdict; - } - - private bool ReadThroughRefLocal(ILocalSymbol refLocal, FlowState state) - { - if (!state.RefTargets.TryGetValue(refLocal, out var targets) || targets == null) - return false; - - foreach (var target in targets) - { - var verdict = target switch - { - ILocalSymbol local => local.IsFixed - || (state.Symbols.TryGetValue(local, out var tracked) && tracked), - IParameterSymbol parameter => state.Symbols.TryGetValue(parameter, out var tracked) - ? tracked - : ParameterIsFixed(parameter), - _ => false, - }; - if (!verdict) - return false; - } - - return targets.Count > 0; - } - - private static void KillThroughReference(IOperation value, FlowState state) - { - switch (value) - { - case ILocalReferenceOperation { Local.IsRef: true } refLocal: - WriteThroughRefLocal(refLocal.Local, false, state); - break; - case ILocalReferenceOperation local: - state.Symbols[local.Local] = false; - break; - case IParameterReferenceOperation parameter: - state.Symbols[parameter.Parameter] = false; - break; - } - } - - private bool Evaluate(IOperation? operation, FlowState state) - { - if (operation == null) - return false; - - // These cases are presumed to be fixed. - if (operation.ConstantValue.HasValue) - return true; - if (operation.Syntax is LiteralExpressionSyntax) - return true; - if (operation.Syntax is StackAllocArrayCreationExpressionSyntax) - return true; - if (operation.Syntax is ImplicitStackAllocArrayCreationExpressionSyntax) - return true; - - // An empty span has no memory to move, and `[]` is how a caller says "no buffer". - if (operation.Syntax is CollectionExpressionSyntax { Elements.Count: 0 }) - return true; - - switch (operation) - { - case IAddressOfOperation: - return true; - case IDefaultValueOperation: - return true; - case IFlowCaptureReferenceOperation captureReference: - return state.Captures.TryGetValue(captureReference.Id, out var captured) && captured; - case ILocalReferenceOperation { Local.IsRef: true } refLocal: - return ReadThroughRefLocal(refLocal.Local, state); - case ILocalReferenceOperation local: - // A pointer bound by a `fixed (T* p = ...)` statement is pinned for the entire - // body of the statement, regardless of what the initializer was. - return local.Local.IsFixed || (state.Symbols.TryGetValue(local.Local, out var tracked) && tracked); - case IParameterReferenceOperation parameter: - return state.Symbols.TryGetValue(parameter.Parameter, out var parameterState) - ? parameterState - : ParameterIsFixed(parameter.Parameter); - case IFieldReferenceOperation fieldReference: - return ContainsFixed(fieldReference.Field.GetAttributes()); - case IPropertyReferenceOperation propertyReference: - // Span.Empty has no memory to move, like the empty collection expression. - return PropertyIsFixed(propertyReference.Property) - || ( - propertyReference.Property.Name == "Empty" - && IsBclSpan(propertyReference.Property.ContainingType) - ); - case IInvocationOperation invocation: - return MethodReturnsFixed(invocation.TargetMethod) || InvocationIsViewOfFixed(invocation, state); - case IImplicitIndexerReferenceOperation implicitIndexer: - // The span range indexer (`buffer[..n]`) is a view: the same memory, so the - // receiver's verdict carries over. - return IsBclSpan(implicitIndexer.Type) - && IsBclSpan(implicitIndexer.Instance.Type) - && Evaluate(implicitIndexer.Instance, state); - case IObjectCreationOperation creation: - return SpanCreationOverPointerIsFixed(creation, state); - case IConversionOperation conversion: - if (conversion.OperatorMethod is { } operatorMethod && MethodReturnsFixed(operatorMethod)) - return true; - return Evaluate(conversion.Operand, state); - case IArrayElementReferenceOperation arrayElement: - return Evaluate(arrayElement.ArrayReference, state); - // Pointer arithmetic stays inside the allocation the pointer came from. - case IBinaryOperation binary when binary.Type is IPointerTypeSymbol: - return binary.LeftOperand.Type is IPointerTypeSymbol - ? Evaluate(binary.LeftOperand, state) - : Evaluate(binary.RightOperand, state); - case IIncrementOrDecrementOperation increment when increment.Type is IPointerTypeSymbol: - return Evaluate(increment.Target, state); - case IConditionalOperation conditional: - return Evaluate(conditional.WhenTrue, state) && Evaluate(conditional.WhenFalse, state); - default: - return false; - } - } - - /// A view over fixed memory is the same memory: Slice and any other span instance member - /// returning a span take the receiver's verdict, as does string.AsSpan. Array AsSpan and - /// MemoryMarshal-style factories stay movable because the analyzer cannot see what they wrap. - private bool InvocationIsViewOfFixed(IInvocationOperation invocation, FlowState state) - { - var method = invocation.TargetMethod; - - if (invocation.Instance != null && IsBclSpan(method.ContainingType) && IsBclSpan(method.ReturnType)) - return Evaluate(invocation.Instance, state); - - if (method.Name != "AsSpan" || method.ContainingType is not { Name: "MemoryExtensions" } containingType) - return false; - if (!IsSystemNamespace(containingType.ContainingNamespace)) - return false; - - if (method.ReducedFrom is { } reducedFrom) - { - return reducedFrom.Parameters.Length > 0 - && reducedFrom.Parameters[0].Type.SpecialType == SpecialType.System_String - && Evaluate(invocation.Instance, state); - } - - return method.Parameters.Length > 0 - && method.Parameters[0].Type.SpecialType == SpecialType.System_String - && invocation.Arguments.Length > 0 - && Evaluate(invocation.Arguments[0].Value, state); - } - - private bool SpanCreationOverPointerIsFixed(IObjectCreationOperation creation, FlowState state) - { - if (!IsBclSpan(creation.Type)) - return false; - if (creation.Constructor is not { Parameters.Length: > 0 } constructor) - return false; - if (constructor.Parameters[0].Type is not IPointerTypeSymbol) - return false; - - foreach (var argument in creation.Arguments) - { - if (argument.Parameter?.Ordinal == 0) - return Evaluate(argument.Value, state); - } - - return false; - } - - private static bool IsBclSpan(ITypeSymbol? type) => - type is INamedTypeSymbol { Name: "Span" or "ReadOnlySpan", Arity: 1 } named - && IsSystemNamespace(named.ContainingNamespace); - - private static bool IsSystemNamespace(INamespaceSymbol? containingNamespace) => - containingNamespace is { Name: "System", ContainingNamespace.IsGlobalNamespace: true }; - - private bool ParameterIsFixed(IParameterSymbol? parameter) - { - if (parameter == null) - return false; - return _fixedParameters.GetOrAdd( - parameter, - static symbol => ComputeParameterIsFixed((IParameterSymbol)symbol) - ); - } - - /// The attribute is effective when declared on the parameter itself, on the same parameter of - /// any overridden method, on any interface method the containing method implements, or on the - /// original definition of a reduced extension method. - private static bool ComputeParameterIsFixed(IParameterSymbol parameter) - { - if (ContainsFixed(parameter.GetAttributes())) - return true; - if (parameter.ContainingSymbol is not IMethodSymbol method) - return false; - - foreach (var related in RelatedMethods(method)) - { - if ( - related.Parameters.Length > parameter.Ordinal - && ContainsFixed(related.Parameters[parameter.Ordinal].GetAttributes()) - ) - return true; - } - - // A reduced extension method's parameter list drops the receiver, shifting ordinals by one. - return method.ReducedFrom is { } reducedFrom - && reducedFrom.Parameters.Length > parameter.Ordinal + 1 - && ContainsFixed(reducedFrom.Parameters[parameter.Ordinal + 1].GetAttributes()); - } - - private bool MethodReturnsFixed(IMethodSymbol? method) - { - if (method == null) - return false; - return _fixedReturns.GetOrAdd(method, static symbol => ComputeMethodReturnsFixed((IMethodSymbol)symbol)); - } - - private static bool ComputeMethodReturnsFixed(IMethodSymbol method) - { - if (ContainsFixed(method.GetReturnTypeAttributes())) - return true; - - foreach (var related in RelatedMethods(method)) - { - if (ContainsFixed(related.GetReturnTypeAttributes())) - return true; - } - - return method.ReducedFrom is { } reducedFrom && ContainsFixed(reducedFrom.GetReturnTypeAttributes()); - } - - private bool PropertyIsFixed(IPropertySymbol? property) - { - if (property == null) - return false; - return _fixedProperties.GetOrAdd( - property, - static symbol => ComputePropertyIsFixed((IPropertySymbol)symbol) - ); - } - - private static bool ComputePropertyIsFixed(IPropertySymbol property) - { - if (PropertyCarriesFixed(property)) - return true; - - for ( - var overridden = property.OverriddenProperty; - overridden != null; - overridden = overridden.OverriddenProperty - ) - { - if (PropertyCarriesFixed(overridden)) - return true; - } - - foreach (var interfaceProperty in ImplementedInterfaceMembers(property)) - { - if (PropertyCarriesFixed(interfaceProperty)) - return true; - } - - return false; - } - - private static bool PropertyCarriesFixed(IPropertySymbol property) => - ContainsFixed(property.GetAttributes()) - || (property.GetMethod is { } getter && ContainsFixed(getter.GetReturnTypeAttributes())); - - private static IEnumerable RelatedMethods(IMethodSymbol method) - { - for (var overridden = method.OverriddenMethod; overridden != null; overridden = overridden.OverriddenMethod) - yield return overridden; - - foreach (var interfaceMethod in ImplementedInterfaceMembers(method)) - yield return interfaceMethod; - } - - private static IEnumerable ImplementedInterfaceMembers(TMember member) - where TMember : class, ISymbol - { - switch (member) - { - case IMethodSymbol method: - foreach (var explicitImplementation in method.ExplicitInterfaceImplementations) - yield return (TMember)(ISymbol)explicitImplementation; - break; - case IPropertySymbol property: - foreach (var explicitImplementation in property.ExplicitInterfaceImplementations) - yield return (TMember)(ISymbol)explicitImplementation; - break; - } - - var containingType = member.ContainingType; - if (containingType == null) - yield break; - - foreach (var interfaceType in containingType.AllInterfaces) - { - // Implicit implementations share the member's name, so only candidates under that - // name need the (expensive) implementation lookup. - foreach (var interfaceMember in interfaceType.GetMembers(member.Name)) - { - if (interfaceMember is not TMember candidate) - continue; - - var implementation = containingType.FindImplementationForInterfaceMember(candidate); - if ( - SymbolEqualityComparer.Default.Equals(implementation, member) - || SymbolEqualityComparer.Default.Equals( - implementation?.OriginalDefinition, - member.OriginalDefinition - ) - ) - yield return candidate; - } - } - } - - private static bool ContainsFixed(ImmutableArray attributes) - { - foreach (var a in attributes) - { - if ( - a.AttributeClass?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) - == "global::Brutal.Attributes.FixedAttribute" - ) - return true; - } - - return false; - } - } - - private sealed class TransferContext - { - public readonly FlowState State; - public FlowState ExceptionMeet; - public readonly Action? Report; - - public TransferContext(FlowState state, Action? report) - { - State = state; - ExceptionMeet = state.Clone(); - Report = report; - } - - /// Called after every state change, so a handler entry sees every intermediate state a - /// mid-operation exception could expose, not just the block and root-operation boundaries. - public void NoteMutation() => ExceptionMeet = FlowState.Meet(ExceptionMeet, State); - } - - private sealed class BlockFlow - { - public FlowState? Entry; - public FlowState? Exit; - public FlowState? ExceptionMeet; - } - - private sealed class FlowState - { - public readonly Dictionary Symbols; - public readonly Dictionary Captures; - - /// The lvalue a flow capture stands for, when it is a tracked local or parameter, so an - /// assignment through the capture reaches the symbol. - public readonly Dictionary CaptureTargets; - - /// Possible referents per ref local; a null set means the referent is unknown. - public readonly Dictionary?> RefTargets; - - public FlowState() - { - Symbols = new Dictionary(SymbolEqualityComparer.Default); - Captures = new Dictionary(); - CaptureTargets = new Dictionary(); - RefTargets = new Dictionary?>(SymbolEqualityComparer.Default); - } - - private FlowState(FlowState source) - { - Symbols = new Dictionary(source.Symbols, SymbolEqualityComparer.Default); - Captures = new Dictionary(source.Captures); - CaptureTargets = new Dictionary(source.CaptureTargets); - RefTargets = new Dictionary?>(SymbolEqualityComparer.Default); - foreach (var pair in source.RefTargets) - RefTargets[pair.Key] = - pair.Value == null ? null : new HashSet(pair.Value, SymbolEqualityComparer.Default); - } - - public FlowState Clone() => new(this); - - // A symbol missing from one side is unconstrained there, so the other side's verdict wins. - public static FlowState Meet(FlowState left, FlowState right) - { - var result = left.Clone(); - foreach (var pair in right.Symbols) - result.Symbols[pair.Key] = - !result.Symbols.TryGetValue(pair.Key, out var existing) || existing ? pair.Value : false; - foreach (var pair in right.Captures) - result.Captures[pair.Key] = - !result.Captures.TryGetValue(pair.Key, out var existing) || existing ? pair.Value : false; - foreach (var pair in right.CaptureTargets) - { - if (!result.CaptureTargets.TryGetValue(pair.Key, out var existing)) - result.CaptureTargets[pair.Key] = pair.Value; - else if (!SymbolEqualityComparer.Default.Equals(existing, pair.Value)) - result.CaptureTargets.Remove(pair.Key); - } - foreach (var pair in right.RefTargets) - { - if (!result.RefTargets.TryGetValue(pair.Key, out var existing)) - { - result.RefTargets[pair.Key] = - pair.Value == null ? null : new HashSet(pair.Value, SymbolEqualityComparer.Default); - } - else if (existing == null || pair.Value == null) - { - result.RefTargets[pair.Key] = null; - } - else - { - existing.UnionWith(pair.Value); - } - } - return result; - } - - public static bool Equal(FlowState? left, FlowState? right) - { - if (ReferenceEquals(left, right)) - return true; - if (left == null || right == null) - return false; - if ( - left.Symbols.Count != right.Symbols.Count - || left.Captures.Count != right.Captures.Count - || left.CaptureTargets.Count != right.CaptureTargets.Count - || left.RefTargets.Count != right.RefTargets.Count - ) - return false; - - foreach (var pair in left.Symbols) - { - if (!right.Symbols.TryGetValue(pair.Key, out var other) || other != pair.Value) - return false; - } - - foreach (var pair in left.Captures) - { - if (!right.Captures.TryGetValue(pair.Key, out var other) || other != pair.Value) - return false; - } - - foreach (var pair in left.CaptureTargets) - { - if ( - !right.CaptureTargets.TryGetValue(pair.Key, out var other) - || !SymbolEqualityComparer.Default.Equals(other, pair.Value) - ) - return false; - } - - foreach (var pair in left.RefTargets) - { - if (!right.RefTargets.TryGetValue(pair.Key, out var other)) - return false; - if (pair.Value == null || other == null) - { - if (pair.Value != other) - return false; - } - else if (!pair.Value.SetEquals(other)) - { - return false; - } - } - - return true; - } - } -} diff --git a/brutal.core/Brutal.Core.Analyzers/OperatingSystemAnalyzer.cs b/brutal.core/Brutal.Core.Analyzers/OperatingSystemAnalyzer.cs deleted file mode 100644 index eec8df4..0000000 --- a/brutal.core/Brutal.Core.Analyzers/OperatingSystemAnalyzer.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Diagnostics; - -namespace Brutal.Core.Analyzers; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public class OperatingSystemAnalyzer : DiagnosticAnalyzer -{ - // Keep in mind: you have to list your rules here. - public override ImmutableArray SupportedDiagnostics { get; } = - ImmutableArray.Create(Resources.BrutalCore0003); - - public override void Initialize(AnalysisContext context) - { - // You must call this method to avoid analyzing generated code. - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); - - // You must call this method to enable the Concurrent Execution. - context.EnableConcurrentExecution(); - - // Subscribe to the Syntax Node with the appropriate 'SyntaxKind' (ClassDeclaration) action. - // To figure out which Syntax Nodes you should choose, consider installing the Roslyn syntax tree viewer plugin Rossynt: https://plugins.jetbrains.com/plugin/16902-rossynt/ - context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression); - } - - private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) - { - if (context.Node is not InvocationExpressionSyntax invocation) - return; - - var memberAccess = invocation.Expression as MemberAccessExpressionSyntax; - if (memberAccess == null) - return; - - var symbolInfo = context.SemanticModel.GetSymbolInfo(memberAccess.Expression); - if (symbolInfo.Symbol == null) - return; - - var systemOperatingSystem = context.SemanticModel.Compilation.GetTypeByMetadataName("System.OperatingSystem"); - - if (!SymbolEqualityComparer.Default.Equals(symbolInfo.Symbol, systemOperatingSystem)) - return; - - // check if member name is "IsWindows", "IsLinux", "IsMacOS" - if (memberAccess.Name.Identifier.Text is not ("IsWindows" or "IsLinux" or "IsMacOS")) - return; - - var diagnostic = Diagnostic.Create(Resources.BrutalCore0003, invocation.GetLocation()); - context.ReportDiagnostic(diagnostic); - } -} diff --git a/brutal.core/Brutal.Core.Analyzers/Resources.cs b/brutal.core/Brutal.Core.Analyzers/Resources.cs deleted file mode 100644 index 3809fa2..0000000 --- a/brutal.core/Brutal.Core.Analyzers/Resources.cs +++ /dev/null @@ -1,66 +0,0 @@ -using Microsoft.CodeAnalysis; - -namespace Brutal.Core.Analyzers; - -public static class Resources -{ - public static readonly DiagnosticDescriptor BrutalCore0003 = new( - "BRUTALCORE0003", - "Prefer Brutal.Platform instead of System.OperatingSystem", - "Brutal.Platform provides a simpler API to check the current platform", - "Obsolete", - DiagnosticSeverity.Info, - isEnabledByDefault: true, - description: "Use Brutal.Platform instead of System.OperatingSystem." - ); - public const string BrutalCore0003Suggestion = "Use Brutal.Platform"; - - // From framework analyser BRUTAL4003 var fixes - public static readonly DiagnosticDescriptor VarBrutalCore0007 = new( - "BRUTALCORE0007", - "Prefer var over explicit type", - "Use var for terseness and ease of refactoring", - "Usage", - DiagnosticSeverity.Info, - isEnabledByDefault: true, - description: "Use var instead of explicit types." - ); - - // From framework analyser BRUTAL4003 var fixes for default initialisation - public static readonly DiagnosticDescriptor VarDefaultBrutalCore0008 = new( - "BRUTALCORE0008", - "Prefer var default literal over explicit with default", - "Use var with default(type) for terseness and consistency", - "Usage", - DiagnosticSeverity.Info, - isEnabledByDefault: true, - description: "Use var instead of explicit types." - ); - - public static readonly DiagnosticDescriptor ExpectsFixedBrutalCore0009 = new( - "BRUTALCORE0009", - "This should be a fixed value", - "Potential unsafe call to {0}. Ensure the argument for '{1}' comes from a fixed source.", - "Usage", - DiagnosticSeverity.Error, - isEnabledByDefault: true - ); - - public static readonly DiagnosticDescriptor ExpectsFixedBrutalCore0010 = new( - "BRUTALCORE0010", - "This should be a fixed value", - "Potential unsafe implicit conversion from {0} to {1}. Ensure cast comes from a fixed source.", - "Usage", - DiagnosticSeverity.Error, - isEnabledByDefault: true - ); - - public static readonly DiagnosticDescriptor LosesFixedBrutalCore0012 = new( - "BRUTALCORE0012", - "Delegate conversion loses [Fixed]", - "Converting {0} to '{1}' erases the [Fixed] requirement on parameter '{2}'. Calls through the delegate are not checked; use a delegate type that marks the parameter [Fixed].", - "Usage", - DiagnosticSeverity.Warning, - isEnabledByDefault: true - ); -} diff --git a/brutal.core/Brutal.Core.Analyzers/VarAnalyzer.cs b/brutal.core/Brutal.Core.Analyzers/VarAnalyzer.cs deleted file mode 100644 index 69d6ab0..0000000 --- a/brutal.core/Brutal.Core.Analyzers/VarAnalyzer.cs +++ /dev/null @@ -1,180 +0,0 @@ -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Diagnostics; - -namespace Brutal.Core.Analyzers; - -/// -/// Analyzer that flags explicit type declarations that can be replaced with 'var'. -/// -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public class VarAnalyzer : DiagnosticAnalyzer -{ - // Keep in mind: you have to list your rules here. - public override ImmutableArray SupportedDiagnostics { get; } = - ImmutableArray.Create(Resources.VarBrutalCore0007, Resources.VarDefaultBrutalCore0008); - - public override void Initialize(AnalysisContext context) - { - // You must call this method to avoid analyzing generated code. - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); - - // You must call this method to enable the Concurrent Execution. - context.EnableConcurrentExecution(); - - // Analyze variable declarations like `float x = 1f` or `MyType obj = new()` - context.RegisterSyntaxNodeAction(AnalyzeVariableDeclaration, SyntaxKind.VariableDeclaration); - - // Check other 'context.Register...' methods that might be helpful for your purposes. - } - - /// - /// Analyzes explicit variable declarations to suggest 'var' where applicable. - /// - /// Operation context. - private void AnalyzeVariableDeclaration(SyntaxNodeAnalysisContext context) - { - var variableDeclaration = (VariableDeclarationSyntax)context.Node; - - if ( - variableDeclaration.Type.IsVar - || variableDeclaration.Parent is not LocalDeclarationStatementSyntax localDecl - || IsConst(localDecl) - ) - return; - - foreach (var variable in variableDeclaration.Variables) - { - if (variable.Initializer == null) - continue; - - var declaredType = context.SemanticModel.GetTypeInfo(variableDeclaration.Type).Type; - var initializerType = context.SemanticModel.GetTypeInfo(variable.Initializer.Value).Type; - - if (declaredType == null || initializerType == null) - continue; - - // SomeType me = default -> var me default(SomeType); - if (variable.Initializer.Value.IsKind(SyntaxKind.DefaultLiteralExpression)) - { - ReportVarDefaultDiagnostic(context, variableDeclaration); - continue; - } - - if (!WouldVarDeclarationProduceSameType(variable, context.SemanticModel)) - continue; - - // Report diagnostic on the explicit type - context.ReportDiagnostic( - Diagnostic.Create( - Resources.VarBrutalCore0007, - variableDeclaration.Type.GetLocation(), - declaredType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) - ) - ); - } - } - - private static void ReportVarDefaultDiagnostic( - SyntaxNodeAnalysisContext context, - VariableDeclarationSyntax variableDeclaration - ) - { - context.ReportDiagnostic( - Diagnostic.Create( - Resources.VarDefaultBrutalCore0008, - variableDeclaration.Type.GetLocation(), - variableDeclaration.Type.ToString() - ) - ); - } - - /// - /// This function returns whether, if the variable declaration was made into a 'var' declaration, - /// that the same final type would be the same as what it originally was. e.g. - /// - /// Given: - /// Span <byte> data = stackalloc byte[1024]; - /// If we test - /// var data = stackalloc byte[1024]; - /// - /// Is the resulting type of the symbol 'data' the same in both cases. - /// - /// - /// - /// - /// - public static bool WouldVarDeclarationProduceSameType( - VariableDeclaratorSyntax declarator, - SemanticModel semanticModel, - CancellationToken ct = default - ) - { - // Must have an initializer to use 'var' - if (declarator.Initializer is null) - return false; - - var declaration = (VariableDeclarationSyntax)declarator.Parent!; - var originalLocal = (ILocalSymbol?)semanticModel.GetDeclaredSymbol(declarator, ct); - if (originalLocal is null) - return false; - - if (declaration.Parent is not LocalDeclarationStatementSyntax localStmt) - return false; - - var synthesisedVarDeclaration = SynthesisedVarDeclaration(declarator, declaration); - - if (!TryGetSynthesisedSymbol(semanticModel, localStmt, synthesisedVarDeclaration, out var specLocal, ct)) - return false; - - return specLocal?.Type is not null - && specLocal.Type.Kind != SymbolKind.ErrorType - && SymbolEqualityComparer.Default.Equals(originalLocal.Type, specLocal.Type); - } - - private static bool TryGetSynthesisedSymbol( - SemanticModel semanticModel, - LocalDeclarationStatementSyntax localStmt, - VariableDeclarationSyntax synthesisedVarDeclaration, - out ILocalSymbol? specLocal, - CancellationToken ct - ) - { - var newLocalStmt = localStmt.WithDeclaration(synthesisedVarDeclaration); - if (!semanticModel.TryGetSpeculativeSemanticModel(localStmt.SpanStart, newLocalStmt, out var specModel)) - { - specLocal = null; - return false; - } - - var specRoot = specModel.SyntaxTree.GetRoot(ct); - var specDeclarator = specRoot.FindNode(synthesisedVarDeclaration.Variables[0].Span); // (node => node == varDeclaration.Variables[0]); - - specLocal = (ILocalSymbol?)specModel.GetDeclaredSymbol(specDeclarator, ct); - return true; - } - - private static VariableDeclarationSyntax SynthesisedVarDeclaration( - VariableDeclaratorSyntax declarator, - VariableDeclarationSyntax declaration - ) - { - var varType = SyntaxFactory.IdentifierName("var").WithTriviaFrom(declaration.Type); - - var varDecl = declaration.WithType(varType); - return varDecl; - } - - private static bool IsConst(LocalDeclarationStatementSyntax localDecl) - { - for (var i = 0; i < localDecl.Modifiers.Count; i++) - { - if (localDecl.Modifiers[i].IsKind(SyntaxKind.ConstKeyword)) - return true; - } - - return false; - } -} diff --git a/brutal.core/Brutal.Core.CodeFixes/OperatingSystemFixProvider.cs b/brutal.core/Brutal.Core.CodeFixes/OperatingSystemFixProvider.cs deleted file mode 100644 index 1466835..0000000 --- a/brutal.core/Brutal.Core.CodeFixes/OperatingSystemFixProvider.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System.Collections.Immutable; -using System.Composition; -using Brutal.Core.Analyzers; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace Brutal.Core.Analyzers; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(OperatingSystemFixProvider)), Shared] -public class OperatingSystemFixProvider : CodeFixProvider -{ - // Specify the diagnostic IDs of analyzers that are expected to be linked. - public sealed override ImmutableArray FixableDiagnosticIds { get; } = [Resources.BrutalCore0003.Id]; - - // If you don't need the 'fix all' behaviour, return null. - public override FixAllProvider? GetFixAllProvider() => null; - - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) - { - // We link only one diagnostic and assume there is only one diagnostic in the context. - var diagnostic = context.Diagnostics.Single(); - - // 'SourceSpan' of 'Location' is the highlighted area. We're going to use this area to find the 'SyntaxNode' to rename. - var diagnosticSpan = diagnostic.Location.SourceSpan; - - // Get the root of Syntax Tree that contains the highlighted diagnostic. - var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); - - // Find SyntaxNode corresponding to the diagnostic. - var diagnosticNode = root?.FindNode(diagnosticSpan); - - // To get the required metadata, we should match the Node to the specific type: 'ClassDeclarationSyntax'. - if (diagnosticNode is not InvocationExpressionSyntax declaration) - return; - - // Register a code action that will invoke the fix. - context.RegisterCodeFix( - CodeAction.Create( - title: Resources.BrutalCore0003Suggestion, - createChangedSolution: c => FixToBrutalPlatformAsync(context.Document, declaration, c), - equivalenceKey: nameof(Resources.BrutalCore0003.Id) - ), - diagnostic - ); - } - - private static async Task FixToBrutalPlatformAsync( - Document document, - InvocationExpressionSyntax invocationExpression, - CancellationToken cancellationToken - ) - { - // Change from OperatingSystem.XYZ() to Platform.XYZ - // Platform.XYZ is a property, not a method, so we just change the expression part. - var memberAccess = invocationExpression.Expression as MemberAccessExpressionSyntax; - if (memberAccess == null) - return document.Project.Solution; - - var root = await document.GetSyntaxRootAsync(cancellationToken); - if (root == null) - return document.Project.Solution; - - var newMemberAccess = SyntaxFactory.MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - SyntaxFactory.IdentifierName("Platform"), - memberAccess.Name - ); - - var newRoot = root.ReplaceNode(invocationExpression, newMemberAccess); - var newDocument = document.WithSyntaxRoot(newRoot); - return newDocument.Project.Solution; - } -} diff --git a/brutal.core/Brutal.Core.CodeFixes/VarFixProvider.cs b/brutal.core/Brutal.Core.CodeFixes/VarFixProvider.cs deleted file mode 100644 index 94368d9..0000000 --- a/brutal.core/Brutal.Core.CodeFixes/VarFixProvider.cs +++ /dev/null @@ -1,192 +0,0 @@ -using System.Collections.Immutable; -using System.Composition; -using Brutal.Core.Analyzers; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace Brutal.Core.Analyzers; - -/// -/// A code fix provider that replaces explicit types with 'var' and expands 'new()' to 'new TypeName()'. -/// All code fixes must be linked to specific analyzers. -/// -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(VarFixProvider)), Shared] -public class VarFixProvider : CodeFixProvider -{ - // Specify the diagnostic IDs of analyzers that are expected to be linked. - public sealed override ImmutableArray FixableDiagnosticIds { get; } = - [Resources.VarBrutalCore0007.Id, Resources.VarDefaultBrutalCore0008.Id]; - - // If you don't need the 'fix all' behavior, return null. - public override FixAllProvider? GetFixAllProvider() => null; //WellKnownFixAllProviders.BatchFixer; - - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) - { - // We link only one diagnostic and assume there is only one diagnostic in the context. - if (context.Diagnostics.Length != 1) - { - return; - } - - var diagnostic = context.Diagnostics[0]; - - // 'SourceSpan' of 'Location' is the highlighted area. - var diagnosticSpan = diagnostic.Location.SourceSpan; - - // Get the root of Syntax Tree that contains the highlighted diagnostic. - var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); - - // Find the TypeSyntax node to replace (eg., 'float' in 'float x = 1f') - if (root?.FindNode(diagnosticSpan) is not TypeSyntax typeSyntax) - return; - - var declaration = typeSyntax.FirstAncestorOrSelf(); - if (declaration is not null && TryRegisterDefault(declaration, context, diagnostic, root)) - return; - - // Register a code action that will invoke the fix. - context.RegisterCodeFix( - CodeAction.Create( - title: string.Format(Resources.VarBrutalCore0007.Id), - createChangedDocument: c => ReplaceWithVarAsync(context.Document, typeSyntax, c), - equivalenceKey: nameof(Resources.VarBrutalCore0007.Id) - ), - diagnostic - ); - } - - private bool TryRegisterDefault( - VariableDeclarationSyntax declaration, - CodeFixContext context, - Diagnostic diagnostic, - SyntaxNode root - ) - { - var variable = declaration.Variables.FirstOrDefault(); - if (variable?.Initializer is null) - { - return false; - } - - // e.g. int bob = default. Here, default is a DefaultLiteralExpression - // int bob = default(3). Here, default is a DefaultExpression - if (!variable.Initializer.Value.IsKind(SyntaxKind.DefaultLiteralExpression)) - return false; - - context.RegisterCodeFix( - CodeAction.Create( - Resources.VarDefaultBrutalCore0008.Title.ToString(), - c => UseVarAndExplicitDefaultAsync(context.Document, declaration, variable, c, root), - nameof(VarFixProvider) - ), - diagnostic - ); - return true; - } - - private Task UseVarAndExplicitDefaultAsync( - Document document, - VariableDeclarationSyntax declaration, - VariableDeclaratorSyntax variable, - CancellationToken cancellationToken, - SyntaxNode root - ) - { - var varType = SyntaxFactory - .IdentifierName("var") - .WithLeadingTrivia(declaration.Type.GetLeadingTrivia()) - .WithTrailingTrivia(declaration.Type.GetTrailingTrivia()); - - var explicitDefault = SyntaxFactory.DefaultExpression(declaration.Type.WithoutTrivia()); - - var newVariable = variable.WithInitializer( - SyntaxFactory.EqualsValueClause(explicitDefault).WithEqualsToken(variable.Initializer!.EqualsToken) - ); - - var newDeclaration = declaration - .WithType(varType) - .WithVariables(SyntaxFactory.SingletonSeparatedList(newVariable)); - - // var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var newRoot = root.ReplaceNode(declaration, newDeclaration); - - return Task.FromResult(document.WithSyntaxRoot(newRoot)); - } - - /// - /// Executed on the quick fix action raised by the user. - /// - /// Affected source file. - /// The explicit type syntax node to replace. - /// Any fix is cancellable by the user, so we should support the cancellation token. - /// A new document with the explicit type replaced by 'var'. - private async Task ReplaceWithVarAsync( - Document document, - TypeSyntax explicitType, - CancellationToken cancellationToken - ) - { - var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - if (root == null) - return document; - - var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - if (semanticModel == null) - return document; - - // Get the VariableDeclarationSyntax node (e.g., 'myObject obj = new();') - if (explicitType.Parent is not VariableDeclarationSyntax declaration || declaration.Variables.Count == 0) - return document; - - var variable = declaration.Variables[0]; - - // Create 'var' keyword with preserved trivia - var varType = SyntaxFactory - .IdentifierName("var") - .WithLeadingTrivia(explicitType.GetLeadingTrivia()) - .WithTrailingTrivia(explicitType.GetTrailingTrivia()); - - ExpressionSyntax? newInitializerExpr = variable.Initializer?.Value; - - // Replace 'new()' with 'new myObject()' if necessary - if (variable.Initializer?.Value is ImplicitObjectCreationExpressionSyntax implicitNew) - { - newInitializerExpr = SyntaxFactory - .ObjectCreationExpression(explicitType.WithoutTrivia()) - .WithArgumentList(implicitNew.ArgumentList ?? SyntaxFactory.ArgumentList()) - .WithTrailingTrivia(implicitNew.GetTrailingTrivia()) - .WithLeadingTrivia(implicitNew.GetLeadingTrivia()); - } - - if (variable.Initializer?.Value is DefaultExpressionSyntax defaultExpression) - { - newInitializerExpr = SyntaxFactory - .DefaultExpression(explicitType.WithoutTrivia()) - .WithType(explicitType.NormalizeWhitespace()); - } - - // Reconstruct initializer - var newInitializer = variable.Initializer?.WithValue(newInitializerExpr!); - - // Reconstruct the variable - var newVariable = variable - .WithInitializer(newInitializer) - .WithLeadingTrivia(variable.GetLeadingTrivia()) - .WithTrailingTrivia(variable.GetTrailingTrivia()); - - // Replace the declaration node - var newDeclaration = declaration - .WithType(varType) - .WithVariables(SyntaxFactory.SingletonSeparatedList(newVariable)) - .WithLeadingTrivia(declaration.GetLeadingTrivia()) - .WithTrailingTrivia(declaration.GetTrailingTrivia()); - - // Replace the old node with the new one in the tree - var newRoot = root.ReplaceNode(declaration, newDeclaration); - - return document.WithSyntaxRoot(newRoot); - } -} diff --git a/brutal.freetype/Brutal.FreeType/cmake/FindFreetype.cmake b/brutal.freetype/Brutal.FreeType/cmake/FindFreetype.cmake deleted file mode 100644 index 7068c18..0000000 --- a/brutal.freetype/Brutal.FreeType/cmake/FindFreetype.cmake +++ /dev/null @@ -1,41 +0,0 @@ -# Finds FreeType from the RocketWerkz.Brutal.FreeType NuGet package, for consumers building native -# code against freetype. Shipped inside the package (build/natives/cmake/); a consumer puts this dir -# on CMAKE_MODULE_PATH and calls find_package(Freetype). FREETYPE_NUGET_DIR is injected by the -# package's auto-imported .targets. - -# Normalise path separators (MSBuild may produce backslashes on Windows). -file(TO_CMAKE_PATH "${FREETYPE_NUGET_DIR}" FREETYPE_NUGET_DIR) - -# Point at the shared lib (and Windows import lib) inside the NuGet package. -if(WIN32) - set(freetype_shared "${FREETYPE_NUGET_DIR}/runtimes/win-x64/native/freetype.dll") - set(freetype_implib "${FREETYPE_NUGET_DIR}/build/natives/lib/win-x64/freetype.lib") -elseif(APPLE) - set(freetype_shared "${FREETYPE_NUGET_DIR}/runtimes/osx-arm64/native/libfreetype.dylib") -else() - set(freetype_shared "${FREETYPE_NUGET_DIR}/runtimes/linux-x64/native/libfreetype.so") -endif() - -# Hand find_package the results it expects. -set(FREETYPE_FOUND TRUE) -set(FREETYPE_INCLUDE_DIRS "${FREETYPE_NUGET_DIR}/build/natives/include") -set(FREETYPE_LIBRARIES "${freetype_shared}") - -# Expose the standard Freetype::Freetype target so consumers can link it. -if(NOT TARGET Freetype::Freetype) - add_library(Freetype::Freetype SHARED IMPORTED GLOBAL) - set_target_properties(Freetype::Freetype PROPERTIES - IMPORTED_LOCATION "${freetype_shared}" - INTERFACE_INCLUDE_DIRECTORIES "${FREETYPE_NUGET_DIR}/build/natives/include" - ) - # Match the soname/implib the linker expects per platform. - if(WIN32) - set_property(TARGET Freetype::Freetype PROPERTY IMPORTED_IMPLIB "${freetype_implib}") - elseif(APPLE) - set_property(TARGET Freetype::Freetype PROPERTY IMPORTED_SONAME "@rpath/libfreetype.6.dylib") - else() - set_property(TARGET Freetype::Freetype PROPERTY IMPORTED_SONAME "libfreetype.so.6") - endif() -endif() - -mark_as_advanced(FREETYPE_FOUND FREETYPE_INCLUDE_DIRS FREETYPE_LIBRARIES) diff --git a/brutal.freetype/Brutal.FreeType/msbuild/RocketWerkz.Brutal.FreeType.targets b/brutal.freetype/Brutal.FreeType/msbuild/RocketWerkz.Brutal.FreeType.targets deleted file mode 100644 index 8f135c8..0000000 --- a/brutal.freetype/Brutal.FreeType/msbuild/RocketWerkz.Brutal.FreeType.targets +++ /dev/null @@ -1,10 +0,0 @@ - - - - $([MSBuild]::NormalizePath('$(MSBuildThisFileDirectory)', '..').Replace('\', '/')) - $(CMakeBuildArgs) -DFREETYPE_NUGET_DIR=$(FreeTypeNuGetDir) - -DFREETYPE_NUGET_DIR=$(FreeTypeNuGetDir) - - diff --git a/brutal.imgui/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt b/brutal.imgui/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt new file mode 100644 index 0000000..b3cd102 --- /dev/null +++ b/brutal.imgui/LICENSES/BRUTAL-IMGUI-THIRD-PARTY-NOTICES.txt @@ -0,0 +1,175 @@ +THIRD-PARTY LICENSE NOTICES +The Brutal.ImGui packages + +This file ships in all eight packages named below. They redistribute the third-party +components listed here, each reproduced with the license that governs it. + + One file serves all eight packages, so this table says which components apply to + the package you are holding: + + RocketWerkz.Brutal.ImGui Dear ImGui, and the three stb libraries + compiled into it + RocketWerkz.Brutal.ImGui.Backends Dear ImGui's platform and renderer + backends, translated to C# + RocketWerkz.Brutal.ImGui.DemoWindow Dear ImGui's demo sources, translated + to C# + RocketWerkz.Brutal.ImGui.FreeType Dear ImGui's FreeType font adapter + RocketWerkz.Brutal.ImPlot ImPlot + RocketWerkz.Brutal.ImPlot.DemoWindow ImPlot's demo sources, translated to C# + RocketWerkz.Brutal.ImGui.Abstractions no third-party code + RocketWerkz.Brutal.ImGui.Extensions no third-party code + + Where a package ships native libraries, it ships them for every runtime identifier + it supports (win-x64, linux-x64, osx-arm64): + + Dear ImGui 1.92.2 imgui.dll / libimgui.so / libimgui.dylib + imgui_freetype.dll / libimgui_freetype.so / libimgui_freetype.dylib + ImPlot 0.17 implot.dll / libimplot.so / libimplot.dylib + + Dear ImGui vendors three of Sean Barrett's stb libraries, and all three are + compiled into the Dear ImGui binaries shipped here. They have their own section + below. + + The managed assemblies are in scope as well as the native libraries. Type names, + enumerant values and entry-point signatures are generated from the corresponding + upstream headers, and the backend and demo assemblies are C# translations of + upstream sources. + + RocketWerkz.Brutal.ImGui.FreeType binds Dear ImGui's FreeType font adapter, which + is Dear ImGui code and is covered by the Dear ImGui section below. FreeType itself + is in none of these eight packages; it is supplied by RocketWerkz.Brutal.FreeType, + whose own notices reproduce the FreeType License in full. + + +============================================================================== +Dear ImGui +============================================================================== + + Name Dear ImGui + Version 1.92.2, docking branch + Upstream https://github.com/ocornut/imgui + SPDX MIT + + Built from a RocketWerkz fork of the docking branch. The modifications are ours + and do not alter the terms below, which are reproduced from the copy these + packages were built from. + + This component covers the imgui and imgui_freetype native libraries, the managed + bindings generated from Dear ImGui's headers, and the C# translations of Dear + ImGui's backend and demo sources. + +The MIT License (MIT) + +Copyright (c) 2014-2025 Omar Cornut + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +============================================================================== +stb +============================================================================== + + Name stb_rect_pack, stb_textedit, stb_truetype + Version 1.01, 1.14, 1.26 respectively + Upstream https://github.com/nothings/stb + SPDX MIT OR Unlicense + + Vendored by Dear ImGui as imstb_rectpack.h, imstb_textedit.h and + imstb_truetype.h, and compiled into the Dear ImGui native libraries shipped + here. All three carry the same dual license, which offers a choice between + the MIT License and release into the public domain. It is reproduced once + below, from the copy these packages were built from. + +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ + + +============================================================================== +ImPlot +============================================================================== + + Name ImPlot + Version 0.17, upstream commit 3da8bd3 (26 commits after tag v0.16) + Upstream https://github.com/epezent/implot + SPDX MIT + + ImPlot is a plotting extension for Dear ImGui. Its version is the one ImPlot + reports for itself; the commit is given because upstream had not tagged 0.17 when + these packages were built. + + This component covers the implot native library, the managed bindings generated + from ImPlot's headers, and the C# translation of ImPlot's demo sources. + +MIT License + +Copyright (c) 2020 Evan Pezent + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/brutal.interop/Brutal.Interop.SourceGenerators/Brutal.Interop.SourceGenerators/InteropHandleGenerator.cs b/brutal.interop/Brutal.Interop.SourceGenerators/Brutal.Interop.SourceGenerators/InteropHandleGenerator.cs deleted file mode 100644 index ce5ffc4..0000000 --- a/brutal.interop/Brutal.Interop.SourceGenerators/Brutal.Interop.SourceGenerators/InteropHandleGenerator.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Text; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; - -namespace Brutal.Interop.SourceGenerators; - -[Generator] -public class InteropHandleGenerator : IIncrementalGenerator -{ - public void Initialize(IncrementalGeneratorInitializationContext context) - { - var pipeline = context.SyntaxProvider.ForAttributeWithMetadataName( - fullyQualifiedMetadataName: "Brutal.Interop.InteropHandleAttribute", - predicate: static (node, _) => node is StructDeclarationSyntax, - transform: static (ctx, _) => new Model(ctx) - ); - - context.RegisterSourceOutput(pipeline, static (ctx, model) => model.Generate(ctx)); - } - - private readonly record struct Model - { - private readonly string? _namespace; - private readonly string _typeName; - - public Model(GeneratorAttributeSyntaxContext context) - { - var symbol = (INamedTypeSymbol)context.TargetSymbol; - _namespace = symbol.ContainingNamespace is { IsGlobalNamespace: false } ns - ? ns.ToDisplayString() - : null; - _typeName = symbol.Name; - } - - public void Generate(SourceProductionContext context) - { - var nsDecl = _namespace is not null ? $"namespace {_namespace};\n\n" : ""; - - var source = $$""" - #nullable enable - using System.Runtime.InteropServices.Marshalling; - using Brutal.Interop; - - {{nsDecl}}[NativeMarshalling(typeof(InteropHandleMarshaller<{{_typeName}}, {{_typeName}}.Handle>))] - public readonly unsafe partial struct {{_typeName}} : IInteropHandle<{{_typeName}}.Handle, {{_typeName}}> - { - public record struct Handle(nint Value); - public required Handle Pointer { get; init; } - public bool IsNull() => Pointer.Value == 0; - public static implicit operator {{_typeName}}(void* ptr) => new() { Pointer = new Handle((nint)ptr) }; - } - """; - - context.AddSource($"{_typeName}.g.cs", SourceText.From(source, Encoding.UTF8)); - } - } -} diff --git a/brutal.monitor/Brutal.Monitor.Host/buildTransitive/RocketWerkz.Brutal.Monitor.Host.targets b/brutal.monitor/Brutal.Monitor.Host/buildTransitive/RocketWerkz.Brutal.Monitor.Host.targets deleted file mode 100644 index 9a000f4..0000000 --- a/brutal.monitor/Brutal.Monitor.Host/buildTransitive/RocketWerkz.Brutal.Monitor.Host.targets +++ /dev/null @@ -1,29 +0,0 @@ - - - - - <_MonitorBuildExecutable Include="$(TargetDir)Brutal.Monitor.Subprocess;$(TargetDir)runtimes/*/native/Brutal.Monitor.Subprocess" /> - - - - - - <_MonitorPublishExecutable Include="$(PublishDir)Brutal.Monitor.Subprocess;$(PublishDir)runtimes/*/native/Brutal.Monitor.Subprocess" /> - - - - diff --git a/brutal.numerics/Brutal.Numerics.Analyzers/Resources.cs b/brutal.numerics/Brutal.Numerics.Analyzers/Resources.cs deleted file mode 100644 index 5ae86a0..0000000 --- a/brutal.numerics/Brutal.Numerics.Analyzers/Resources.cs +++ /dev/null @@ -1,39 +0,0 @@ -using Microsoft.CodeAnalysis; - -namespace Brutal.Numerics.Analyzers; - -public static class Resources -{ - // From framework analyser BRUTAL3001 Usage of System.Drawing - public static readonly DiagnosticDescriptor SystemDrawingBrutalCore0004 = new( - "BRUTALCORE0004", - "Prefer Brutal.Numerics instead of System.Drawing.Color", - "Brutal.Numerics has colour constant types", - "Obsolete", - DiagnosticSeverity.Warning, - isEnabledByDefault: true, - description: "Use Brutal.Numerics instead of System.Drawing.Color." - ); - - // From framework analyser BRUTAL3002 Usage of System.Numerics - public static readonly DiagnosticDescriptor SystemNumericsBrutalCore0005 = new( - "BRUTALCORE0005", - "Prefer Brutal.Numerics instead of System.Numerics", - "Brutal.Numerics provides optimised numeric functions", - "Obsolete", - DiagnosticSeverity.Info, - isEnabledByDefault: true, - description: "Brutal.Numerics instead of System.Numerics." - ); - - // From framework analyser BRUTAL4002 Usage of float3.Rgb(...) to create grayscale colors - public static readonly DiagnosticDescriptor RgbToGreyBrutalCore0006 = new( - "BRUTALCORE0006", - "Prefer Brutal.Numerics.Color.Gray instead of specifying explicit color channel values", - "Brutal.Numerics provides a set of predefined colors", - "Usage", - DiagnosticSeverity.Info, - isEnabledByDefault: true, - description: "Brutal.Numerics instead of System.Numerics." - ); -} diff --git a/brutal.numerics/Brutal.Numerics.Analyzers/RgbToGrayAnalyzer.cs b/brutal.numerics/Brutal.Numerics.Analyzers/RgbToGrayAnalyzer.cs deleted file mode 100644 index bfdf210..0000000 --- a/brutal.numerics/Brutal.Numerics.Analyzers/RgbToGrayAnalyzer.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; - -namespace Brutal.Numerics.Analyzers; - -/// -/// Analyzer that flags usage of Brutal color types such as `float3.Rgb(...)` and suggests replacing it with -/// `float3.Grayscale()`. -/// -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public class RgbToGrayAnalyzer : DiagnosticAnalyzer -{ - // Keep in mind: you have to list your rules here. - public override ImmutableArray SupportedDiagnostics { get; } = - ImmutableArray.Create(Resources.RgbToGreyBrutalCore0006); - - public override void Initialize(AnalysisContext context) - { - // You must call this method to avoid analyzing generated code. - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); - - // You must call this method to enable the Concurrent Execution. - context.EnableConcurrentExecution(); - - // Only interested in invocation operations, like `float3.Rgb(...)` - context.RegisterOperationAction(AnalyzeInvocation, OperationKind.Invocation); - - // Check other 'context.Register...' methods that might be helpful for your purposes. - } - - /// - /// Called for each invocation expression in the code. - /// - /// Operation context. - private void AnalyzeInvocation(OperationAnalysisContext context) - { - if (context.Operation is not IInvocationOperation invocation) - return; - - var methodSymbol = invocation.TargetMethod; - - // Must be in Brutal namespace - if (methodSymbol.ContainingNamespace.ToDisplayString() != "Brutal.Numerics") - return; - - // Color type must match allowed set - var typeName = methodSymbol.ContainingType.Name; - switch (typeName) - { - case "float3": - case "float4": - case "byte3": - case "byte4": - case "ushort3": - case "ushort4": - break; - default: - return; - } - - // Only check methods named Rgb or Rgba - var methodName = methodSymbol.Name; - if (methodName != "Rgb" && methodName != "Rgba") - return; - - // Check argument count and argument equality - var args = invocation.Arguments; - if (methodName == "Rgb") - { - if (args.Length != 3) - return; - if (!ArgsAreEqual(args[0], args[1], args[2])) - return; - } - else if (methodName == "Rgba") - { - if (args.Length != 4) - return; - if (!ArgsAreEqual(args[0], args[1], args[2])) - return; - - var alphaLiteral = args[3].Syntax.ToString(); - - switch (typeName) - { - case "float4": - if (alphaLiteral != "1") - return; - break; - case "byte4": - if (alphaLiteral != "0xFF") - return; - break; - case "ushort4": - if (alphaLiteral != "0xFFFF") - return; - break; - default: - return; - } - } - else - return; - - var location = invocation.Syntax.GetLocation(); - - if (invocation.Syntax is InvocationExpressionSyntax invocationExpression) - { - ExpressionSyntax expr = invocationExpression; - - // Get location of method name - var methodNameToken = expr switch - { - IdentifierNameSyntax id => id.Identifier, // Simple method call like Foo() - MemberAccessExpressionSyntax memberAccess => memberAccess.Name.Identifier, // Call like obj.Method() - // Handle cases like Console.WriteLine(...) - InvocationExpressionSyntax nestedInvocation => nestedInvocation.Expression switch - { - MemberAccessExpressionSyntax nestedMemberAccess => nestedMemberAccess.Name.Identifier, // Nested like Console.WriteLine(...) - IdentifierNameSyntax nestedId => nestedId.Identifier, // Nested like Foo.Bar() - _ => default, - }, - _ => default, - }; - - location = methodNameToken.GetLocation(); - } - - // Emit a diagnostic at the location of the entire invocation - context.ReportDiagnostic(Diagnostic.Create(Resources.RgbToGreyBrutalCore0006, location)); - } - - private static bool ArgsAreEqual(IArgumentOperation a, IArgumentOperation b, IArgumentOperation c) - { - var t0 = a.Syntax.ToString(); - var t1 = b.Syntax.ToString(); - var t2 = c.Syntax.ToString(); - return t0 == t1 && t0 == t2; - } -} diff --git a/brutal.numerics/Brutal.Numerics.Analyzers/SystemDrawingAnalyzer.cs b/brutal.numerics/Brutal.Numerics.Analyzers/SystemDrawingAnalyzer.cs deleted file mode 100644 index 00d41b7..0000000 --- a/brutal.numerics/Brutal.Numerics.Analyzers/SystemDrawingAnalyzer.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System.Collections.Immutable; -using Brutal.Numerics.Analyzers; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; - -namespace Brutal.Numerics.Analyzers; - -/// -/// Analyzer that flags usage of System.Drawing.Color. -/// -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public class SystemDrawingAnalyzer : DiagnosticAnalyzer -{ - // Keep in mind: you have to list your rules here. - public override ImmutableArray SupportedDiagnostics { get; } = - ImmutableArray.Create(Resources.SystemDrawingBrutalCore0004); - - public override void Initialize(AnalysisContext context) - { - // You must call this method to avoid analyzing generated code. - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); - - // You must call this method to enable the Concurrent Execution. - context.EnableConcurrentExecution(); - - // Subscribe to semantic (compile time) action invocation, e.g. method invocation. - context.RegisterOperationAction( - AnalyzeOperation, - OperationKind.FieldReference, - OperationKind.PropertyReference - ); - } - - /// - /// Executed on the completion of the semantic analysis associated with the Invocation operation. - /// - /// Operation context. - private void AnalyzeOperation(OperationAnalysisContext context) - { - // Check if the current operation is a reference to a member (field or property), such as accessing Color.Red. - // If not, exit early as this analyzer only targets member references. - if (context.Operation is not IMemberReferenceOperation memberRef) - return; - - // Get the type that contains the referenced member, e.g., System.Drawing.Color. - var containingType = memberRef.Member.ContainingType; - if (containingType == null) - return; - - // Get the namespace of the containing type (e.g. "System.Drawing"). - var namespaceName = containingType.ContainingNamespace?.ToDisplayString(); - - // Validate the namespace and type name. If the namespace is null or empty, ignore the operation. If the - // namespace does not start with "System.Drawing" or if the type is not specifically "Color", ignore it. - // Together, this ensures we only target usages like System.Drawing.Color.Red. - if ( - namespaceName != null - && ( - string.IsNullOrEmpty(namespaceName) - || !namespaceName.StartsWith("System.Drawing", StringComparison.Ordinal) - || containingType.Name != "Color" - ) - ) - return; - - // At this point, we've confirmed a usage of System.Drawing.Color.. Create and report a diagnostic at - // the location where the member is used. - context.ReportDiagnostic( - Diagnostic.Create(Resources.SystemDrawingBrutalCore0004, memberRef.Syntax.GetLocation()) - ); - } -} diff --git a/brutal.numerics/Brutal.Numerics.Analyzers/SystemNumericsAnalyzer.cs b/brutal.numerics/Brutal.Numerics.Analyzers/SystemNumericsAnalyzer.cs deleted file mode 100644 index 407b1ff..0000000 --- a/brutal.numerics/Brutal.Numerics.Analyzers/SystemNumericsAnalyzer.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Collections.Immutable; -using Brutal.Numerics.Analyzers; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; - -namespace Brutal.Numerics.Analyzers; - -/// -/// Analyzer that reports invalid usage of System.Numerics. -/// -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public class SystemNumericsAnalyzer : DiagnosticAnalyzer -{ - // Keep in mind: you have to list your rules here. - public override ImmutableArray SupportedDiagnostics { get; } = - ImmutableArray.Create(Resources.SystemNumericsBrutalCore0005); - - public override void Initialize(AnalysisContext context) - { - // You must call this method to avoid analyzing generated code. - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); - - // You must call this method to enable the Concurrent Execution. - context.EnableConcurrentExecution(); - - // Subscribe to semantic (compile time) action invocation, e.g. method invocation. - context.RegisterOperationAction(AnalyzeOperation, OperationKind.ObjectCreation); - } - - /// - /// Executed on the completion of the semantic analysis associated with the Invocation operation. - /// - /// Operation context. - private void AnalyzeOperation(OperationAnalysisContext context) - { - // Check if the operation is an object creation (ie., 'new TypeName(...)'). Specifically targeting cases like - // 'new Vector2(...)'. - if (context.Operation is not IObjectCreationOperation objectCreation) - return; - - // Retrieve the type being instantiated - var containingType = objectCreation.Type; - if (containingType == null) - return; - - // Get the namespace of the type (e.g. "System.Numerics"). - var namespaceName = containingType.ContainingNamespace?.ToDisplayString(); - - // Ensure the namespace is valid and starts with "System.Numerics". If null or empty, the type is not from a - // relevant namespace. If the namespace doesn't match, ignore the operation. - if ( - namespaceName != null - && ( - string.IsNullOrEmpty(namespaceName) - || !namespaceName.StartsWith("System.Numerics", StringComparison.Ordinal) - ) - ) - return; - - // At this point, we've identified an instantiation of a System.Numerics type. Create and report a diagnostic - // at the source location of the 'new' expression.git - context.ReportDiagnostic( - Diagnostic.Create(Resources.SystemNumericsBrutalCore0005, context.Operation.Syntax.GetLocation()) - ); - } -} diff --git a/brutal.numerics/Brutal.Numerics.CodeFixes/RgbToGrayFixProvider.cs b/brutal.numerics/Brutal.Numerics.CodeFixes/RgbToGrayFixProvider.cs deleted file mode 100644 index 4e7aa6a..0000000 --- a/brutal.numerics/Brutal.Numerics.CodeFixes/RgbToGrayFixProvider.cs +++ /dev/null @@ -1,215 +0,0 @@ -using System.Collections.Immutable; -using System.Composition; -using Brutal.Numerics.Analyzers; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Document = Microsoft.CodeAnalysis.Document; - -namespace Brutal.Numerics.Analyzers; - -/// -/// A code fix provider that replaces calls to float3.Rgb(...) with float3.Grayscale(). -/// All code fixes must be linked to specific analyzers. -/// -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(RgbToGrayFixProvider)), Shared] -public class RgbToGrayFixProvider : CodeFixProvider -{ - public sealed override ImmutableArray FixableDiagnosticIds { get; } = - [Resources.RgbToGreyBrutalCore0006.Id]; - - // If you don't need the 'fix all' behavior, return null. - public override FixAllProvider? GetFixAllProvider() => null; - - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) - { - // We link only one diagnostic and assume there is only one diagnostic in the context. - if (context.Diagnostics.Length != 1) - { - return; - } - - var diagnostic = context.Diagnostics[0]; - var diagnosticSpan = diagnostic.Location.SourceSpan; - var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); - var diagnosticNode = root?.FindNode(diagnosticSpan); - - var invocation = diagnosticNode?.FirstAncestorOrSelf(); - if (invocation is null) - return; - - context.RegisterCodeFix( - CodeAction.Create( - title: string.Format(Resources.RgbToGreyBrutalCore0006.Id), - createChangedDocument: c => ReplaceWithGrayscaleAsync(context.Document, invocation, c), - equivalenceKey: nameof(Resources.RgbToGreyBrutalCore0006.Id) - ), - diagnostic - ); - } - - /// - /// Executed on the quick fix action raised by the user. - /// - /// Affected source file. - /// The original method invocation node. - /// Any fix is cancellable by the user, so we should support the cancellation token. - /// A modified version of the solution with the method call replaced. - private async Task ReplaceWithGrayscaleAsync( - Document document, - InvocationExpressionSyntax invocation, - CancellationToken cancellationToken - ) - { - if (invocation.Expression is not MemberAccessExpressionSyntax memberAccess) - return document; - - var method = await TryGetReplaceableMethod(memberAccess, document, cancellationToken); - if ( - method == null - || !IsMethodOfReplaceableType(method, out var typeName) - || !IsMethodParametersReplaceableByGrayscale(invocation, method.Name, typeName, out var replacementArgExpr) - ) - return document; - - var newInvocation = CreateFunctionCallToGrayscale(invocation, memberAccess, replacementArgExpr!); - var newRoot = await ReplaceNode(document, invocation, cancellationToken, newInvocation); - - return document.WithSyntaxRoot(newRoot); - } - - private static bool IsMethodOfReplaceableType(IMethodSymbol methodSymbol, out string typeName) - { - typeName = methodSymbol.ContainingType.Name; - switch (typeName) - { - case "float3" or "float4" or "byte3" or "byte4" or "ushort3" or "ushort4": - var methodName = methodSymbol.Name; - return methodName is "Rgb" or "Rgba"; - default: - return false; - } - } - - private static async Task TryGetReplaceableMethod( - MemberAccessExpressionSyntax memberAccess, - Document document, - CancellationToken cancellationToken - ) - { - var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - var symbolInfo = semanticModel.GetSymbolInfo(memberAccess, cancellationToken); - if ( - symbolInfo.Symbol is not IMethodSymbol methodSymbol - || methodSymbol.ContainingNamespace.ToDisplayString() != "Brutal.Numerics" - ) - return null; - - return methodSymbol; - } - - private static bool IsMethodParametersReplaceableByGrayscale( - InvocationExpressionSyntax invocation, - string methodName, - string typeName, - out ExpressionSyntax? replacementArgExpr - ) - { - var args = invocation.ArgumentList.Arguments; - - switch (methodName) - { - case "Rgb" when args.Count != 3 || !ArgsAreEqual(args[0], args[1], args[2]): - replacementArgExpr = null; - return false; - case "Rgb": - replacementArgExpr = args[0].Expression; - break; - case "Rgba" when args.Count != 4 || !ArgsAreEqual(args[0], args[1], args[2]): - replacementArgExpr = null; - return false; - case "Rgba": - { - var alphaLiteral = args[3].Expression.ToString(); - - switch (typeName) - { - case "float4": - if (alphaLiteral != "1") - { - replacementArgExpr = null; - return false; - } - - break; - case "byte4": - if (alphaLiteral != "0xFF") - { - replacementArgExpr = null; - return false; - } - - break; - case "ushort4": - if (alphaLiteral != "0xFFFF") - { - replacementArgExpr = null; - return false; - } - - break; - default: - replacementArgExpr = null; - return false; - } - - replacementArgExpr = args[0].Expression; - break; - } - default: - replacementArgExpr = null; - return false; - } - - return true; - } - - private static InvocationExpressionSyntax CreateFunctionCallToGrayscale( - InvocationExpressionSyntax invocation, - MemberAccessExpressionSyntax memberAccess, - ExpressionSyntax replacementArgExpr - ) - { - var newMemberAccess = memberAccess.WithName(SyntaxFactory.IdentifierName("Grayscale")); - var newInvocation = invocation - .WithExpression(newMemberAccess) - .WithArgumentList( - SyntaxFactory.ArgumentList( - SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Argument(replacementArgExpr)) - ) - ); - return newInvocation; - } - - private static async Task ReplaceNode( - Document document, - InvocationExpressionSyntax invocation, - CancellationToken cancellationToken, - InvocationExpressionSyntax newInvocation - ) - { - var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var newRoot = root!.ReplaceNode(invocation, newInvocation); - return newRoot; - } - - private static bool ArgsAreEqual(ArgumentSyntax a, ArgumentSyntax b, ArgumentSyntax c) - { - var t0 = a.ToString(); - var t1 = b.ToString(); - var t2 = c.ToString(); - return t0 == t1 && t0 == t2; - } -} diff --git a/brutal.strings/Brutal.Strings.Analyzers/PreferString8OverloadAnalyzer.cs b/brutal.strings/Brutal.Strings.Analyzers/PreferString8OverloadAnalyzer.cs deleted file mode 100644 index dfcab34..0000000 --- a/brutal.strings/Brutal.Strings.Analyzers/PreferString8OverloadAnalyzer.cs +++ /dev/null @@ -1,188 +0,0 @@ -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; - -namespace Brutal.Strings.Analyzers; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public class PreferString8OverloadAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics { get; } = - [Resources.PreferU8OverloadBrutalCore0011]; - - public override void Initialize(AnalysisContext context) - { - context.EnableConcurrentExecution(); - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); - - context.RegisterCompilationStartAction(startContext => - { - // Early-exit if ReadOnlySpan is unavailable (e.g. netstandard2.0 without System.Memory) - var readOnlySpan = startContext.Compilation.GetTypeByMetadataName("System.ReadOnlySpan`1"); - if (readOnlySpan is null) - return; - - var analyzer = new PreferString8OverloadCompilationAnalyzer(startContext.Compilation, readOnlySpan); - startContext.RegisterOperationAction(analyzer.Analyze, OperationKind.Argument, OperationKind.Conversion); - }); - } -} - -/* - * Follow the guidelines frmo RS1008 (https://dotnetrules.com): - * Avoid storing per-compilation data into the fields of a diagnostic analyzer - * Instance of a diagnostic analyzer might outlive the lifetime of compilation. - * Hence, storing per-compilation data, such as symbols, into the fields of a diagnostic analyzer might cause stale compilations to stay alive and cause memory leaks. - * Instead, you should store this data on a separate type instantiated in a compilation start action, registered using 'AnalysisContext.RegisterCompilationStartAction' API. - * An instance of this type will be created per-compilation and it won't outlive compilation's lifetime, hence avoiding memory leaks. - */ -class PreferString8OverloadCompilationAnalyzer(Compilation compilation, INamedTypeSymbol readOnlySpan) -{ - private readonly INamedTypeSymbol _readOnlySpanByte = readOnlySpan.Construct( - compilation.GetSpecialType(SpecialType.System_Byte) - ); - - private bool IsString8(ITypeSymbol type) => compilation.HasImplicitConversion(_readOnlySpanByte, type); - - private static bool IsString16(ITypeSymbol type) => type.SpecialType == SpecialType.System_String; - - /// Is method a compatible replacement for ? - private bool IsCompatible(OperationAnalysisContext context, IMethodSymbol method, IMethodSymbol overload) - { - /* - * We want to err on the side of caution: only suggest using an overload if it is _strictly_ identical: - * - same kind/generic-ness etc. - * - same type parameters (same constraints etc.) - * - same parameters (except for string/String8 of course) - * - * We won't suggest overloads with (type) parameters that _could_ be compatible through conversion, type constraints etc. - */ - - if (method.MethodKind != overload.MethodKind) - return false; - - var isGeneric = method.IsGenericMethod; - if (isGeneric != overload.IsGenericMethod) - return false; - - // ignore self - if (SymbolEqualityComparer.IncludeNullability.Equals(isGeneric ? method.OriginalDefinition : method, overload)) - return false; - - // is the overload accessible from the call site? - if (!compilation.IsSymbolAccessibleWithin(overload, context.ContainingSymbol.ContainingType)) - return false; - - if (isGeneric) - { - // compare type parameters - if (!method.TypeParameters.SequenceEqual(overload.TypeParameters, IsCompatible)) - return false; - } - - // compare parameters - if (!method.Parameters.SequenceEqual(overload.Parameters, (a, b) => IsCompatible(a.Type, b.Type))) - return false; - - return true; - } - - /// Is type a compatible replacement for ? - private bool IsCompatible(ITypeSymbol methodParamType, ITypeSymbol overloadParamType) - { - if (SymbolEqualityComparer.IncludeNullability.Equals(methodParamType, overloadParamType)) - return true; - - if (IsString16(methodParamType) && IsString8(overloadParamType)) - return true; - - return false; - } - - /// Are type parameters a and b compatible? - private static bool IsCompatible(ITypeParameterSymbol a, ITypeParameterSymbol b) - { - return a.AllowsRefLikeType == b.AllowsRefLikeType - && a.HasConstructorConstraint == b.HasConstructorConstraint - && a.HasNotNullConstraint == b.HasNotNullConstraint - && a.HasReferenceTypeConstraint == b.HasReferenceTypeConstraint - && a.HasUnmanagedTypeConstraint == b.HasUnmanagedTypeConstraint - && a.HasValueTypeConstraint == b.HasValueTypeConstraint - && a.Variance == b.Variance - && Utility.SequenceEqual(a.ConstraintTypes, b.ConstraintTypes, SymbolEqualityComparer.IncludeNullability); - } - - public void Analyze(OperationAnalysisContext context) - { - switch (context.Operation) - { - case IArgumentOperation argumentOp: - { - var parameter = argumentOp.Parameter; - if (parameter == null) - break; - - // is the current argument a string literal? - if (!IsString16(parameter.Type) || argumentOp.Value.Syntax is not LiteralExpressionSyntax) - break; - - if (argumentOp.Parent is not IInvocationOperation parent) - break; - - // does the method have an overload that takes a UTF8 string instead? - var method = parent.TargetMethod; - var overloads = method.ContainingType.GetMembers(method.Name).OfType(); - var overload = overloads.FirstOrDefault(o => IsCompatible(context, method, o)); - - if (overload == null) - break; - - // suggest using a UTF8 literal instead of a string - var message = overload.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); - ReportDiagnostic(message); - break; - } - - case IConversionOperation conversionOp: - { - if (conversionOp.OperatorMethod == null) - break; - - // are we converting from a string literal? - if (conversionOp.Operand is not ILiteralOperation { Type.SpecialType: SpecialType.System_String }) - break; - - // is the target type assignable from UTF8? - var targetType = conversionOp.Type; - if (targetType == null || !IsString8(targetType)) - break; - - // find the actual conversion method - only for displaying to the user / debugging - var conversions = targetType - .GetMembers() - .OfType() - .Where(m => m.MethodKind == MethodKind.Conversion); - var overload = conversions.FirstOrDefault(m => IsString8(m.Parameters[0].Type)); - var message = - overload?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) - ?? $"{targetType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)} implicit conversion from UTF8"; - - // suggest using a UTF8 literal instead of a string - ReportDiagnostic(message); - break; - } - } - - void ReportDiagnostic(string message) - { - var diagnostic = Diagnostic.Create( - Resources.PreferU8OverloadBrutalCore0011, - context.Operation.Syntax.GetLocation(), - message - ); - context.ReportDiagnostic(diagnostic); - } - } -} diff --git a/brutal.strings/Brutal.Strings.Analyzers/Resources.cs b/brutal.strings/Brutal.Strings.Analyzers/Resources.cs deleted file mode 100644 index 20f1edd..0000000 --- a/brutal.strings/Brutal.Strings.Analyzers/Resources.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Microsoft.CodeAnalysis; - -namespace Brutal.Strings.Analyzers; - -public static class Resources -{ - public static readonly DiagnosticDescriptor BrutalCore0001 = new( - "BRUTALCORE0001", - "Avoid calling ToString on (ReadOnly)Span", - "ToString() on a span does not convert the contents to a string, did you mean to use ToString16?", - "Intent", - DiagnosticSeverity.Warning, - isEnabledByDefault: true, - description: "Span.ToString() does not decode the bytes to a string." - ); - public const string BrutalCore0001Suggestion = "Use .ToString16()"; - - public static readonly DiagnosticDescriptor BrutalCore0002 = new( - "BRUTALCORE0002", - "Avoid calling ToString on (ReadOnly)Span where T is not string or byte", - "ToString() on a span does not convert the contents to a string, did you mean to use a different method?", - "Intent", - DiagnosticSeverity.Warning, - isEnabledByDefault: true, - description: "Span.ToString() does not decode the content to a string." - ); - - public static readonly DiagnosticDescriptor PreferU8OverloadBrutalCore0011 = new( - "BRUTALCORE0011", - "Prefer using a UTF8 string", - "Prefer using a UTF8 string: {0}", - "Usage", - DiagnosticSeverity.Warning, - isEnabledByDefault: true - ); - public const string PreferU8OverloadBrutalCore0011Suggestion = "Append u8 to the string literal"; -} diff --git a/brutal.strings/Brutal.Strings.Analyzers/SpanToStringAnalyzer.cs b/brutal.strings/Brutal.Strings.Analyzers/SpanToStringAnalyzer.cs deleted file mode 100644 index 8094795..0000000 --- a/brutal.strings/Brutal.Strings.Analyzers/SpanToStringAnalyzer.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; - -namespace Brutal.Strings.Analyzers; - -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public class SpanToStringAnalyzer : DiagnosticAnalyzer -{ - // Keep in mind: you have to list your rules here. - public override ImmutableArray SupportedDiagnostics { get; } = - [Resources.BrutalCore0001, Resources.BrutalCore0002]; - - public override void Initialize(AnalysisContext context) - { - // You must call this method to avoid analyzing generated code. - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); - - // You must call this method to enable the Concurrent Execution. - context.EnableConcurrentExecution(); - - // Monitor (method) invocations - context.RegisterOperationAction(AnalyzeInvocation, OperationKind.Invocation); - } - - private static void AnalyzeInvocation(OperationAnalysisContext context) - { - var invocation = (IInvocationOperation)context.Operation; - var method = invocation.TargetMethod; - - if (method.Name != "ToString") - return; - - var type = method.ContainingType; - if (type.TypeArguments.Length != 1) - return; - - var compilation = context.Compilation; - var spanType = compilation.GetTypeByMetadataName("System.Span`1"); - var readOnlySpanType = compilation.GetTypeByMetadataName("System.ReadOnlySpan`1"); - - // no need for IncludeNullability as all types we're testing are value types, and spans can't be nullable - var comparer = SymbolEqualityComparer.Default; - - if ( - !comparer.Equals(type.OriginalDefinition, spanType) - && !comparer.Equals(type.OriginalDefinition, readOnlySpanType) - ) - return; - - var typeArg = type.TypeArguments[0]; - var charType = compilation.GetTypeByMetadataName("System.Char"); - var byteType = compilation.GetTypeByMetadataName("System.Byte"); - - // Span.ToString() is ok - if (comparer.Equals(typeArg, charType)) - return; - - var rule = comparer.Equals(typeArg, byteType) ? Resources.BrutalCore0001 : Resources.BrutalCore0002; - - var invocationSyntax = (InvocationExpressionSyntax)invocation.Syntax; - var memberAccess = (MemberAccessExpressionSyntax)invocationSyntax.Expression; - var methodSyntax = memberAccess.Name; - - var diagnostic = Diagnostic.Create(rule, methodSyntax.GetLocation()); - context.ReportDiagnostic(diagnostic); - } -} diff --git a/brutal.strings/Brutal.Strings.Analyzers/Utility.cs b/brutal.strings/Brutal.Strings.Analyzers/Utility.cs deleted file mode 100644 index 4c27739..0000000 --- a/brutal.strings/Brutal.Strings.Analyzers/Utility.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; - -public static class Utility -{ - public static bool SequenceEqual( - ImmutableArray a, - ImmutableArray b, - SymbolEqualityComparer comparer - ) - where TSymbol : class, ISymbol - { - var aUp = ImmutableArray.CastUp(a); - var bUp = ImmutableArray.CastUp(b); - return aUp.SequenceEqual(bUp, comparer); - } -} diff --git a/brutal.strings/Brutal.Strings.CodeFixes/PreferString8OverloadFixProvider.cs b/brutal.strings/Brutal.Strings.CodeFixes/PreferString8OverloadFixProvider.cs deleted file mode 100644 index 61b21ed..0000000 --- a/brutal.strings/Brutal.Strings.CodeFixes/PreferString8OverloadFixProvider.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System.Collections.Immutable; -using System.Composition; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace Brutal.Strings.Analyzers; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(PreferString8OverloadFixProvider)), Shared] -public class PreferString8OverloadFixProvider : CodeFixProvider -{ - private static readonly string DiagnosticId = Resources.PreferU8OverloadBrutalCore0011.Id; - private const string Suggestion = Resources.PreferU8OverloadBrutalCore0011Suggestion; - - public sealed override ImmutableArray FixableDiagnosticIds { get; } = [DiagnosticId]; - - public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; - - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) - { - // We link only one diagnostic and assume there is only one diagnostic in the context. - var diagnostic = context.Diagnostics.Single(); - - // 'SourceSpan' of 'Location' is the highlighted area. We're going to use this area to find the 'SyntaxNode' to rename. - var diagnosticSpan = diagnostic.Location.SourceSpan; - - // Get the root of Syntax Tree that contains the highlighted diagnostic. - var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); - - // Find SyntaxNode corresponding to the diagnostic. - var diagnosticNode = root?.FindNode(diagnosticSpan); - - // We expect a string literal (argument or conversion) - var literal = diagnosticNode switch - { - ArgumentSyntax { Expression: LiteralExpressionSyntax literalArg } => literalArg, - LiteralExpressionSyntax literalConversion => literalConversion, - _ => null, - }; - if (literal == null) - return; - - // Register a code action that will invoke the fix. - context.RegisterCodeFix( - CodeAction.Create( - title: Suggestion, - createChangedSolution: c => FixAsync(context.Document, literal, c), - equivalenceKey: nameof(DiagnosticId) - ), - diagnostic - ); - } - - private static async Task FixAsync( - Document document, - LiteralExpressionSyntax stringLiteral, - CancellationToken cancellationToken - ) - { - var root = await document.GetSyntaxRootAsync(cancellationToken); - if (root == null) - return document.Project.Solution; - - // change from "literal" to "literal"u8 - var token = stringLiteral.Token; - var u8Token = SyntaxFactoryExtensions.Utf8Literal(token.Text + "u8", token.ValueText); - var u8Literal = SyntaxFactory.LiteralExpression(SyntaxKind.Utf8StringLiteralExpression, u8Token); - var newRoot = root.ReplaceNode(stringLiteral, u8Literal); - var newDocument = document.WithSyntaxRoot(newRoot); - return newDocument.Project.Solution; - } -} diff --git a/brutal.strings/Brutal.Strings.CodeFixes/SpanToStringFixProvider.cs b/brutal.strings/Brutal.Strings.CodeFixes/SpanToStringFixProvider.cs deleted file mode 100644 index a54e99f..0000000 --- a/brutal.strings/Brutal.Strings.CodeFixes/SpanToStringFixProvider.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.Collections.Immutable; -using System.Composition; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; - -namespace Brutal.Strings.Analyzers; - -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SpanToStringFixProvider)), Shared] -public class SpanToStringFixProvider : CodeFixProvider -{ - // Specify the diagnostic IDs of analyzers that are expected to be linked. - public sealed override ImmutableArray FixableDiagnosticIds { get; } = [Resources.BrutalCore0001.Id]; - - // If you don't need the 'fix all' behaviour, return null. - public override FixAllProvider? GetFixAllProvider() => null; - - public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) - { - // We link only one diagnostic and assume there is only one diagnostic in the context. - var diagnostic = context.Diagnostics.Single(); - - // 'SourceSpan' of 'Location' is the highlighted area. We're going to use this area to find the 'SyntaxNode' to rename. - var diagnosticSpan = diagnostic.Location.SourceSpan; - - // Get the root of Syntax Tree that contains the highlighted diagnostic. - var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); - - // Find SyntaxNode corresponding to the diagnostic. - var diagnosticNode = root?.FindNode(diagnosticSpan)!; - - // Register a code action that will invoke the fix. - context.RegisterCodeFix( - CodeAction.Create( - title: Resources.BrutalCore0001Suggestion, - createChangedSolution: c => FixToStringAsync(context.Document, diagnosticNode, c), - equivalenceKey: nameof(Resources.BrutalCore0001.Id) - ), - diagnostic - ); - } - - /// - /// Executed on the quick fix action raised by the user. - /// - /// Affected source file. - /// The syntax node that we found in 'RegisterCodeFixesAsync'. - /// Any fix is cancellable by the user, so we should support the cancellation token. - /// Clone of the solution with updates: renamed class. - private static async Task FixToStringAsync( - Document document, - SyntaxNode methodName, - CancellationToken cancellationToken - ) - { - // change from "ReadOnlySpan.ToString()" to "ReadOnlySpan.ToString16()" - var root = await document.GetSyntaxRootAsync(cancellationToken); - if (root == null) - return document.Project.Solution; - - var newName = SyntaxFactory.IdentifierName("ToString16"); - var newRoot = root.ReplaceNode(methodName, newName); - var newDocument = document.WithSyntaxRoot(newRoot); - return newDocument.Project.Solution; - } -} diff --git a/brutal.strings/Brutal.Strings.CodeFixes/SyntaxFactoryExtensions.cs b/brutal.strings/Brutal.Strings.CodeFixes/SyntaxFactoryExtensions.cs deleted file mode 100644 index 4b17cf4..0000000 --- a/brutal.strings/Brutal.Strings.CodeFixes/SyntaxFactoryExtensions.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; - -namespace Brutal.Strings.Analyzers; - -using static SyntaxFactory; - -// TODO: move this to a shared package... -public static class SyntaxFactoryExtensions -{ - /// - public static SyntaxToken Utf8Literal(string value) - { - return Utf8Literal(SymbolDisplay.FormatLiteral(value, quote: true) + "u8", value); - } - - /// - /// Creates a token with kind Utf8StringLiteralToken from the text and corresponding string value. - /// - /// The raw text of the literal, including quotes and escape sequences. - /// The string value to be represented by the returned token. - public static SyntaxToken Utf8Literal(string text, string value) - { - return Token(SyntaxTriviaList.Empty, SyntaxKind.Utf8StringLiteralToken, text, value, SyntaxTriviaList.Empty); - } -} diff --git a/brutal.zlib/Brutal.ZLib/cmake/FindZLIB.cmake b/brutal.zlib/Brutal.ZLib/cmake/FindZLIB.cmake deleted file mode 100644 index 9b99035..0000000 --- a/brutal.zlib/Brutal.ZLib/cmake/FindZLIB.cmake +++ /dev/null @@ -1,41 +0,0 @@ -# Finds Zlib from the RocketWerkz.Brutal.Zlib NuGet package, for consumers building native -# code against zlib. Shipped inside the package (build/natives/cmake/); a consumer puts this dir -# on CMAKE_MODULE_PATH and calls find_package(ZLIB). ZLIB_NUGET_DIR is injected by the -# package's auto-imported .targets. - -# Normalise path separators (MSBuild may produce backslashes on Windows). -file(TO_CMAKE_PATH "${ZLIB_NUGET_DIR}" ZLIB_NUGET_DIR) - -# Point at the shared lib (and Windows import lib) inside the NuGet package. -if(WIN32) - set(zlib_shared "${ZLIB_NUGET_DIR}/runtimes/win-x64/native/zlib.dll") - set(zlib_implib "${ZLIB_NUGET_DIR}/build/natives/lib/win-x64/zlib.lib") -elseif(APPLE) - set(zlib_shared "${ZLIB_NUGET_DIR}/runtimes/osx-arm64/native/libzlib.dylib") -else() - set(zlib_shared "${ZLIB_NUGET_DIR}/runtimes/linux-x64/native/libzlib.so") -endif() - -# Hand find_package the results it expects. -set(ZLIB_FOUND TRUE) -set(ZLIB_INCLUDE_DIRS "${ZLIB_NUGET_DIR}/build/natives/include") -set(ZLIB_LIBRARIES "${zlib_shared}") - -# Expose the standard ZLIB::ZLIB target so consumers (FreeType/libpng) can link it. -if(NOT TARGET ZLIB::ZLIB) - add_library(ZLIB::ZLIB SHARED IMPORTED GLOBAL) - set_target_properties(ZLIB::ZLIB PROPERTIES - IMPORTED_LOCATION "${zlib_shared}" - INTERFACE_INCLUDE_DIRECTORIES "${ZLIB_NUGET_DIR}/build/natives/include" - ) - # Match the soname/implib the linker expects per platform. - if(WIN32) - set_property(TARGET ZLIB::ZLIB PROPERTY IMPORTED_IMPLIB "${zlib_implib}") - elseif(APPLE) - set_property(TARGET ZLIB::ZLIB PROPERTY IMPORTED_SONAME "@rpath/libzlib.1.dylib") - else() - set_property(TARGET ZLIB::ZLIB PROPERTY IMPORTED_SONAME "libzlib.so.1") - endif() -endif() - -mark_as_advanced(ZLIB_FOUND ZLIB_INCLUDE_DIRS ZLIB_LIBRARIES) diff --git a/brutal.zlib/Brutal.ZLib/msbuild/RocketWerkz.Brutal.ZLib.targets b/brutal.zlib/Brutal.ZLib/msbuild/RocketWerkz.Brutal.ZLib.targets deleted file mode 100644 index 487a5e4..0000000 --- a/brutal.zlib/Brutal.ZLib/msbuild/RocketWerkz.Brutal.ZLib.targets +++ /dev/null @@ -1,10 +0,0 @@ - - - - $([MSBuild]::NormalizePath('$(MSBuildThisFileDirectory)', '..').Replace('\', '/')) - $(CMakeBuildArgs) -DZLIB_NUGET_DIR=$(ZLibNuGetDir) - -DZLIB_NUGET_DIR=$(ZLibNuGetDir) - -