public async Task SkipLocalsInitNotAddedWhenDefinedAtClassLevel()
        {
            string      source = @"
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
[SkipLocalsInit]
partial class C
{
    [GeneratedDllImportAttribute(""DoesNotExist"")]
    public static partial S Method();
}

[NativeMarshalling(typeof(Native))]
struct S
{
}

struct Native
{
    public Native(S s) { }
    public S ToManaged() { return default; }
}";
            Compilation comp   = await TestUtils.CreateCompilation(source);

            Compilation newComp = TestUtils.RunGenerators(comp, out _, new Microsoft.Interop.DllImportGenerator());

            ITypeSymbol   c          = newComp.GetTypeByMetadataName("C") !;
            IMethodSymbol stubMethod = c.GetMembers().OfType <IMethodSymbol>().Single(m => m.Name == "Method");

            Assert.DoesNotContain(stubMethod.GetAttributes(), attr => attr.AttributeClass !.ToDisplayString() == typeof(SkipLocalsInitAttribute).FullName);
        }
 private static bool UsageAttributesAllowProperties(IMethodSymbol method) =>
 method.GetAttributes()
 .Select(attribute => attribute.AttributeClass)
 .SelectMany(cls => cls.GetAttributes(KnownType.System_AttributeUsageAttribute))
 .Select(attr => attr.ConstructorArguments[0].Value)
 .Cast <AttributeTargets>()
 .All(targets => targets.HasFlag(AttributeTargets.Property));
Example #3
0
 private static KnownType ToKnownTestType(IMethodSymbol method)
 {
     return(method.GetAttributes()
            .Select(
                attribute =>
     {
         if (attribute.AttributeClass.Is(KnownType.Microsoft_VisualStudio_TestTools_UnitTesting_TestMethodAttribute))
         {
             return KnownType.Microsoft_VisualStudio_TestTools_UnitTesting_TestMethodAttribute;
         }
         else if (attribute.AttributeClass.Is(KnownType.NUnit_Framework_TestAttribute))
         {
             return KnownType.NUnit_Framework_TestAttribute;
         }
         else if (attribute.AttributeClass.Is(KnownType.Xunit_FactAttribute))
         {
             return KnownType.Xunit_FactAttribute;
         }
         else
         {
             return null;
         }
     })
            .FirstOrDefault());
 }
Example #4
0
            public void AnalyzeSymbol(SymbolAnalysisContext context)
            {
                switch (context.Symbol.Kind)
                {
                case SymbolKind.NamedType:
                    // Check if the symbol implements "_secureTypeInterfaceType".
                    INamedTypeSymbol namedType = (INamedTypeSymbol)context.Symbol;
                    if (namedType.AllInterfaces.Contains(_secureTypeInterfaceType))
                    {
                        lock (_secureTypes)
                        {
                            _secureTypes.Add(namedType);
                        }
                    }

                    break;

                case SymbolKind.Method:
                    // Check if this is an interface method with "_unsecureMethodAttributeType" attribute.
                    IMethodSymbol method = (IMethodSymbol)context.Symbol;
                    if (method.ContainingType.TypeKind == TypeKind.Interface &&
                        method.GetAttributes().Any(a => a.AttributeClass.Equals(_unsecureMethodAttributeType)))
                    {
                        lock (_interfacesWithUnsecureMethods)
                        {
                            _interfacesWithUnsecureMethods.Add(method.ContainingType);
                        }
                    }

                    break;
                }
            }
        public static IMethodSymbol RenameTypeParameters(this IMethodSymbol method, IList<string> newNames)
        {
            if (method.TypeParameters.Select(t => t.Name).SequenceEqual(newNames))
            {
                return method;
            }

            var typeGenerator = new TypeGenerator();
            var updatedTypeParameters = RenameTypeParameters(
                method.TypeParameters, newNames, typeGenerator);

            // The use of AllNullabilityIgnoringSymbolComparer is tracked by https://github.com/dotnet/roslyn/issues/36093
            var mapping = new Dictionary<ITypeSymbol, ITypeSymbol>(AllNullabilityIgnoringSymbolComparer.Instance);
            for (int i = 0; i < method.TypeParameters.Length; i++)
            {
                mapping[method.TypeParameters[i]] = updatedTypeParameters[i];
            }

            return CodeGenerationSymbolFactory.CreateMethodSymbol(
                method.ContainingType,
                method.GetAttributes(),
                method.DeclaredAccessibility,
                method.GetSymbolModifiers(),
                method.ReturnType.SubstituteTypes(mapping, typeGenerator),
                method.RefKind,
                method.ExplicitInterfaceImplementations,
                method.Name,
                updatedTypeParameters,
                method.Parameters.SelectAsArray(p =>
                    CodeGenerationSymbolFactory.CreateParameterSymbol(p.GetAttributes(), p.RefKind, p.IsParams, p.Type.SubstituteTypes(mapping, typeGenerator), p.Name, p.IsOptional,
                        p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)));
        }
Example #6
0
 public override void VisitMethod(IMethodSymbol symbol)
 {
     if (symbol.GetAttributes().Any(x => TestAttributes.Contains(x.AttributeClass.MetadataName)))
     {
         Methods.Enqueue(symbol);
     }
 }
Example #7
0
        internal static AnalysisResult IsMatch(IMethodSymbol method, SemanticModel semanticModel, CancellationToken cancellationToken, PooledSet <IMethodSymbol>?visited = null)
        {
            if (visited?.Add(method) == false)
            {
                return(AnalysisResult.No);
            }

            if (!IsPotentialMatch(method, semanticModel.Compilation))
            {
                return(AnalysisResult.No);
            }

            // not using known symbol here as both jetbrains & mvvm cross defines a NotifyPropertyChangedInvocatorAttribute
            if (method.GetAttributes().TryFirst(x => x.AttributeClass.Name == "NotifyPropertyChangedInvocatorAttribute", out _))
            {
                return(AnalysisResult.Yes);
            }

            var result = AnalysisResult.No;

            if (method.Parameters.TrySingle(out var parameter) &&
                method.TrySingleDeclaration(cancellationToken, out MethodDeclarationSyntax? declaration))
            {
                using var walker = InvocationWalker.Borrow(declaration);
                foreach (var invocation in walker.Invocations)
                {
                    if (invocation is { ArgumentList: { Arguments: { Count: 2 } oneArg } } &&
Example #8
0
        private static IMethodSymbol GetMethodFromConventionMethodAttribute(ApiControllerSymbolCache symbolCache, IMethodSymbol method)
        {
            var attribute = method.GetAttributes(symbolCache.ApiConventionMethodAttribute, inherit: true)
                            .FirstOrDefault();

            if (attribute == null)
            {
                return(null);
            }

            if (attribute.ConstructorArguments.Length != 2)
            {
                return(null);
            }

            if (attribute.ConstructorArguments[0].Kind != TypedConstantKind.Type ||
                !(attribute.ConstructorArguments[0].Value is ITypeSymbol conventionType))
            {
                return(null);
            }

            if (attribute.ConstructorArguments[1].Kind != TypedConstantKind.Primitive ||
                !(attribute.ConstructorArguments[1].Value is string conventionMethodName))
            {
                return(null);
            }

            var conventionMethod = conventionType.GetMembers(conventionMethodName)
                                   .FirstOrDefault(m => m.Kind == SymbolKind.Method && m.IsStatic && m.DeclaredAccessibility == Accessibility.Public);

            return((IMethodSymbol)conventionMethod);
        }
Example #9
0
        private static OperatorDeclarationSyntax GenerateOperatorDeclarationWorker(
            IMethodSymbol method,
            CodeGenerationDestination destination,
            CSharpCodeGenerationContextInfo info)
        {
            var hasNoBody = !info.Context.GenerateMethodBodies || method.IsExtern || method.IsAbstract;

            var operatorSyntaxKind = SyntaxFacts.GetOperatorKind(method.MetadataName);

            if (operatorSyntaxKind == SyntaxKind.None)
            {
                throw new ArgumentException(string.Format(WorkspacesResources.Cannot_generate_code_for_unsupported_operator_0, method.Name), nameof(method));
            }

            var operatorToken = SyntaxFactory.Token(operatorSyntaxKind);
            var checkedToken  = SyntaxFacts.IsCheckedOperator(method.MetadataName)
                ? SyntaxFactory.Token(SyntaxKind.CheckedKeyword)
                : default;

            var operatorDecl = SyntaxFactory.OperatorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), info),
                modifiers: GenerateModifiers(method, destination, hasNoBody),
                returnType: method.ReturnType.GenerateTypeSyntax(),
                explicitInterfaceSpecifier: GenerateExplicitInterfaceSpecifier(method.ExplicitInterfaceImplementations),
                operatorKeyword: SyntaxFactory.Token(SyntaxKind.OperatorKeyword),
                checkedKeyword: checkedToken,
                operatorToken: operatorToken,
                parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, info: info),
                body: hasNoBody ? null : StatementGenerator.GenerateBlock(method),
                expressionBody: null,
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken());

            operatorDecl = UseExpressionBodyIfDesired(info, operatorDecl);
            return(operatorDecl);
        }
Example #10
0
 public bool?SearchForMethodReferences(IMethodSymbol methodSymbol)
 {
     return(methodSymbol.GetAttributes()
            .Any(o => MethodTestAttributes.Contains(o.AttributeClass.ToString()))
                         ? false
                         : (bool?)null);
 }
Example #11
0
 public bool?RequiresCancellationToken(IMethodSymbol methodSymbol)
 {
     return(methodSymbol.GetAttributes()
            .Any(o => MethodTestAttributes.Contains(o.AttributeClass.ToString()))
                         ? false
                         : (bool?)null);
 }
Example #12
0
 public bool?PreserveReturnType(IMethodSymbol methodSymbol)
 {
     return(methodSymbol.GetAttributes()
            .Any(o => MethodTestAttributes.Contains(o.AttributeClass.ToString()))
                         ? true
                         : (bool?)null);
 }
Example #13
0
        private void AnalyzeSymbol(SymbolAnalysisContext context)
        {
            IMethodSymbol method = (IMethodSymbol)context.Symbol;

            if (method.MethodKind == MethodKind.PropertySet || method.MethodKind == MethodKind.PropertyGet)
            {
                return;
            }

            if (method.Name[0].IsUpper() == false && method.GetAttributes().Any(a => a.AttributeClass.Name == "SpecialName") == false)
            {
                // 此处判断不准确,应当用typeof判断
                if (method.Parameters.Length == 2 &&
                    method.DeclaredAccessibility != Accessibility.Public &&
                    method.Parameters[0].Type.Name == "Object" && method.Parameters[0].Name == "sender" &&
                    method.Parameters[1].Type.Name == "EventArgs" && method.Parameters[1].Name == "e")
                {
                    // 这是标准的事件订阅代码,而且还是IDE自动生成的,因此先允许这种代码。
                }
                else
                {
                    Diagnostic diagnostic = Diagnostic.Create(Rule, method.Locations[0], method.Name);
                    context.ReportDiagnostic(diagnostic);
                }
            }
        }
 private static bool MarkedWithStringFormatMethodAttribute(IMethodSymbol method)
 {
     return 
         method.GetAttributes()
         .Select(a => a.AttributeClass.FullName())
         .Any(a => a == "JetBrains.Annotations.StringFormatMethodAttribute");
 }
Example #15
0
        private static OperatorDeclarationSyntax GenerateOperatorDeclarationWorker(
            IMethodSymbol method,
            CodeGenerationDestination destination,
            CodeGenerationOptions options)
        {
            var hasNoBody = !options.GenerateMethodBodies || method.IsExtern;

            var operatorSyntaxKind = SyntaxFacts.GetOperatorKind(method.MetadataName);
            if (operatorSyntaxKind == SyntaxKind.None)
            {
                throw new ArgumentException(string.Format(WorkspacesResources.Cannot_generate_code_for_unsupported_operator_0, method.Name), nameof(method));
            }

            var operatorToken = SyntaxFactory.Token(operatorSyntaxKind);

            return SyntaxFactory.OperatorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options),
                modifiers: GenerateModifiers(method),
                returnType: method.ReturnType.GenerateTypeSyntax(),
                operatorKeyword: SyntaxFactory.Token(SyntaxKind.OperatorKeyword),
                operatorToken: operatorToken,
                parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options: options),
                body: hasNoBody ? null : StatementGenerator.GenerateBlock(method),
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken());
        }
        internal static DestructorDeclarationSyntax GenerateDestructorDeclaration(
            IMethodSymbol destructor, CodeGenerationDestination destination, CodeGenerationOptions options)
        {
            options = options ?? CodeGenerationOptions.Default;

            var reusableSyntax = GetReuseableSyntaxNodeForSymbol <DestructorDeclarationSyntax>(destructor, options);

            if (reusableSyntax != null)
            {
                return(reusableSyntax);
            }

            bool hasNoBody = !options.GenerateMethodBodies;

            var declaration = SyntaxFactory.DestructorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(destructor.GetAttributes(), options),
                modifiers: default(SyntaxTokenList),
                tildeToken: SyntaxFactory.Token(SyntaxKind.TildeToken),
                identifier: CodeGenerationDestructorInfo.GetTypeName(destructor).ToIdentifierToken(),
                parameterList: SyntaxFactory.ParameterList(),
                body: hasNoBody ? null : GenerateBlock(destructor),
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default(SyntaxToken));

            return(AddCleanupAnnotationsTo(
                       ConditionallyAddDocumentationCommentTo(declaration, destructor, options)));
        }
 public AbiMethod(IMethodSymbol symbol)
     : base(symbol, symbol.GetDisplayName(true), symbol.Parameters.Select(p => p.ToAbiParameter()).ToArray())
 {
     Symbol     = symbol;
     Safe       = symbol.GetAttributes().Any(p => p.AttributeClass !.Name == nameof(scfx::Neo.SmartContract.Framework.SafeAttribute));
     ReturnType = symbol.ReturnType.GetContractParameterType();
 }
Example #18
0
        public async Task GeneratedCodeAdded()
        {
            string      source = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly:DisableRuntimeMarshalling]
partial class C
{
    [LibraryImportAttribute(""DoesNotExist"")]
    public static partial S Method();
}

[NativeMarshalling(typeof(Native))]
struct S
{
}

[CustomTypeMarshaller(typeof(S))]
struct Native
{
    public Native(S s) { }
    public S ToManaged() { return default; }
}";
            Compilation comp   = await TestUtils.CreateCompilation(source);

            Compilation newComp = TestUtils.RunGenerators(comp, out _, new Microsoft.Interop.LibraryImportGenerator());

            ITypeSymbol   c          = newComp.GetTypeByMetadataName("C") !;
            IMethodSymbol stubMethod = c.GetMembers().OfType <IMethodSymbol>().Single(m => m.Name == "Method");

            Assert.Contains(stubMethod.GetAttributes(), attr => attr.AttributeClass !.ToDisplayString() == typeof(System.CodeDom.Compiler.GeneratedCodeAttribute).FullName);
        }
Example #19
0
        public static IMethodSymbol RenameParameters(
            this IMethodSymbol method,
            ImmutableArray <string> parameterNames
            )
        {
            var parameterList = method.Parameters;

            if (parameterList.Select(p => p.Name).SequenceEqual(parameterNames))
            {
                return(method);
            }

            var parameters = parameterList.RenameParameters(parameterNames);

            return(CodeGenerationSymbolFactory.CreateMethodSymbol(
                       method.ContainingType,
                       method.GetAttributes(),
                       method.DeclaredAccessibility,
                       method.GetSymbolModifiers(),
                       method.ReturnType,
                       method.RefKind,
                       method.ExplicitInterfaceImplementations,
                       method.Name,
                       method.TypeParameters,
                       parameters
                       ));
        }
 private static bool MethodCanBeSafelyChanged(IMethodSymbol methodSymbol)
 {
     return(methodSymbol.DeclaredAccessibility == Accessibility.Private &&
            !methodSymbol.GetAttributes().Any() &&
            methodSymbol.IsChangeable() &&
            !methodSymbol.IsProbablyEventHandler());
 }
Example #21
0
 public bool?AlwaysAwait(IMethodSymbol methodSymbol)
 {
     return(methodSymbol.GetAttributes()
            .Any(o => MethodTestAttributes.Contains(o.AttributeClass.ToString()))
                         ? true
                         : (bool?)null);
 }
Example #22
0
        private static bool ShouldHaveAsyncInTheEnd(IMethodSymbol methodSymbol)
        {
            var interfaces = methodSymbol.ContainingType.Interfaces;

            foreach (var item in interfaces)
            {
                if (item.MemberNames.Contains(methodSymbol.Name))
                {
                    return(false);
                }
            }

            var methodAttributes = methodSymbol.GetAttributes();

            foreach (var testMethodAttribute in testMethodAttributes)
            {
                if (methodAttributes.Any(x => x.AttributeClass.Name.StartsWith(testMethodAttribute)))
                {
                    return(false);
                }
            }

            return(IsAwaitable(methodSymbol) &&
                   !methodSymbol.IsOverride &&
                   !methodSymbol.Name.Equals("Main") &&
                   !methodSymbol.Name.Equals("<Main>$") &&
                   !methodSymbol.Name.EndsWith("Async"));
        }
Example #23
0
        private static ConversionOperatorDeclarationSyntax GenerateConversionDeclarationWorker(
            IMethodSymbol method,
            CodeGenerationDestination destination,
            CodeGenerationOptions options)
        {
            var hasNoBody = !options.GenerateMethodBodies || method.IsExtern;

            var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ConversionOperatorDeclarationSyntax>(method, options);
            if (reusableSyntax != null)
            {
                return reusableSyntax;
            }

            var operatorToken = SyntaxFactory.Token(SyntaxFacts.GetOperatorKind(method.MetadataName));
            var keyword = method.MetadataName == WellKnownMemberNames.ImplicitConversionName
                ? SyntaxFactory.Token(SyntaxKind.ImplicitKeyword)
                : SyntaxFactory.Token(SyntaxKind.ExplicitKeyword);

            return SyntaxFactory.ConversionOperatorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options),
                modifiers: GenerateModifiers(method),
                implicitOrExplicitKeyword: keyword,
                operatorKeyword: SyntaxFactory.Token(SyntaxKind.OperatorKeyword),
                type: method.ReturnType.GenerateTypeSyntax(),
                parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options: options),
                body: hasNoBody ? null : StatementGenerator.GenerateBlock(method),
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken());
        }
Example #24
0
        public override HashSet <ISymbol> GetAnalyzableSymbols(SymbolAnalysisContext context, INamedTypeSymbol containingType)
        {
            HashSet <ISymbol> properties = null;

            ImmutableArray <ISymbol> members = containingType.GetMembers();

            for (int i = 0; i < members.Length; i++)
            {
                if (members[i].Kind == SymbolKind.Property)
                {
                    var propertySymbol = (IPropertySymbol)members[i];

                    if (!propertySymbol.IsIndexer &&
                        !propertySymbol.IsReadOnly &&
                        !propertySymbol.IsImplicitlyDeclared &&
                        propertySymbol.ExplicitInterfaceImplementations.IsDefaultOrEmpty &&
                        !propertySymbol.HasAttribute(context.GetTypeByMetadataName(MetadataNames.System_Runtime_Serialization_DataMemberAttribute)))
                    {
                        IMethodSymbol setMethod = propertySymbol.SetMethod;

                        if (setMethod?.DeclaredAccessibility == Accessibility.Private &&
                            setMethod.GetAttributes().IsEmpty &&
                            setMethod.GetSyntaxOrDefault(context.CancellationToken) is AccessorDeclarationSyntax accessor &&
                            accessor.BodyOrExpressionBody() == null)
                        {
                            (properties ?? (properties = new HashSet <ISymbol>())).Add(propertySymbol);
                        }
                    }
                }
            }

            return(properties);
        }
Example #25
0
        internal static ConstructorDeclarationSyntax GenerateConstructorDeclaration(
            IMethodSymbol constructor, CodeGenerationDestination destination, CodeGenerationOptions options)
        {
            options = options ?? CodeGenerationOptions.Default;

            var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ConstructorDeclarationSyntax>(constructor, options);
            if (reusableSyntax != null)
            {
                return reusableSyntax;
            }

            bool hasNoBody = !options.GenerateMethodBodies;

            var declaration = SyntaxFactory.ConstructorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(constructor.GetAttributes(), options),
                modifiers: GenerateModifiers(constructor, options),
                identifier: CodeGenerationConstructorInfo.GetTypeName(constructor).ToIdentifierToken(),
                parameterList: ParameterGenerator.GenerateParameterList(constructor.Parameters, isExplicit: false, options: options),
                initializer: GenerateConstructorInitializer(constructor),
                body: hasNoBody ? null : GenerateBlock(constructor),
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default(SyntaxToken));

            return AddCleanupAnnotationsTo(
                ConditionallyAddDocumentationCommentTo(declaration, constructor, options));
        }
Example #26
0
        private static OperatorDeclarationSyntax GenerateOperatorDeclarationWorker(
            IMethodSymbol method,
            CodeGenerationDestination destination,
            CodeGenerationOptions options)
        {
            var hasNoBody = !options.GenerateMethodBodies || method.IsExtern;

            var operatorSyntaxKind = SyntaxFacts.GetOperatorKind(method.MetadataName);

            if (operatorSyntaxKind == SyntaxKind.None)
            {
                throw new ArgumentException(string.Format(WorkspacesResources.Cannot_generate_code_for_unsupported_operator_0, method.Name), nameof(method));
            }

            var operatorToken = SyntaxFactory.Token(operatorSyntaxKind);

            return(SyntaxFactory.OperatorDeclaration(
                       attributeLists: AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options),
                       modifiers: GenerateModifiers(method),
                       returnType: method.ReturnType.GenerateTypeSyntax(),
                       operatorKeyword: SyntaxFactory.Token(SyntaxKind.OperatorKeyword),
                       operatorToken: operatorToken,
                       parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options: options),
                       body: hasNoBody ? null : StatementGenerator.GenerateBlock(method),
                       semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken()));
        }
Example #27
0
        private static ConversionOperatorDeclarationSyntax GenerateConversionDeclarationWorker(
            IMethodSymbol method,
            CodeGenerationDestination destination,
            Workspace workspace,
            CodeGenerationOptions options,
            ParseOptions parseOptions)
        {
            var hasNoBody = !options.GenerateMethodBodies || method.IsExtern;

            var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ConversionOperatorDeclarationSyntax>(method, options);
            if (reusableSyntax != null)
            {
                return reusableSyntax;
            }

            var operatorToken = SyntaxFactory.Token(SyntaxFacts.GetOperatorKind(method.MetadataName));
            var keyword = method.MetadataName == WellKnownMemberNames.ImplicitConversionName
                ? SyntaxFactory.Token(SyntaxKind.ImplicitKeyword)
                : SyntaxFactory.Token(SyntaxKind.ExplicitKeyword);

            var declaration = SyntaxFactory.ConversionOperatorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options),
                modifiers: GenerateModifiers(method),
                implicitOrExplicitKeyword: keyword,
                operatorKeyword: SyntaxFactory.Token(SyntaxKind.OperatorKeyword),
                type: method.ReturnType.GenerateTypeSyntax(),
                parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options: options),
                body: hasNoBody ? null : StatementGenerator.GenerateBlock(method),
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken());

            declaration = UseExpressionBodyIfDesired(workspace, declaration, parseOptions);

            return declaration;
        }
Example #28
0
        public static IMethodSymbol RenameTypeParameters(this IMethodSymbol method, IList <string> newNames)
        {
            if (method.TypeParameters.Select(t => t.Name).SequenceEqual(newNames))
            {
                return(method);
            }

            var typeGenerator         = new TypeGenerator();
            var updatedTypeParameters = RenameTypeParameters(
                method.TypeParameters, newNames, typeGenerator);

            var mapping = new Dictionary <ITypeSymbol, ITypeSymbol>();

            for (int i = 0; i < method.TypeParameters.Length; i++)
            {
                mapping[method.TypeParameters[i]] = updatedTypeParameters[i];
            }

            return(CodeGenerationSymbolFactory.CreateMethodSymbol(
                       method.ContainingType,
                       method.GetAttributes(),
                       method.DeclaredAccessibility,
                       method.GetSymbolModifiers(),
                       method.ReturnType.SubstituteTypes(mapping, typeGenerator),
                       method.ReturnsByRef,
                       method.ExplicitInterfaceImplementations,
                       method.Name,
                       updatedTypeParameters,
                       method.Parameters.SelectAsArray(p =>
                                                       CodeGenerationSymbolFactory.CreateParameterSymbol(p.GetAttributes(), p.RefKind, p.IsParams, p.Type.SubstituteTypes(mapping, typeGenerator), p.Name, p.IsOptional,
                                                                                                         p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null))));
        }
        internal static ConstructorDeclarationSyntax GenerateConstructorDeclaration(
            IMethodSymbol constructor, CodeGenerationDestination destination,
            Workspace workspace, CodeGenerationOptions options, ParseOptions parseOptions)
        {
            options = options ?? CodeGenerationOptions.Default;

            var reusableSyntax = GetReuseableSyntaxNodeForSymbol <ConstructorDeclarationSyntax>(constructor, options);

            if (reusableSyntax != null)
            {
                return(reusableSyntax);
            }

            bool hasNoBody = !options.GenerateMethodBodies;

            var declaration = SyntaxFactory.ConstructorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(constructor.GetAttributes(), options),
                modifiers: GenerateModifiers(constructor, options),
                identifier: CodeGenerationConstructorInfo.GetTypeName(constructor).ToIdentifierToken(),
                parameterList: ParameterGenerator.GenerateParameterList(constructor.Parameters, isExplicit: false, options: options),
                initializer: GenerateConstructorInitializer(constructor),
                body: hasNoBody ? null : GenerateBlock(constructor),
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default(SyntaxToken));

            declaration = UseExpressionBodyIfDesired(workspace, declaration, parseOptions);

            return(AddCleanupAnnotationsTo(
                       ConditionallyAddDocumentationCommentTo(declaration, constructor, options)));
        }
Example #30
0
 private static bool MethodCanBeSafelyChanged(IMethodSymbol methodSymbol)
 {
     return(methodSymbol.GetEffectiveAccessibility() == Accessibility.Private &&
            !methodSymbol.GetAttributes().Any() &&
            methodSymbol.IsChangeable() &&
            !methodSymbol.IsEventHandler());
 }
Example #31
0
 private static bool MarkedWithStringFormatMethodAttribute(IMethodSymbol method)
 {
     return
         (method.GetAttributes()
          .Select(a => a.AttributeClass.FullName())
          .Any(a => a == "JetBrains.Annotations.StringFormatMethodAttribute"));
 }
Example #32
0
        private static bool TryGetOperationContract(IMethodSymbol methodSymbol, out AttributeData attribute)
        {
            attribute = methodSymbol.GetAttributes()
                        .FirstOrDefault(a => a.AttributeClass.Is(KnownType.System_ServiceModel_OperationContractAttribute));

            return(attribute != null);
        }
        private static IReadOnlyList <IMethodSymbol> SearchForTestMethods(INamedTypeSymbol classSymbol)
        {
            List <IMethodSymbol> methods = new List <IMethodSymbol>();

            foreach (ISymbol member in classSymbol.GetMembers())
            {
                IMethodSymbol method = member as IMethodSymbol;
                if (method == null)
                {
                    continue;
                }

                IEnumerable <AttributeData> attributes = method.GetAttributes();
                foreach (AttributeData attribute in attributes)
                {
                    if ("NUnit.Framework.TestAttribute".Equals(attribute.AttributeClass?.ToString()))
                    {
                        methods.Add(method);
                        break;
                    }
                }
            }

            return(methods);
        }
        private bool ContainsHandleProcessCorruptedStateExceptionsAttribute(IMethodSymbol method, CompilationSecurityTypes compilationTypes)
        {
            ImmutableArray <AttributeData> attributes = method.GetAttributes();

            return(attributes.Any(
                       attribute => attribute.AttributeClass.Equals(compilationTypes.HandleProcessCorruptedStateExceptionsAttribute)));
        }
 private static bool MethodCanBeSafelyChanged(IMethodSymbol methodSymbol)
 {
     return methodSymbol.DeclaredAccessibility == Accessibility.Private &&
         !methodSymbol.GetAttributes().Any() &&
         methodSymbol.IsChangeable() &&
         !methodSymbol.IsProbablyEventHandler();
 }
		////		public override string CreateFieldEncapsulation (IUnresolvedTypeDefinition implementingType, IField field, string propertyName, Accessibility modifiers, bool readOnly)
		////		{
		////			SetIndentTo (implementingType);
		////			StringBuilder result = new StringBuilder ();
		////			AppendIndent (result);
		////			
		//////			if (modifiers != MonoDevelop.Projects.Dom.Modifiers.None) {
		//////				switch (modifiers) {
		//////				}
		//////				result.Append (ambience.GetString (modifiers));
		//////				result.Append (" ");
		//////			}
		////			var options = new CodeGenerationOptions () {
		////				ImplementingType = field.DeclaringTypeDefinition,
		////				Part = implementingType
		////			};
		////			result.Append ("public ");
		////			AppendReturnType (result, options, field.ReturnType);
		////			result.Append (" ");
		////			result.Append (propertyName);
		////			AppendBraceStart (result, Policy.PropertyBraceStyle);
		////			AppendIndent (result);
		////			
		////			result.Append ("get");
		////			AppendBraceStart (result, Policy.PropertyGetBraceStyle);
		////			AppendIndent (result);
		////			result.Append ("return this.");
		////			result.Append (CSharpAmbience.FilterName (field.Name));
		////			result.Append (";");
		////			AppendLine (result);
		////			AppendBraceEnd (result, Policy.PropertyGetBraceStyle);
		////			AppendLine (result);
		////
		////			if (!readOnly) {
		////				AppendIndent (result);
		////				result.Append ("set");
		////				AppendBraceStart (result, Policy.PropertyGetBraceStyle);
		////				AppendIndent (result);
		////				result.Append (CSharpAmbience.FilterName (field.Name));
		////				result.Append (" = value;");
		////				AppendLine (result);
		////				AppendBraceEnd (result, Policy.PropertyGetBraceStyle);
		////				AppendLine (result);
		////			}
		////			
		////			AppendBraceEnd (result, Policy.PropertyBraceStyle);
		////			return result.ToString ();
		////		}
		//		
		//		int CountBlankLines (IReadonlyTextDocument doc, int startLine)
		//		{
		//			int result = 0;
		//			IDocumentLine line;
		//			while ((line = doc.GetLine (startLine + result)) != null && doc.GetLineIndent (line).Length == line.Length) {
		//				result++;
		//			}
		//		
		//			return result;
		//		}
		//		
		//		static bool InsertUsingAfter (AstNode node)
		//		{
		//			return node is NewLineNode && IsCommentOrUsing (node.GetNextSibling (s => !(s is NewLineNode))) ||
		//				IsCommentOrUsing (node) || (node is PreProcessorDirective);
		//		}
		//
		//		static bool IsCommentOrUsing (AstNode node)
		//		{
		//			return node is ICSharpCode.NRefactory.CSharp.Comment ||
		//				node is UsingDeclaration ||
		//				node is UsingAliasDeclaration;
		//		}
		//		

		//		
		//		static string OutputNode (TextEditor editor, DocumentContext context, AstNode node)
		//		{
		//			using (var stringWriter = new System.IO.StringWriter ()) {
		////				formatter.Indentation = indentLevel;
		//				var formatter = new TextWriterTokenWriter (stringWriter);
		//				stringWriter.NewLine = editor.EolMarker;
		//
		//				var visitor = new CSharpOutputVisitor (formatter, null /* TODO: BROKEN DUE ROSLYN PORT (note: that code should be unused) */ );
		//				node.AcceptVisitor (visitor);
		//				return stringWriter.ToString ();
		//			}
		//		}
		//		
		//		
		//		public AstType CreateShortType (ICompilation compilation, CSharpUnresolvedFile parsedFile, TextLocation loc, IType fullType)
		//		{
		//			var csResolver = parsedFile.GetResolver (compilation, loc);
		//			var builder = new ICSharpCode.NRefactory.CSharp.Refactoring.TypeSystemAstBuilder (csResolver);
		//			return builder.ConvertType (fullType);			
		//		}
		//		
		//		public override void CompleteStatement (MonoDevelop.Ide.Gui.Document doc)
		//		{
		//			//  TODO: BROKEN DUE ROSLYN PORT - needs to be ported to NR6
		////			var fixer = new ConstructFixer (doc.GetFormattingOptions (), doc.Editor.CreateNRefactoryTextEditorOptions ());
		////			int newOffset;
		////			if (fixer.TryFix (new DocumentWrapper (doc.Editor), doc.Editor.CaretOffset, out newOffset)) {
		////				doc.Editor.CaretOffset = newOffset;
		////			}
		//		}




		static CodeGeneratorMemberResult GenerateProtocolCode(IMethodSymbol method, CodeGenerationOptions options)
		{
			int bodyStartOffset = -1, bodyEndOffset = -1;
			var result = new StringBuilder();
			var exportAttribute = method.GetAttributes ().FirstOrDefault (attr => attr.AttributeClass.Name == "ExportAttribute");
			if (exportAttribute != null) {
				result.Append ("[Export(\"");
				result.Append (exportAttribute.ConstructorArguments.First ().Value.ToString ());
				result.Append ("\")]");
				result.AppendLine ();
			}
			AppendModifiers (result, options, method);

			AppendReturnType (result, options, method.ReturnType);
			result.Append (" ");
			if (options.ExplicitDeclaration) {
				AppendReturnType (result, options, method.ContainingType);
				result.Append(".");
			}

			result.Append(CSharpAmbience.FilterName(method.Name));
			if (method.TypeParameters.Length > 0) {
				result.Append("<");
				for (int i = 0; i < method.TypeParameters.Length; i++) {
					if (i > 0)
						result.Append(", ");
					var p = method.TypeParameters[i];
					result.Append(CSharpAmbience.FilterName(p.Name));
				}
				result.Append(">");
			}
			result.Append("(");
			AppendParameterList (result, options, method.Parameters, true);
			result.Append(")");

			var typeParameters = method.TypeParameters;

			result.Append ("{");
			AppendIndent (result);
			bodyStartOffset = result.Length;
			result.Append ("throw new System.NotImplementedException ();");
			bodyEndOffset = result.Length;
			AppendLine (result);
			result.Append ("}");
			return new CodeGeneratorMemberResult(result.ToString (), bodyStartOffset, bodyEndOffset);
		}
      private TemplateEventMethodInfo TranslateMethodAttributes(IMethodSymbol sourceMethod, EventSourceTypeInfo eventSourceTypeInfo, CollectedGenerationInfo overloads)
      {
         List<SyntaxNode> attributes = new List<SyntaxNode>();

         SyntaxNode eventAttribute = null;
         int? eventId = null;

         foreach (AttributeData attributeData in sourceMethod.GetAttributes())
         {
            var attributeClass = attributeData.AttributeClass;

            if (attributeClass.Name.Equals(TemplateEventAttributeName) || attributeClass.Equals(eventSourceTypeInfo.EventAttributeType))
            {               
               SyntaxNode attributeSyntax = attributeData.ApplicationSyntaxReference?.GetSyntax();
               if (attributeSyntax == null)
                  throw new CodeGeneratorException(sourceMethod, $"Cannot find the source file containing the method {sourceMethod.Name}. The source code must be available for any Template EventSource class to participate in generation. Is the project unloaded?");

               Document attributeDocument = m_document.Project.Solution.GetDocument(attributeSyntax.SyntaxTree);
               if (attributeDocument == null)
                  throw new CodeGeneratorException(sourceMethod, $"Cannot find the document containing the method {sourceMethod.Name}.");

               
               overloads.AddConstants(attributeSyntax, attributeDocument.GetSemanticModelAsync().Result, eventSourceTypeInfo);

               attributeSyntax = m_generator.Attribute(eventSourceTypeInfo.EventAttributeType.GetFullName(), m_generator.GetAttributeArguments(attributeSyntax));
                  
               attributes.Add(attributeSyntax);


               TypedConstant eventIdArgument = attributeData.ConstructorArguments.FirstOrDefault();
               if (attributeData.ConstructorArguments.Length == 0)
                  throw new CodeGeneratorException(sourceMethod, $"The {attributeData.AttributeClass.Name} attribute must have an event ID as its first argument.");

               if (!(eventIdArgument.Value is int))
                  throw new CodeGeneratorException(sourceMethod, $"The first argument to the {attributeData.AttributeClass.Name} attribute must be of type Int32.");

               eventId = (int)eventIdArgument.Value;
               eventAttribute = attributeSyntax;
            }
            else
            {
               attributes.Add(CreateAttribute(attributeData));                  
            }
         }

         if (eventAttribute == null)
            throw new CodeGeneratorException(sourceMethod, $"Internal error; Unable to find EventAttribute or TemplateEventAttribute on method {sourceMethod.Name}");

         if (eventId == null)
            throw new CodeGeneratorException(sourceMethod, $"Unable to determine EventId for method {sourceMethod.Name}");

         return new TemplateEventMethodInfo(attributes, eventId.Value);
      }
Example #38
0
 CommandInfo GetCommandInfo(IMethodSymbol method)
 {
     return method.GetAttributes()
                 .FirstOrDefault(x => x.AttributeClass == asyncCommandAttributeType || x.AttributeClass == commandAttributeType)
                 .With(x => {
                     var args = x.ConstructorArguments.Select(arg => arg.Value).ToArray(); //TODO dup code
                     var namedArgs = x.NamedArguments.ToImmutableDictionary(p => p.Key, p => p.Value.Value); //TODO error if names are not recognizable
                     return new CommandInfo(
                         isCommand: args.Length > 0 ? (bool)args[0] : true,
                         allowMultipleExecution: (bool)namedArgs.GetValueOrDefault("AllowMultipleExecution", false),
                         useCommandManager: (bool)namedArgs.GetValueOrDefault("UseCommandManager", true),
                         name: (string)namedArgs.GetValueOrDefault("Name"),
                         canExecuteMethodName: (string)namedArgs.GetValueOrDefault("CanExecuteMethodName"));
                 });
 }
 private bool ContainsHandleProcessCorruptedStateExceptionsAttribute(IMethodSymbol method, CompilationSecurityTypes compilationTypes)
 {
     ImmutableArray<AttributeData> attributes = method.GetAttributes();
     return attributes.Any(
         attribute => attribute.AttributeClass.Equals(compilationTypes.HandleProcessCorruptedStateExceptionsAttribute));
 }
        private static bool ShouldAnalyze(IMethodSymbol methodSymbol, Compilation compilation)
        {
            // Modifiers that we don't care about
            if (methodSymbol.IsStatic || methodSymbol.IsOverride || methodSymbol.IsVirtual ||
                methodSymbol.IsExtern || methodSymbol.IsAbstract || methodSymbol.IsImplementationOfAnyInterfaceMember())
            {
                return false;
            }

            if (methodSymbol.IsConstructor() || methodSymbol.IsFinalizer())
            {
                return false;
            }
            
            // CA1000 says one shouldn't declare static members on generic types. So don't flag such cases.
            if (methodSymbol.ContainingType.IsGenericType && methodSymbol.GetResultantVisibility() == SymbolVisibility.Public)
            {
                return false;
            }

            // FxCop doesn't check for the fully qualified name for these attributes - so we'll do the same.
            var skipAttributes = new[]
            {
                "WebMethodAttribute",
                "TestInitializeAttribute",
                "TestMethodAttribute",
                "TestCleanupAttribute",
            };

            if (methodSymbol.GetAttributes().Any(attribute => skipAttributes.Contains(attribute.AttributeClass.Name)))
            {
                return false;
            }

            // If this looks like an event handler don't flag such cases.
            if (methodSymbol.Parameters.Length == 2 && 
                methodSymbol.Parameters[0].Type.SpecialType == SpecialType.System_Object &&
                IsEventArgs(methodSymbol.Parameters[1].Type, compilation))
            {
                return false;
            }

            if (IsExplicitlyVisibleFromCom(methodSymbol, compilation))
            {
                return false;
            }

            return true;
        }
        private static bool IsExplicitlyVisibleFromCom(IMethodSymbol methodSymbol, Compilation compilation)
        {
            if (methodSymbol.GetResultantVisibility() != SymbolVisibility.Public || methodSymbol.IsGenericMethod)
            {
                return false;
            }

            var comVisibleAttribute = WellKnownTypes.ComVisibleAttribute(compilation);
            if (comVisibleAttribute == null)
            {
                return false;
            }

            if (methodSymbol.GetAttributes().Any(attribute => attribute.AttributeClass.Equals(comVisibleAttribute)) ||
                methodSymbol.ContainingType.GetAttributes().Any(attribute => attribute.AttributeClass.Equals(comVisibleAttribute)))
            {
                return true;
            }

            return false;
        }
        private static bool TryGetOperationContract(IMethodSymbol methodSymbol, out AttributeData attribute)
        {
            attribute = methodSymbol.GetAttributes()
                .FirstOrDefault(a => a.AttributeClass.Is(KnownType.System_ServiceModel_OperationContractAttribute));

            return attribute != null;
        }
        private static string GetAttributeArgument(IMethodSymbol methodSymbol, string typeName)
        {
            var attribute = methodSymbol.GetAttributes().FirstOrDefault(a => a.ToString().Contains(typeName));
            if (attribute != null)
            {
                return attribute.ConstructorArguments.First().Value.ToString();
            }

            throw new Exception("Unable to retrieve/parse attribute parameters.");
        }
        private static SyntaxList<AttributeListSyntax> GenerateAttributes(
            IMethodSymbol method, CodeGenerationOptions options, bool isExplicit)
        {
            var attributes = new List<AttributeListSyntax>();

            if (!isExplicit)
            {
                attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options));
                attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetReturnTypeAttributes(), options, SyntaxFactory.Token(SyntaxKind.ReturnKeyword)));
            }

            return attributes.ToSyntaxList();
        }
        // TODO: analyze not only with format litteral but with method calls that returns formatted literal!
        private static string GetFormatArgumentName(IMethodSymbol symbol)
        {
            var annotationAttribute = symbol.GetAttributes().FirstOrDefault(a => a.AttributeClass.FullName() == "JetBrains.Annotations.StringFormatMethodAttribute");
            if (annotationAttribute != null)
            {
                var firstArgument = annotationAttribute.ConstructorArguments.FirstOrDefault();
                if (firstArgument.Value != null)
                {
                    return firstArgument.Value.ToString();
                }
            }

            return expectedFormatArgumentName;
        }