From 5aa43706225aa27f6ce930809900e4dfe037d02b Mon Sep 17 00:00:00 2001 From: Daniel Cazzulino Date: Tue, 29 Sep 2026 22:10:09 -0300 Subject: [PATCH] Copy custom attributes onto generated stunts so reflection and omitted calls see them. Optional defaults are emitted as attributes, since an override cannot spell = value without a warning. --- .../Processors/AttributeReplication.cs | 446 ++++++++++++++++++ .../Processors/CSharpRewrite.cs | 45 +- .../Processors/MemberScaffold.cs | 91 +++- src/Stunts.Package/Stunts.Package.msbuildproj | 2 +- src/Stunts.UnitTests/ArgumentTests.cs | 6 - src/Stunts.UnitTests/Castle/AttributeTests.cs | 307 ++++++++++++ 6 files changed, 843 insertions(+), 54 deletions(-) create mode 100644 src/Stunts.CompiledProxy/Processors/AttributeReplication.cs create mode 100644 src/Stunts.UnitTests/Castle/AttributeTests.cs diff --git a/src/Stunts.CompiledProxy/Processors/AttributeReplication.cs b/src/Stunts.CompiledProxy/Processors/AttributeReplication.cs new file mode 100644 index 00000000..8850d5f0 --- /dev/null +++ b/src/Stunts.CompiledProxy/Processors/AttributeReplication.cs @@ -0,0 +1,446 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace Stunts.Processors +{ + /// + /// Copies custom attributes from the proxied API onto the generated stunt. + /// + /// + /// + /// Types and methods already surface inheritable attributes through + /// GetCustomAttributes(inherit: true), so only non-inheritable ones + /// (, ) + /// are copied there. Properties, events, parameters, return values, and + /// constructors do not inherit attribute data onto the override, so those + /// are copied whether or not is set. + /// + /// + /// Compiler attributes that the signature already spells (params, in, + /// out, nullable) are left out so the generated declaration does not + /// apply them twice. + /// + /// + static class AttributeReplication + { + static readonly SymbolDisplayFormat TypeFormat = new SymbolDisplayFormat( + globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, + typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, + genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, + miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers); + + // Written by the compiler from keywords and annotations we already emit. + static readonly HashSet Skip = new HashSet(StringComparer.Ordinal) + { + "System.ParamArrayAttribute", + "System.Runtime.CompilerServices.AsyncStateMachineAttribute", + "System.Runtime.CompilerServices.CompilerGeneratedAttribute", + "System.Runtime.CompilerServices.DynamicAttribute", + "System.Runtime.CompilerServices.ExtensionAttribute", + "System.Runtime.CompilerServices.ExtensionMarkerAttribute", + "System.Runtime.CompilerServices.IsByRefLikeAttribute", + "System.Runtime.CompilerServices.IsReadOnlyAttribute", + "System.Runtime.CompilerServices.IsUnmanagedAttribute", + "System.Runtime.CompilerServices.IteratorStateMachineAttribute", + "System.Runtime.CompilerServices.NativeIntegerAttribute", + "System.Runtime.CompilerServices.NullableAttribute", + "System.Runtime.CompilerServices.NullableContextAttribute", + "System.Runtime.CompilerServices.ParamCollectionAttribute", + "System.Runtime.CompilerServices.PreserveBaseOverridesAttribute", + "System.Runtime.CompilerServices.RefSafetyRulesAttribute", + "System.Runtime.CompilerServices.RequiredMemberAttribute", + "System.Runtime.CompilerServices.RequiresLocationAttribute", + "System.Runtime.CompilerServices.ScopedRefAttribute", + "System.Runtime.CompilerServices.SetsRequiredMembersAttribute", + "System.Runtime.CompilerServices.TupleElementNamesAttribute", + "System.Runtime.InteropServices.ComImportAttribute", + "System.Runtime.InteropServices.TypeIdentifierAttribute", + }; + + public static SyntaxList Replicate(ISymbol symbol, AttributeTargets target, IAssemblySymbol assembly, bool includeInherited) + { + var lists = new List(); + foreach (var attribute in symbol.GetAttributes()) + { + if (Replicate(attribute, symbol, target, assembly, includeInherited, targetKind: null) is AttributeListSyntax list) + lists.Add(list); + } + + return List(lists); + } + + /// + /// Optional values are not ordinary attributes on a source symbol. The compiler + /// stores them as and + /// + /// (or / + /// ). + /// Spelling = value on an override is CS1066, so the attributes are emitted directly. + /// + public static SyntaxList Defaults(IParameterSymbol parameter) + { + if (!parameter.HasExplicitDefaultValue || parameter.IsParams || HasDefaultAttribute(parameter)) + return default; + + var lists = new List + { + AttributeList(SingletonSeparatedList(Attribute(ParseName("global::System.Runtime.InteropServices.OptionalAttribute")))), + }; + if (ValueAttribute(parameter) is AttributeListSyntax value) + lists.Add(value); + return List(lists); + } + + static bool HasDefaultAttribute(IParameterSymbol parameter) + { + foreach (var attribute in parameter.GetAttributes()) + { + if (attribute.AttributeClass == null) + continue; + switch (MetadataName(attribute.AttributeClass)) + { + case "System.Runtime.InteropServices.OptionalAttribute": + case "System.Runtime.InteropServices.DefaultParameterValueAttribute": + case "System.Runtime.CompilerServices.DecimalConstantAttribute": + case "System.Runtime.CompilerServices.DateTimeConstantAttribute": + return true; + } + } + + return false; + } + + static AttributeListSyntax? ValueAttribute(IParameterSymbol parameter) + { + var type = parameter.Type; + var value = parameter.ExplicitDefaultValue; + if (type.SpecialType == SpecialType.System_Decimal && value is decimal number) + return DecimalConstant(number); + if (type.SpecialType == SpecialType.System_DateTime && value is DateTime time) + return DateTimeConstant(time); + if (Constant(value, type) is not ExpressionSyntax expression) + return null; + + return AttributeList(SingletonSeparatedList( + Attribute(ParseName("global::System.Runtime.InteropServices.DefaultParameterValueAttribute")) + .WithArgumentList(AttributeArgumentList(SingletonSeparatedList(AttributeArgument(expression)))))); + } + + static AttributeListSyntax DecimalConstant(decimal number) + { + var bits = decimal.GetBits(number); + var scale = (byte)((bits[3] >> 16) & 0x7F); + var sign = (bits[3] & int.MinValue) != 0 ? (byte)1 : (byte)0; + return AttributeList(SingletonSeparatedList( + Attribute(ParseName("global::System.Runtime.CompilerServices.DecimalConstantAttribute")) + .WithArgumentList(AttributeArgumentList(SeparatedList(new[] + { + AttributeArgument(CastExpression(PredefinedType(Token(SyntaxKind.ByteKeyword)), Number(scale))), + AttributeArgument(CastExpression(PredefinedType(Token(SyntaxKind.ByteKeyword)), Number(sign))), + AttributeArgument(Number(bits[2])), + AttributeArgument(Number(bits[1])), + AttributeArgument(Number(bits[0])), + }))))); + } + + static AttributeListSyntax DateTimeConstant(DateTime time) + => AttributeList(SingletonSeparatedList( + Attribute(ParseName("global::System.Runtime.CompilerServices.DateTimeConstantAttribute")) + .WithArgumentList(AttributeArgumentList(SingletonSeparatedList( + AttributeArgument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(time.Ticks)))))))); + + static ExpressionSyntax? Constant(object? value, ITypeSymbol type) + { + if (value == null) + return CastExpression(TypeName(type), LiteralExpression(SyntaxKind.NullLiteralExpression)); + if (type.TypeKind == TypeKind.Enum && type is INamedTypeSymbol enumType && enumType.EnumUnderlyingType != null) + { + var literal = Primitive(value, enumType.EnumUnderlyingType); + if (literal == null) + return null; + return CastExpression(TypeName(enumType), literal is LiteralExpressionSyntax ? literal : ParenthesizedExpression(literal)); + } + + if (type is INamedTypeSymbol named && named.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T && named.TypeArguments.Length == 1) + type = named.TypeArguments[0]; + return Primitive(value, type); + } + + public static SyntaxList ReplicateReturn(IMethodSymbol method, IAssemblySymbol assembly) + { + var lists = new List(); + foreach (var attribute in method.GetReturnTypeAttributes()) + { + if (Replicate(attribute, method, AttributeTargets.ReturnValue, assembly, includeInherited: true, SyntaxKind.ReturnKeyword) is AttributeListSyntax list) + lists.Add(list); + } + + return List(lists); + } + + static AttributeListSyntax? Replicate(AttributeData attribute, ISymbol owner, AttributeTargets target, IAssemblySymbol assembly, bool includeInherited, SyntaxKind? targetKind) + { + if (attribute.AttributeClass is not INamedTypeSymbol attributeClass || attributeClass.TypeKind == TypeKind.Error) + return null; + if (attribute.AttributeConstructor == null) + return null; + if (!includeInherited && Inherited(attributeClass)) + return null; + if ((Targets(attributeClass) & target) == 0) + return null; + if (Skip.Contains(MetadataName(attributeClass)) || IsSecurityAttribute(attributeClass)) + return null; + if (owner is IParameterSymbol parameter && ImpliedBySignature(parameter, MetadataName(attributeClass))) + return null; + if (!Accessible(attributeClass, assembly) || !Accessible(attribute.AttributeConstructor, assembly)) + return null; + + var arguments = new List(); + foreach (var constant in attribute.ConstructorArguments) + { + if (Expression(constant) is not ExpressionSyntax value) + return null; + arguments.Add(AttributeArgument(value)); + } + + foreach (var named in attribute.NamedArguments) + { + if (!NamedAccessible(attributeClass, named.Key, assembly)) + return null; + if (Expression(named.Value) is not ExpressionSyntax value) + return null; + arguments.Add(AttributeArgument(NameEquals(IdentifierName(named.Key)), null, value)); + } + + var syntax = Attribute(ParseName(attributeClass.ToDisplayString(TypeFormat))); + if (arguments.Count > 0) + syntax = syntax.WithArgumentList(AttributeArgumentList(SeparatedList(arguments))); + + var list = AttributeList(SingletonSeparatedList(syntax)); + return targetKind == null + ? list + : list.WithTarget(AttributeTargetSpecifier(Token(targetKind.Value))); + } + + // `in`, `out`, and `params` already emit these. Copying them again is CS0579. + static bool ImpliedBySignature(IParameterSymbol parameter, string metadataName) + { + if (metadataName == "System.ParamArrayAttribute") + return true; + if (metadataName == "System.Runtime.InteropServices.InAttribute" && parameter.RefKind == RefKind.In) + return true; + if (metadataName == "System.Runtime.InteropServices.OutAttribute" && parameter.RefKind == RefKind.Out) + return true; + return false; + } + + static bool Inherited(INamedTypeSymbol attributeClass) + { + var usage = Usage(attributeClass); + if (usage == null) + return true; + + foreach (var named in usage.NamedArguments) + { + if (named.Key == nameof(AttributeUsageAttribute.Inherited) && named.Value.Value is bool inherited) + return inherited; + } + + return true; + } + + static AttributeTargets Targets(INamedTypeSymbol attributeClass) + { + var usage = Usage(attributeClass); + if (usage == null || usage.ConstructorArguments.Length == 0 || usage.ConstructorArguments[0].Value == null) + return AttributeTargets.All; + + return (AttributeTargets)Convert.ToInt32(usage.ConstructorArguments[0].Value); + } + + static AttributeData? Usage(INamedTypeSymbol attributeClass) + { + for (var type = attributeClass; type != null; type = type.BaseType) + { + var usage = type.GetAttributes().FirstOrDefault(attribute => + attribute.AttributeClass != null && MetadataName(attribute.AttributeClass) == "System.AttributeUsageAttribute"); + if (usage != null) + return usage; + } + + return null; + } + + static bool IsSecurityAttribute(INamedTypeSymbol attributeClass) + { + for (var type = attributeClass; type != null; type = type.BaseType) + { + if (MetadataName(type) == "System.Security.Permissions.SecurityAttribute") + return true; + } + + return false; + } + + static bool NamedAccessible(INamedTypeSymbol attributeClass, string name, IAssemblySymbol assembly) + { + for (var type = attributeClass; type != null; type = type.BaseType) + { + var member = type.GetMembers(name).FirstOrDefault(candidate => candidate is IPropertySymbol or IFieldSymbol); + if (member is IPropertySymbol property) + return property.SetMethod != null && Accessible(property.SetMethod, assembly); + if (member is IFieldSymbol field) + return Accessible(field, assembly); + } + + return false; + } + + static bool Accessible(ISymbol symbol, IAssemblySymbol from) + { + for (ISymbol? current = symbol; current != null && current is not INamespaceSymbol; current = current.ContainingSymbol) + { + switch (current.DeclaredAccessibility) + { + case Accessibility.Public: + continue; + case Accessibility.Internal: + case Accessibility.ProtectedOrInternal: + if (SymbolEqualityComparer.Default.Equals(current.ContainingAssembly, from) || + current.ContainingAssembly.GivesAccessTo(from)) + continue; + return false; + default: + return false; + } + } + + return true; + } + + static string MetadataName(INamedTypeSymbol type) + { + var name = type.ContainingType != null ? MetadataName(type.ContainingType) + "+" + type.Name : type.Name; + var ns = type.ContainingNamespace; + if (type.ContainingType != null || ns == null || ns.IsGlobalNamespace) + return name; + return ns.ToDisplayString() + "." + name; + } + + static ExpressionSyntax? Expression(TypedConstant constant) + { + if (constant.Type == null || constant.Type.TypeKind == TypeKind.Error || constant.Kind == TypedConstantKind.Error) + return null; + if (constant.IsNull) + return CastExpression(TypeName(constant.Type), LiteralExpression(SyntaxKind.NullLiteralExpression)); + + switch (constant.Kind) + { + case TypedConstantKind.Primitive: + return Primitive(constant.Value, constant.Type); + case TypedConstantKind.Enum: + if (constant.Type is not INamedTypeSymbol enumType || enumType.EnumUnderlyingType == null) + return null; + var literal = Primitive(constant.Value, enumType.EnumUnderlyingType); + if (literal == null) + return null; + return CastExpression(TypeName(enumType), literal is LiteralExpressionSyntax ? literal : ParenthesizedExpression(literal)); + case TypedConstantKind.Type: + return constant.Value is ITypeSymbol type && type.TypeKind != TypeKind.Error + ? TypeOfExpression(TypeName(type)) + : null; + case TypedConstantKind.Array: + return constant.Type is IArrayTypeSymbol array ? Array(array, constant.Values) : null; + default: + return null; + } + } + + static ExpressionSyntax? Array(IArrayTypeSymbol array, ImmutableArray values) + { + var elements = new List(); + foreach (var value in values) + { + if (Expression(value) is not ExpressionSyntax element) + return null; + elements.Add(element); + } + + return ArrayCreationExpression( + ArrayType(TypeName(array.ElementType)).WithRankSpecifiers( + SingletonList(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))), + InitializerExpression(SyntaxKind.ArrayInitializerExpression, SeparatedList(elements))); + } + + static ExpressionSyntax? Primitive(object? value, ITypeSymbol type) + { + if (value == null) + return null; + + switch (type.SpecialType) + { + case SpecialType.System_Boolean: + return LiteralExpression(Convert.ToBoolean(value) ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression); + case SpecialType.System_String: + return LiteralExpression(SyntaxKind.StringLiteralExpression, Literal((string)value)); + case SpecialType.System_Char: + return LiteralExpression(SyntaxKind.CharacterLiteralExpression, Literal(Convert.ToChar(value))); + case SpecialType.System_SByte: + return CastExpression(PredefinedType(Token(SyntaxKind.SByteKeyword)), Number(Convert.ToInt32(value))); + case SpecialType.System_Byte: + return CastExpression(PredefinedType(Token(SyntaxKind.ByteKeyword)), Number(Convert.ToInt32(value))); + case SpecialType.System_Int16: + return CastExpression(PredefinedType(Token(SyntaxKind.ShortKeyword)), Number(Convert.ToInt32(value))); + case SpecialType.System_UInt16: + return CastExpression(PredefinedType(Token(SyntaxKind.UShortKeyword)), Number(Convert.ToInt32(value))); + case SpecialType.System_Int32: + return Number(Convert.ToInt32(value)); + case SpecialType.System_UInt32: + return LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(Convert.ToUInt32(value))); + case SpecialType.System_Int64: + return LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(Convert.ToInt64(value))); + case SpecialType.System_UInt64: + return LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(Convert.ToUInt64(value))); + case SpecialType.System_Single: + var single = Convert.ToSingle(value); + if (float.IsNaN(single)) + return Member(nameof(System.Single), nameof(float.NaN)); + if (float.IsPositiveInfinity(single)) + return Member(nameof(System.Single), nameof(float.PositiveInfinity)); + if (float.IsNegativeInfinity(single)) + return Member(nameof(System.Single), nameof(float.NegativeInfinity)); + return LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(single)); + case SpecialType.System_Double: + var real = Convert.ToDouble(value); + if (double.IsNaN(real)) + return Member(nameof(System.Double), nameof(double.NaN)); + if (double.IsPositiveInfinity(real)) + return Member(nameof(System.Double), nameof(double.PositiveInfinity)); + if (double.IsNegativeInfinity(real)) + return Member(nameof(System.Double), nameof(double.NegativeInfinity)); + return LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(real)); + case SpecialType.System_Decimal: + return LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(Convert.ToDecimal(value))); + default: + return null; + } + } + + static LiteralExpressionSyntax Number(int value) + => LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(value)); + + static ExpressionSyntax Member(string type, string member) + => MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + ParseName("global::System." + type), + IdentifierName(member)); + + static TypeSyntax TypeName(ITypeSymbol type) => ParseTypeName(type.ToDisplayString(TypeFormat)); + } +} diff --git a/src/Stunts.CompiledProxy/Processors/CSharpRewrite.cs b/src/Stunts.CompiledProxy/Processors/CSharpRewrite.cs index b235d156..30d05063 100644 --- a/src/Stunts.CompiledProxy/Processors/CSharpRewrite.cs +++ b/src/Stunts.CompiledProxy/Processors/CSharpRewrite.cs @@ -395,7 +395,8 @@ StatementSyntax InitLocal(ParameterSyntax parameter) => node = node.WithAccessorList(null); - if (canRead && setter == null) + // A get-only property becomes an expression body, which cannot carry accessor attributes. + if (canRead && setter == null && getter?.AttributeLists.Count is not > 0) { var baseCall = GetBaseCall(prop, SyntaxKind.GetAccessorDeclaration); node = node @@ -455,7 +456,7 @@ StatementSyntax InitLocal(ParameterSyntax parameter) => node = node.WithAccessorList(null); - if (canRead && setter == null) + if (canRead && setter == null && getter?.AttributeLists.Count is not > 0) { return node.WithExpressionBody( ArrowExpressionClause( @@ -520,12 +521,8 @@ StatementSyntax InitLocal(ParameterSyntax parameter) => { node = node.WithAccessorList(AccessorList(List(new AccessorDeclarationSyntax[] { - AccessorDeclaration(SyntaxKind.AddAccessorDeclaration) - .WithExpressionBody(ArrowExpressionClause(Execute(null, parameters, defaultAdd))) - .WithSemicolon(), - AccessorDeclaration(SyntaxKind.RemoveAccessorDeclaration) - .WithExpressionBody(ArrowExpressionClause(Execute(null, parameters, defaultRemove))) - .WithSemicolon() + EventAccessor(node.AccessorList, SyntaxKind.AddAccessorDeclaration, ArrowExpressionClause(Execute(null, parameters, defaultAdd))), + EventAccessor(node.AccessorList, SyntaxKind.RemoveAccessorDeclaration, ArrowExpressionClause(Execute(null, parameters, defaultRemove))), }))); } else if (virtualEvents.Contains(node.Identifier.ValueText)) @@ -545,26 +542,16 @@ ArrowExpressionClauseSyntax body(SyntaxKind kind) node = node.WithAccessorList(AccessorList(List(new AccessorDeclarationSyntax[] { - AccessorDeclaration(SyntaxKind.AddAccessorDeclaration) - .WithExpressionBody(add) - .WithSemicolon(), - AccessorDeclaration(SyntaxKind.RemoveAccessorDeclaration) - .WithExpressionBody(remove) - .WithSemicolon() + EventAccessor(node.AccessorList, SyntaxKind.AddAccessorDeclaration, add), + EventAccessor(node.AccessorList, SyntaxKind.RemoveAccessorDeclaration, remove), }))); } else { node = node.WithAccessorList(AccessorList(List(new AccessorDeclarationSyntax[] { - AccessorDeclaration(SyntaxKind.AddAccessorDeclaration) - .WithExpressionBody( - ArrowExpressionClause(CreatePipelineInvocation(null, parameters))) - .WithSemicolon(), - AccessorDeclaration(SyntaxKind.RemoveAccessorDeclaration) - .WithExpressionBody( - ArrowExpressionClause(CreatePipelineInvocation(null, parameters))) - .WithSemicolon() + EventAccessor(node.AccessorList, SyntaxKind.AddAccessorDeclaration, ArrowExpressionClause(CreatePipelineInvocation(null, parameters))), + EventAccessor(node.AccessorList, SyntaxKind.RemoveAccessorDeclaration, ArrowExpressionClause(CreatePipelineInvocation(null, parameters))), }))); } @@ -574,13 +561,25 @@ ArrowExpressionClauseSyntax body(SyntaxKind kind) static AccessorDeclarationSyntax? Accessor(BasePropertyDeclarationSyntax node, params SyntaxKind[] kinds) => node.AccessorList?.Accessors.FirstOrDefault(accessor => kinds.Contains(accessor.Kind())); - // Keeps a narrowed accessor (protected set, internal get) on the override. + // Keeps a narrowed accessor (protected set, internal get) and its attributes on the override. static AccessorDeclarationSyntax WithBody(AccessorDeclarationSyntax accessor, ExpressionSyntax body) => AccessorDeclaration(accessor.Kind()) + .WithAttributeLists(accessor.AttributeLists) .WithModifiers(accessor.Modifiers) .WithExpressionBody(ArrowExpressionClause(body)) .WithSemicolon(); + static AccessorDeclarationSyntax EventAccessor(AccessorListSyntax? list, SyntaxKind kind, ArrowExpressionClauseSyntax body) + { + var accessor = AccessorDeclaration(kind) + .WithExpressionBody(body) + .WithSemicolon(); + var source = list?.Accessors.FirstOrDefault(candidate => candidate.IsKind(kind)); + return source == null || source.AttributeLists.Count == 0 + ? accessor + : accessor.WithAttributeLists(source.AttributeLists); + } + static ElementAccessExpressionSyntax? FixBaseCall(IndexerDeclarationSyntax indexer, ElementAccessExpressionSyntax? baseCall) // Replace base indexer call args with references to pipeline invocation args => baseCall?.WithArgumentList( diff --git a/src/Stunts.CompiledProxy/Processors/MemberScaffold.cs b/src/Stunts.CompiledProxy/Processors/MemberScaffold.cs index f10e0590..607a227c 100644 --- a/src/Stunts.CompiledProxy/Processors/MemberScaffold.cs +++ b/src/Stunts.CompiledProxy/Processors/MemberScaffold.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -47,6 +48,14 @@ public SyntaxNode Process(SyntaxNode syntax, ProcessorContext context) if (model.GetDeclaredSymbol(declaration, context.CancellationToken) is not INamedTypeSymbol symbol) return syntax; + var original = declaration; + if (ProxiedType(declaration, model) is INamedTypeSymbol proxied) + { + var copied = AttributeReplication.Replicate(proxied, AttributeTargets.Class, symbol.ContainingAssembly, includeInherited: false); + if (copied.Count > 0) + declaration = declaration.WithAttributeLists(declaration.AttributeLists.AddRange(copied)); + } + var members = new List(); members.AddRange(Constructors(symbol)); @@ -56,7 +65,7 @@ public SyntaxNode Process(SyntaxNode syntax, ProcessorContext context) if (generated.ContainsKey(ParameterSignature(member))) continue; generated.Add(ParameterSignature(member), member); - members.Add(Stub(member, isOverride: true, explicitInterface: null, stunt: symbol)); + members.Add(Stub(member, isOverride: true, explicitInterface: null, stunt: symbol, assembly: symbol.ContainingAssembly)); } members.AddRange(InterfaceStubs(symbol, generated, context.CancellationToken)); @@ -65,10 +74,19 @@ public SyntaxNode Process(SyntaxNode syntax, ProcessorContext context) { context.DefaultImplementations.Add(provider); var instance = DefaultInstance(context.NamingConvention, provider, member.ContainingType); - members.Add(Stub(member, isOverride: false, explicitInterface: Collides(member, generated), instance, symbol)); + members.Add(Stub(member, false, Collides(member, generated), instance, symbol, symbol.ContainingAssembly)); } - return syntax.ReplaceNode(declaration, declaration.AddMembers(members.ToArray())); + return syntax.ReplaceNode(original, declaration.AddMembers(members.ToArray())); + } + + // The first base is the class, or the primary interface when the stunt has no class base. + static INamedTypeSymbol? ProxiedType(TypeDeclarationSyntax declaration, SemanticModel model) + { + var first = declaration.BaseList?.Types.FirstOrDefault(); + if (first == null) + return null; + return model.GetTypeInfo(first.Type).Type as INamedTypeSymbol; } /// @@ -77,8 +95,9 @@ public SyntaxNode Process(SyntaxNode syntax, ProcessorContext context) /// internal static IEnumerable InterfaceStubs(INamedTypeSymbol symbol, Dictionary generated, CancellationToken cancellationToken) { + var assembly = symbol.ContainingAssembly; foreach (var member in symbol.GetUnimplementedInterfaceMembers(cancellationToken)) - yield return Stub(member, isOverride: false, explicitInterface: Collides(member, generated)); + yield return Stub(member, isOverride: false, explicitInterface: Collides(member, generated), assembly: assembly); } // Same parameters, different return type: IEnumerable.GetEnumerator vs IEnumerable.GetEnumerator. @@ -121,12 +140,13 @@ static IEnumerable Constructors(INamedTypeSymbol s if (!Accessible(constructor, symbol)) continue; - var parameters = constructor.Parameters.Select(Parameter).ToArray(); + var parameters = constructor.Parameters.Select(parameter => Parameter(parameter, symbol.ContainingAssembly)).ToArray(); var initializer = ConstructorInitializer( SyntaxKind.BaseConstructorInitializer, ArgumentList(SeparatedList(constructor.Parameters.Select(ArgumentFor)))); yield return ConstructorDeclaration(symbol.Name) + .WithAttributeLists(AttributeReplication.Replicate(constructor, AttributeTargets.Constructor, symbol.ContainingAssembly, includeInherited: true)) .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))) .WithParameterList(ParameterList(SeparatedList(parameters))) .WithInitializer(initializer) @@ -153,21 +173,24 @@ static bool Accessible(IMethodSymbol constructor, INamedTypeSymbol stunt) // A null receiver throws NotImplementedException. Otherwise, the member proceeds to // base (overrides) or to the default instance (default interface implementations). - static MemberDeclarationSyntax Stub(ISymbol member, bool isOverride, INamedTypeSymbol? explicitInterface, ExpressionSyntax? defaultInstance = null, INamedTypeSymbol? stunt = null) + static MemberDeclarationSyntax Stub(ISymbol member, bool isOverride, INamedTypeSymbol? explicitInterface, ExpressionSyntax? defaultInstance = null, INamedTypeSymbol? stunt = null, IAssemblySymbol? assembly = null) { + assembly ??= stunt?.ContainingAssembly ?? member.ContainingAssembly; var receiver = defaultInstance ?? (isOverride && !member.IsAbstract ? BaseExpression() : null); if (member is IMethodSymbol method) - return Method(method, isOverride, explicitInterface, receiver); + return Method(method, isOverride, explicitInterface, receiver, assembly); if (member is IPropertySymbol property) - return property.IsIndexer ? Indexer(property, isOverride, explicitInterface, receiver, stunt) : Property(property, isOverride, explicitInterface, receiver, stunt); - return Event((IEventSymbol)member, isOverride, explicitInterface, defaultInstance); + return property.IsIndexer ? Indexer(property, isOverride, explicitInterface, receiver, stunt, assembly) : Property(property, isOverride, explicitInterface, receiver, stunt, assembly); + return Event((IEventSymbol)member, isOverride, explicitInterface, defaultInstance, assembly); } - static MethodDeclarationSyntax Method(IMethodSymbol method, bool isOverride, INamedTypeSymbol? explicitInterface, ExpressionSyntax? receiver) + static MethodDeclarationSyntax Method(IMethodSymbol method, bool isOverride, INamedTypeSymbol? explicitInterface, ExpressionSyntax? receiver, IAssemblySymbol assembly) { var declaration = MethodDeclaration(ReturnType(method.ReturnType, method), method.Name) + .WithAttributeLists(AttributeReplication.Replicate(method, AttributeTargets.Method, assembly, includeInherited: false) + .AddRange(AttributeReplication.ReplicateReturn(method, assembly))) .WithModifiers(Modifiers(method, isOverride, explicitInterface != null)) - .WithParameterList(ParameterList(SeparatedList(method.Parameters.Select(Parameter)))) + .WithParameterList(ParameterList(SeparatedList(method.Parameters.Select(parameter => Parameter(parameter, assembly))))) .WithExpressionBody(ArrowExpressionClause(Body(method, receiver))) .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); if (explicitInterface != null) @@ -184,32 +207,37 @@ static MethodDeclarationSyntax Method(IMethodSymbol method, bool isOverride, INa return Annotate(declaration, method.ReturnType); } - static PropertyDeclarationSyntax Property(IPropertySymbol property, bool isOverride, INamedTypeSymbol? explicitInterface, ExpressionSyntax? receiver, INamedTypeSymbol? stunt) + static PropertyDeclarationSyntax Property(IPropertySymbol property, bool isOverride, INamedTypeSymbol? explicitInterface, ExpressionSyntax? receiver, INamedTypeSymbol? stunt, IAssemblySymbol assembly) { var declaration = PropertyDeclaration(ReturnType(property.Type, property.GetMethod), property.Name) + .WithAttributeLists(MemberAttributes(property, property.GetMethod, stunt, assembly)) .WithModifiers(Modifiers(property, isOverride, explicitInterface != null)) - .WithAccessorList(AccessorList(List(Accessors(property, receiver, stunt)))); + .WithAccessorList(AccessorList(List(Accessors(property, receiver, stunt, assembly)))); if (explicitInterface != null) declaration = declaration.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(ParseName(explicitInterface.ToDisplayString(TypeFormat)))); return Annotate(declaration, property.Type); } - static IndexerDeclarationSyntax Indexer(IPropertySymbol property, bool isOverride, INamedTypeSymbol? explicitInterface, ExpressionSyntax? receiver, INamedTypeSymbol? stunt) + static IndexerDeclarationSyntax Indexer(IPropertySymbol property, bool isOverride, INamedTypeSymbol? explicitInterface, ExpressionSyntax? receiver, INamedTypeSymbol? stunt, IAssemblySymbol assembly) { var declaration = IndexerDeclaration(ReturnType(property.Type, property.GetMethod)) + .WithAttributeLists(MemberAttributes(property, property.GetMethod, stunt, assembly)) .WithModifiers(Modifiers(property, isOverride, explicitInterface != null)) - .WithParameterList(BracketedParameterList(SeparatedList(property.Parameters.Select(Parameter)))) - .WithAccessorList(AccessorList(List(Accessors(property, receiver, stunt)))); + .WithParameterList(BracketedParameterList(SeparatedList(property.Parameters.Select(parameter => Parameter(parameter, assembly))))) + .WithAccessorList(AccessorList(List(Accessors(property, receiver, stunt, assembly)))); if (explicitInterface != null) declaration = declaration.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(ParseName(explicitInterface.ToDisplayString(TypeFormat)))); return Annotate(declaration, property.Type); } - static EventDeclarationSyntax Event(IEventSymbol ev, bool isOverride, INamedTypeSymbol? explicitInterface, ExpressionSyntax? defaultInstance) + static EventDeclarationSyntax Event(IEventSymbol ev, bool isOverride, INamedTypeSymbol? explicitInterface, ExpressionSyntax? defaultInstance, IAssemblySymbol assembly) { - AccessorDeclarationSyntax Accessor(SyntaxKind kind, SyntaxKind assignment) + AccessorDeclarationSyntax Accessor(SyntaxKind kind, SyntaxKind assignment, IMethodSymbol? method) { - var accessor = AccessorDeclaration(kind); + var accessor = AccessorDeclaration(kind) + .WithAttributeLists(method == null + ? default + : AttributeReplication.Replicate(method, AttributeTargets.Method, assembly, includeInherited: false)); if (defaultInstance == null) return accessor.WithBody(Block()); @@ -222,18 +250,28 @@ AccessorDeclarationSyntax Accessor(SyntaxKind kind, SyntaxKind assignment) } var declaration = EventDeclaration(TypeName(ev.Type), ev.Name) + .WithAttributeLists(AttributeReplication.Replicate(ev, AttributeTargets.Event, assembly, includeInherited: true)) .WithModifiers(Modifiers(ev, isOverride, explicitInterface != null)) .WithAccessorList(AccessorList(List(new[] { - Accessor(SyntaxKind.AddAccessorDeclaration, SyntaxKind.AddAssignmentExpression), - Accessor(SyntaxKind.RemoveAccessorDeclaration, SyntaxKind.SubtractAssignmentExpression), + Accessor(SyntaxKind.AddAccessorDeclaration, SyntaxKind.AddAssignmentExpression, ev.AddMethod), + Accessor(SyntaxKind.RemoveAccessorDeclaration, SyntaxKind.SubtractAssignmentExpression, ev.RemoveMethod), }))); return explicitInterface == null ? declaration : declaration.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(ParseName(explicitInterface.ToDisplayString(TypeFormat)))); } - static IEnumerable Accessors(IPropertySymbol property, ExpressionSyntax? receiver, INamedTypeSymbol? stunt) + // Property and event attributes are not visible on an override. Accessor methods are. + static SyntaxList MemberAttributes(IPropertySymbol property, IMethodSymbol? getter, INamedTypeSymbol? stunt, IAssemblySymbol assembly) + { + var lists = AttributeReplication.Replicate(property, AttributeTargets.Property, assembly, includeInherited: true); + if (getter != null && OverridableAccessor(getter, stunt)) + lists = lists.AddRange(AttributeReplication.ReplicateReturn(getter, assembly)); + return lists; + } + + static IEnumerable Accessors(IPropertySymbol property, ExpressionSyntax? receiver, INamedTypeSymbol? stunt, IAssemblySymbol assembly) { if (property.GetMethod != null && OverridableAccessor(property.GetMethod, stunt)) { @@ -245,6 +283,7 @@ static IEnumerable Accessors(IPropertySymbol property if (property.GetMethod.ReturnsByRef || property.GetMethod.ReturnsByRefReadonly) value = RefExpression(value); yield return AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) + .WithAttributeLists(AttributeReplication.Replicate(property.GetMethod, AttributeTargets.Method, assembly, includeInherited: false)) .WithModifiers(NarrowedModifiers(property, property.GetMethod)) .WithExpressionBody(ArrowExpressionClause(value)) .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); @@ -260,6 +299,7 @@ static IEnumerable Accessors(IPropertySymbol property IdentifierName("value"))) : ThrowNotImplemented(); yield return AccessorDeclaration(SetterKind(property.SetMethod)) + .WithAttributeLists(AttributeReplication.Replicate(property.SetMethod, AttributeTargets.Method, assembly, includeInherited: false)) .WithModifiers(NarrowedModifiers(property, property.SetMethod)) .WithExpressionBody(ArrowExpressionClause(value)) .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); @@ -389,9 +429,12 @@ static TNode Annotate(TNode node, ITypeSymbol type) where TNode : SyntaxN return node; } - static ParameterSyntax Parameter(IParameterSymbol parameter) + static ParameterSyntax Parameter(IParameterSymbol parameter, IAssemblySymbol assembly) { - var syntax = SyntaxFactory.Parameter(Identifier(parameter.Name)).WithType(TypeName(parameter.Type)); + var syntax = SyntaxFactory.Parameter(Identifier(parameter.Name)) + .WithAttributeLists(AttributeReplication.Replicate(parameter, AttributeTargets.Parameter, assembly, includeInherited: true) + .AddRange(AttributeReplication.Defaults(parameter))) + .WithType(TypeName(parameter.Type)); var modifiers = new List(); switch (parameter.RefKind) { diff --git a/src/Stunts.Package/Stunts.Package.msbuildproj b/src/Stunts.Package/Stunts.Package.msbuildproj index bc166200..15685cc0 100644 --- a/src/Stunts.Package/Stunts.Package.msbuildproj +++ b/src/Stunts.Package/Stunts.Package.msbuildproj @@ -22,7 +22,7 @@ service.AddBehavior(...); - + diff --git a/src/Stunts.UnitTests/ArgumentTests.cs b/src/Stunts.UnitTests/ArgumentTests.cs index 0eeb37bd..c2b5a3e1 100644 --- a/src/Stunts.UnitTests/ArgumentTests.cs +++ b/src/Stunts.UnitTests/ArgumentTests.cs @@ -117,12 +117,6 @@ public void WhenComparingArguments_ThenComparesStructurally() Assert.NotEqual(first, second.WithRawValue(24)); } - - - - - - [Fact] public void WhenTypedValueIsCompatible_ThenRawValueEqualsValue() { diff --git a/src/Stunts.UnitTests/Castle/AttributeTests.cs b/src/Stunts.UnitTests/Castle/AttributeTests.cs new file mode 100644 index 00000000..860db1e0 --- /dev/null +++ b/src/Stunts.UnitTests/Castle/AttributeTests.cs @@ -0,0 +1,307 @@ +using System; +using System.Reflection; +using System.Runtime.InteropServices; +using Xunit; + +namespace Stunts.UnitTests.Castle +{ + /// + /// Attributes that reflection does not inherit onto an override are copied + /// onto the generated stunt. Inheritable type and method attributes are not + /// copied a second time. + /// + public class AttributeTests : IRunnable + { + public void Run() + { + ClassAttributesAndMembers(); + InterfaceGuidAndParameterAttribute(); + OmittedArgumentsArriveAsTheDefault(); + ReflectionInvokeUsesTheCopiedDefault(); + } + + public void ClassAttributesAndMembers() + { + var stunt = Stunt.Of(4); + var type = stunt.GetType(); + + Assert.NotNull(type.GetCustomAttribute()); + Assert.Equal(new Guid("22222222-2222-2222-2222-222222222222"), type.GUID); + Assert.Null(type.GetCustomAttribute(inherit: false)); + Assert.Single(type.GetCustomAttributes(inherit: true)); + + var go = type.GetMethod(nameof(Marked.Go)); + var note = go.GetCustomAttribute(); + Assert.Equal("go", note.Text); + Assert.True(note.Mark); + Assert.Null(go.GetCustomAttribute(inherit: false)); + Assert.Single(go.GetCustomAttributes(inherit: true)); + Assert.Equal("id", go.GetParameters()[0].GetCustomAttribute().Name); + Assert.Equal(2, go.GetParameters()[0].GetCustomAttribute().Count); + Assert.NotNull(go.GetParameters()[1].GetCustomAttribute(inherit: false)); + + var label = type.GetMethod(nameof(Marked.Label)); + Assert.Equal("ret", label.ReturnParameter.GetCustomAttribute().Text); + Assert.Equal("l", stunt.Label()); + + var flag = type.GetMethod(nameof(Marked.Flag)); + Assert.Equal(UnmanagedType.Bool, flag.ReturnParameter.GetCustomAttribute().Value); + Assert.Equal(UnmanagedType.LPWStr, flag.GetParameters()[0].GetCustomAttribute().Value); + + Assert.Equal(5, type.GetMethod(nameof(Marked.Defaulted)).GetParameters()[0].DefaultValue); + Assert.Equal(1.5m, type.GetMethod(nameof(Marked.Price)).GetParameters()[0].DefaultValue); + Assert.Equal("none", type.GetMethod(nameof(Marked.OptionalName)).GetParameters()[0].DefaultValue); + + var meta = type.GetMethod(nameof(Marked.Meta)); + Assert.Equal(Side.Right, meta.GetCustomAttribute().Value); + Assert.Equal(typeof(string), meta.GetCustomAttribute().Type); + Assert.Equal(new[] { 1, 2, 3 }, meta.GetCustomAttribute().Values); + Assert.NotNull(type.GetMethod(nameof(Marked.Generic)).GetCustomAttribute>()); + Assert.NotNull(type.GetMethod(nameof(Marked.Hidden)).GetCustomAttribute()); + + var value = type.GetProperty(nameof(Marked.Value)); + Assert.Equal("value", value.GetCustomAttribute().Text); + Assert.NotNull(value.GetCustomAttribute(inherit: false)); + Assert.Equal("get", value.GetGetMethod().GetCustomAttribute().Text); + Assert.Equal("set", value.GetSetMethod().GetCustomAttribute().Text); + Assert.Equal("name", type.GetProperty(nameof(Marked.Name)).GetGetMethod().GetCustomAttribute().Text); + Assert.Equal("index", type.GetProperty("Item").GetIndexParameters()[0].GetCustomAttribute().Name); + + Assert.Equal("changed", type.GetEvent(nameof(Marked.Changed)).GetCustomAttribute().Text); + var happened = type.GetEvent(nameof(Marked.Happened)); + Assert.Equal("add", happened.AddMethod.GetCustomAttribute().Text); + Assert.Equal("remove", happened.RemoveMethod.GetCustomAttribute().Text); + + Assert.Equal("ctor", type.GetConstructor(new[] { typeof(int) }).GetCustomAttribute().Text); + Assert.Equal("seed", type.GetConstructor(new[] { typeof(int) }).GetParameters()[0].GetCustomAttribute().Name); + Assert.Equal(4, stunt.Seed); + } + + public void OmittedArgumentsArriveAsTheDefault() + { + int number = 0; + decimal amount = 0; + string label = null; + var marked = Stunt.Of(0).AddBehavior((invocation, next) => + { + switch (invocation.MethodBase.Name) + { + case nameof(Marked.Defaulted): + number = invocation.Arguments.Get("value"); + break; + case nameof(Marked.Price): + amount = invocation.Arguments.Get("value"); + break; + case nameof(Marked.OptionalName): + label = invocation.Arguments.Get("value"); + break; + } + + return next(invocation, next); + }); + + Assert.Equal(5, marked.Defaulted()); + Assert.Equal(5, number); + Assert.Equal(1.5m, marked.Price()); + Assert.Equal(1.5m, amount); + Assert.Equal("none", marked.OptionalName()); + Assert.Equal("none", label); + + Assert.Equal(9, marked.Defaulted(9)); + Assert.Equal(9, number); + + int echo = 0; + string text = null; + var optional = Stunt.Of().AddBehavior((invocation, next) => + { + echo = invocation.Arguments.Get("value"); + text = invocation.Arguments.Get("text"); + return invocation.CreateValueReturn(echo + text); + }); + + Assert.Equal("7hi", optional.Echo()); + Assert.Equal(7, echo); + Assert.Equal("hi", text); + + Assert.Equal("7other", optional.Echo(text: "other")); + Assert.Equal("other", text); + } + + public void ReflectionInvokeUsesTheCopiedDefault() + { + var marked = Stunt.Of(0); + var markedType = marked.GetType(); + + Assert.Equal(5, InvokeOptional(markedType.GetMethod(nameof(Marked.Defaulted)), marked, Type.Missing)); + Assert.Equal(1.5m, InvokeOptional(markedType.GetMethod(nameof(Marked.Price)), marked, Type.Missing)); + Assert.Equal("none", InvokeOptional(markedType.GetMethod(nameof(Marked.OptionalName)), marked, Type.Missing)); + + var optional = Stunt.Of().AddBehavior((invocation, next) => + invocation.CreateValueReturn(invocation.Arguments.Get("value") + invocation.Arguments.Get("text"))); + var echo = optional.GetType().GetMethod(nameof(IOptional.Echo)); + + Assert.Equal("7hi", InvokeOptional(echo, optional, Type.Missing, Type.Missing)); + Assert.Equal("7other", InvokeOptional(echo, optional, Type.Missing, "other")); + } + + static object InvokeOptional(MethodInfo method, object instance, params object[] arguments) + => method.Invoke( + instance, + BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.OptionalParamBinding, + null, + arguments, + null); + + public void InterfaceGuidAndParameterAttribute() + { + var stunt = Stunt.Of(); + var type = stunt.GetType(); + + Assert.Equal(new Guid("11111111-1111-1111-1111-111111111111"), type.GUID); + + var run = type.GetMethod(nameof(IMarked.Run)); + Assert.Equal("iface", run.GetCustomAttribute().Text); + Assert.Equal("n", run.GetParameters()[0].GetCustomAttribute().Name); + } + + [Serializable] + [Guid("22222222-2222-2222-2222-222222222222")] + [InheritedMarker] + public class Marked + { + [Note("ctor")] + public Marked([Tag("seed")] int seed) => Seed = seed; + + public int Seed { get; } + + [Note("go", Mark = true)] + [InheritedMarker] + public virtual void Go([Tag("id", Count = 2)] int id, [InheritedMarker] string name) { } + + [return: Note("ret")] + public virtual string Label() => "l"; + + [return: MarshalAs(UnmanagedType.Bool)] + public virtual bool Flag([MarshalAs(UnmanagedType.LPWStr)] string text) => text.Length > 0; + + public virtual int Defaulted(int value = 5) => value; + + public virtual decimal Price(decimal value = 1.5m) => value; + + public virtual string OptionalName(string value = "none") => value; + + [Kind(Side.Right)] + [TypeMark(typeof(string))] + [Numbers(new[] { 1, 2, 3 })] + public virtual void Meta() { } + + [GenericMark] + public virtual void Generic() { } + + [InternalNote] + public virtual void Hidden() { } + + [Note("value")] + [InheritedMarker] + public virtual int Value + { + [Note("get")] + get => 0; + [Note("set")] + set { } + } + + public virtual string Name + { + [Note("name")] + get => "x"; + } + + public virtual int this[[Tag("index")] int index] => index; + + [Note("changed")] + public virtual event EventHandler Changed; + + public virtual event EventHandler Happened + { + [Note("add")] + add { } + [Note("remove")] + remove { } + } + + public void Raise() => Changed?.Invoke(this, EventArgs.Empty); + } + + public interface IOptional + { + string Echo(int value = 7, string text = "hi"); + } + + [Guid("11111111-1111-1111-1111-111111111111")] + public interface IMarked + { + [Note("iface")] + void Run([Tag("n")] int n); + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, Inherited = true, AllowMultiple = true)] + public sealed class InheritedMarkerAttribute : Attribute { } + + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Event | AttributeTargets.Constructor, Inherited = false)] + public sealed class NoteAttribute : Attribute + { + public NoteAttribute(string text) => Text = text; + + public string Text { get; } + + public bool Mark { get; set; } + } + + [AttributeUsage(AttributeTargets.Parameter, Inherited = true)] + public sealed class TagAttribute : Attribute + { + public TagAttribute(string name) => Name = name; + + public string Name { get; } + + public int Count { get; set; } + } + + [AttributeUsage(AttributeTargets.Method, Inherited = false)] + public sealed class KindAttribute : Attribute + { + public KindAttribute(Side value) => Value = value; + + public Side Value { get; } + } + + [AttributeUsage(AttributeTargets.Method, Inherited = false)] + public sealed class TypeMarkAttribute : Attribute + { + public TypeMarkAttribute(Type type) => Type = type; + + public Type Type { get; } + } + + [AttributeUsage(AttributeTargets.Method, Inherited = false)] + public sealed class NumbersAttribute : Attribute + { + public NumbersAttribute(int[] values) => Values = values; + + public int[] Values { get; } + } + + [AttributeUsage(AttributeTargets.Method, Inherited = false)] + public sealed class GenericMarkAttribute : Attribute { } + + [AttributeUsage(AttributeTargets.Method, Inherited = false)] + internal sealed class InternalNoteAttribute : Attribute { } + + public enum Side + { + Left = 1, + Right = 2, + } + } +}