public void IsAsyncLibraryConstruct(IMethodSymbol symbol)
        {
            if (symbol.ContainingNamespace.ToString().Equals("System.Threading.Tasks") ||
                symbol.ContainingNamespace.ToString().Equals("System.Threading") ||
                (symbol.ContainingNamespace.ToString().Equals("System.Linq") && (symbol.ContainingType.ToString().Contains("ParallelQuery") || symbol.ContainingType.ToString().Contains("ParallelEnumerable"))) ||
                symbol.ContainingNamespace.ToString().Equals("System.Collections.Concurrent"))
            {

                if (ConsultingAnalysisResult.libraryUsage.ContainsKey(symbol.ToString()))
                    ConsultingAnalysisResult.libraryUsage[symbol.ToString()]++;
                else
                    ConsultingAnalysisResult.libraryUsage[symbol.ToString()] = 1;
            }
        }
        private static void Analyze(SyntaxNodeAnalysisContext context)
        {
            InvocationExpressionSyntax   invocationExpression   = (InvocationExpressionSyntax)context.Node;
            MemberAccessExpressionSyntax memberAccessExpression = invocationExpression.Expression as MemberAccessExpressionSyntax;

            if (memberAccessExpression == null)
            {
                return;
            }

            string memberName = memberAccessExpression.Expression.ToString();
            string name       = memberAccessExpression.Name.ToString();

            Location location;

            if (memberName == @"Thread" && name == @"Sleep")
            {
                ClassDeclarationSyntax           classDeclaration   = (ClassDeclarationSyntax)context.Node.Parent.Parent.Parent.Parent;
                SyntaxList <AttributeListSyntax> classAttributeList = classDeclaration.AttributeLists;
                if (Helper.HasAttribute(classAttributeList, context, MsTestFrameworkDefinitions.TestClassAttribute, out location))
                {
                    IMethodSymbol memberSymbol = context.SemanticModel.GetSymbolInfo(memberAccessExpression).Symbol as IMethodSymbol;
                    if ((memberSymbol != null) && memberSymbol.ToString().StartsWith("System.Threading.Thread"))
                    {
                        Diagnostic diagnostic = Diagnostic.Create(Rule, invocationExpression.GetLocation());
                        context.ReportDiagnostic(diagnostic);
                    }
                }
            }
        }
        public void Analyze(ClassDeclarationSyntax classDeclarationSyntax, ClassModel classModel)
        {
            List <MethodDeclarationSyntax> methodDeclarationSyntaxes = classDeclarationSyntax
                                                                       .DescendantNodes()
                                                                       .OfType <MethodDeclarationSyntax>()
                                                                       .ToList();

            foreach (MethodDeclarationSyntax methodDeclarationSyntax in methodDeclarationSyntaxes)
            {
                MethodModel methodModel = new MethodModel();

                methodModel.Name = methodDeclarationSyntax.Identifier.Text;

                IMethodSymbol methodSymbol = SemanticModel.GetDeclaredSymbol(methodDeclarationSyntax) as IMethodSymbol;

                if (methodSymbol != null && !methodSymbol.IsAbstract)
                {
                    ControlFlowGraph controlFlowGraph = ControlFlowGraph
                                                        .Create(methodDeclarationSyntax, SemanticModel, CancellationToken.None);

                    int numberOfBlocks = controlFlowGraph.Blocks.Length;
                    int numberOfEdges  = 0;

                    foreach (BasicBlock basicBlock in controlFlowGraph.Blocks)
                    {
                        if (basicBlock.ConditionalSuccessor != null)
                        {
                            numberOfEdges++;
                        }

                        if (basicBlock.FallThroughSuccessor != null)
                        {
                            numberOfEdges++;
                        }
                    }

                    methodModel.CyclomaticComplexity = numberOfEdges - numberOfBlocks + 2;
                }

                methodModel.Fqn             = methodSymbol.ToString();
                methodModel.Static          = methodSymbol.IsStatic;
                methodModel.Abstract        = methodSymbol.IsAbstract;
                methodModel.Sealed          = methodSymbol.IsSealed;
                methodModel.Async           = methodSymbol.IsAsync;
                methodModel.Override        = methodSymbol.IsOverride;
                methodModel.Virtual         = methodSymbol.IsVirtual;
                methodModel.Extern          = methodSymbol.IsExtern;
                methodModel.Accessibility   = methodSymbol.DeclaredAccessibility.ToString();
                methodModel.ReturnType      = methodSymbol.ReturnType.ToString();
                methodModel.FirstLineNumber =
                    methodDeclarationSyntax.GetLocation().GetLineSpan().StartLinePosition.Line + 1;
                methodModel.LastLineNumber =
                    methodDeclarationSyntax.GetLocation().GetLineSpan().EndLinePosition.Line + 1;

                _invocationAnalyzer.Analyze(methodDeclarationSyntax, methodModel);
                _parameterAnalyzer.Analyze(methodDeclarationSyntax, methodModel);

                classModel.Methods.Add(methodModel);
            }
        }
Example #4
0
File: Task.cs Project: legigor/Nake
 public Task(IMethodSymbol symbol, bool step)
 {
     CheckSignature(symbol);
     Signature   = symbol.ToString();
     this.symbol = symbol;
     this.step   = step;
 }
        private void ProcessInvocations(IEnumerable <InvocationExpressionSyntax> invocationExpressionSyntaxes,
                                        MethodModel methodModel)
        {
            foreach (InvocationExpressionSyntax invocationExpressionSyntax in invocationExpressionSyntaxes)
            {
                IMethodSymbol methodSymbol = null;

                MemberAccessExpressionSyntax memberAccessExpressionSyntax =
                    invocationExpressionSyntax.Expression as MemberAccessExpressionSyntax;

                IdentifierNameSyntax identifierNameSyntax =
                    invocationExpressionSyntax.Expression as IdentifierNameSyntax;

                if (memberAccessExpressionSyntax != null)
                {
                    methodSymbol = SemanticModel.GetSymbolInfo(memberAccessExpressionSyntax).Symbol as IMethodSymbol;
                }
                else if (identifierNameSyntax != null)
                {
                    methodSymbol = SemanticModel.GetSymbolInfo(identifierNameSyntax).Symbol as IMethodSymbol;
                }

                InvokesModel invokesModel = new InvokesModel
                {
                    LineNumber = invocationExpressionSyntax.GetLocation().GetLineSpan().StartLinePosition.Line + 1,
                    MethodId   = methodSymbol?.ToString()
                };
                methodModel.Invocations.Add(invokesModel);
            }
        }
        private void Analyze(SyntaxNodeAnalysisContext context)
        {
            Diagnostic diagnostic = null;
            InvocationExpressionSyntax   invocationExpression   = (InvocationExpressionSyntax)context.Node;
            MemberAccessExpressionSyntax memberAccessExpression = invocationExpression?.Expression as MemberAccessExpressionSyntax;

            if (memberAccessExpression == null)
            {
                return;
            }

            if (memberAccessExpression.Expression is IdentifierNameSyntax identifier && identifier.Identifier.Text.EndsWith("Assert"))
            {
                diagnostic = Analyze(context, invocationExpression, memberAccessExpression);
            }

            if (diagnostic != null)
            {
                IMethodSymbol memberSymbol = context.SemanticModel.GetSymbolInfo(memberAccessExpression).Symbol as IMethodSymbol;
                if ((memberSymbol == null) || !memberSymbol.ToString().StartsWith("Microsoft.VisualStudio.TestTools.UnitTesting.Assert"))
                {
                    return;
                }
                context.ReportDiagnostic(diagnostic);
            }
        }
        private static void Analyze(SyntaxNodeAnalysisContext context)
        {
            var mds = context.Node as InvocationExpressionSyntax;

            if (mds == null)
            {
                return;
            }

            MemberAccessExpressionSyntax maes = mds.Expression as MemberAccessExpressionSyntax;

            if (maes == null)
            {
                return;
            }

            string memberName = maes.Name.ToString();

            if ((memberName != @"AreEqual") && (memberName != @"AreNotEqual"))
            {
                return;
            }

            IMethodSymbol memberSymbol = context.SemanticModel.GetSymbolInfo(maes).Symbol as IMethodSymbol;

            if ((memberSymbol == null) || !memberSymbol.ToString().StartsWith("Microsoft.VisualStudio.TestTools.UnitTesting.Assert"))
            {
                return;
            }

            // If it resolved to Are[Not]Equal<T>, then we know the types are the same.
            if (memberSymbol.IsGenericMethod)
            {
                return;
            }

            ArgumentListSyntax argumentList = mds.ArgumentList as ArgumentListSyntax;
            TypeInfo           ti1          = context.SemanticModel.GetTypeInfo(argumentList.Arguments[0].Expression);
            TypeInfo           ti2          = context.SemanticModel.GetTypeInfo(argumentList.Arguments[1].Expression);

            // Our <actual> is of type object.  If it matches the type of <expected>, then AreEqual will pass, so we wouldn't want to fail here.
            // However, if the types differ, it will be a runtime Assert fail, so the early notice is advantageous.  The code is also clearer.
            // Moreover, if it were "AreNotEqual", that is particularly insidious, because the Assert would pass due to the type difference
            // rather than the value difference.  Let's play it safe, and require the author to be clear.
            //if (ti2.Type.ToString() == @"object")
            //{
            //	return;
            //}

            if (!context.SemanticModel.Compilation.ClassifyConversion(ti2.Type, ti1.Type).IsImplicit)
            {
                Diagnostic diagnostic = Diagnostic.Create(Rule, mds.GetLocation(), ti1.Type.ToString(), ti2.Type.ToString());
                context.ReportDiagnostic(diagnostic);
            }
        }
        protected override Diagnostic Analyze(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocationExpressionSyntax, MemberAccessExpressionSyntax memberAccessExpression)
        {
            string memberName = memberAccessExpression.Name.ToString();

            if ((memberName != @"AreEqual") && (memberName != @"AreNotEqual"))
            {
                return(null);
            }

            IMethodSymbol memberSymbol = context.SemanticModel.GetSymbolInfo(memberAccessExpression).Symbol as IMethodSymbol;

            if ((memberSymbol == null) || !memberSymbol.ToString().StartsWith("Microsoft.VisualStudio.TestTools.UnitTesting.Assert"))
            {
                return(null);
            }

            // Assert.AreEqual is incorrectly used if the literal is the second argument (including null) or if the first argument is null
            bool isUsedIncorrectly = false;
            ArgumentListSyntax      argumentList = invocationExpressionSyntax.ArgumentList as ArgumentListSyntax;
            LiteralExpressionSyntax arg0Literal  = argumentList.Arguments[0].Expression as LiteralExpressionSyntax;
            LiteralExpressionSyntax arg1Literal  = argumentList.Arguments[1].Expression as LiteralExpressionSyntax;

            if ((arg1Literal != null) || Helper.IsConstantExpression(argumentList.Arguments[1].Expression, context.SemanticModel))
            {
                if ((arg0Literal == null) && !Helper.IsConstantExpression(argumentList.Arguments[0].Expression, context.SemanticModel))
                {
                    isUsedIncorrectly = true;
                }
                else if (arg1Literal != null)
                {
                    Optional <object> literalValue = context.SemanticModel.GetConstantValue(arg1Literal);
                    if (literalValue.Value == null)
                    {
                        isUsedIncorrectly = true;
                    }
                }
            }
            else if (arg0Literal != null)
            {
                Optional <object> literalValue = context.SemanticModel.GetConstantValue(arg0Literal);
                if (literalValue.Value == null)
                {
                    isUsedIncorrectly = true;
                }
            }

            if (isUsedIncorrectly)
            {
                Diagnostic diagnostic = Diagnostic.Create(Rule, invocationExpressionSyntax.GetLocation());
                return(diagnostic);
            }

            return(null);
        }
Example #9
0
File: Task.cs Project: vansha/Nake
        static void CheckSignature(IMethodSymbol symbol)
        {
            bool hasDuplicateParameters = symbol.Parameters
                                          .GroupBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
                                          .Any(p => p.Count() > 1);

            if (!symbol.ReturnsVoid ||
                symbol.IsGenericMethod ||
                symbol.Parameters.Any(p => p.RefKind != RefKind.None || !TypeConverter.IsSupported(p.Type)) ||
                hasDuplicateParameters)
            {
                throw new TaskSignatureViolationException(symbol.ToString());
            }
        }
        private MethodDetails GetMethodDetails(IMethodSymbol methodSymbol)
        {
            var fullMethodName = methodSymbol.ToString().Replace("()", "");

            if (methodSymbol.IsGenericMethod)
            {
                fullMethodName = fullMethodName.Split('<')[0];
                fullMethodName = $"{fullMethodName}``{methodSymbol.Arity}";
            }

            return(new MethodDetails
            {
                FullName = fullMethodName
            });
        }
Example #11
0
        public void Analyze(SyntaxNodeAnalysisContext context)
        {
            IEnumerable <MethodDeclarationSyntax> ancestorMethods = context.Node.Ancestors().OfType <MethodDeclarationSyntax>();

            if (ancestorMethods.Count() > 0)
            {
                MethodDeclarationSyntax parentMethod = ancestorMethods.First();
                if (parentMethod.Identifier.Text == @"Dispose")
                {
                    IMethodSymbol methodSymbol = context.SemanticModel.GetDeclaredSymbol(parentMethod);
                    if ((methodSymbol != null) && methodSymbol.ToString().Contains(".Dispose("))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation()));
                    }
                }
            }
        }
Example #12
0
 public static bool HasAttribute(AttributeListSyntax attributes, SyntaxNodeAnalysisContext context, string name, string fullName, out Location location)
 {
     location = null;
     foreach (AttributeSyntax attribute in attributes.Attributes)
     {
         if (attribute.Name.ToString().Contains(name))
         {
             IMethodSymbol memberSymbol = context.SemanticModel.GetSymbolInfo(attribute).Symbol as IMethodSymbol;
             if (memberSymbol != null && memberSymbol.ToString().StartsWith(fullName))
             {
                 location = attribute.GetLocation();
                 return(true);
             }
         }
     }
     return(false);
 }
Example #13
0
        public static bool TryGetAttribute(AttributeListSyntax attributes, SyntaxNodeAnalysisContext context, AttributeDefinition attributeDefinition, out AttributeSyntax attribute)
        {
            foreach (AttributeSyntax attr in attributes.Attributes)
            {
                if (attr.Name.ToString().Contains(attributeDefinition.Name))
                {
                    IMethodSymbol memberSymbol = context.SemanticModel.GetSymbolInfo(attr).Symbol as IMethodSymbol;
                    if (memberSymbol != null && memberSymbol.ToString().StartsWith(attributeDefinition.FullName))
                    {
                        attribute = attr;
                        return(true);
                    }
                }
            }

            attribute = default;
            return(false);
        }
Example #14
0
        protected override IEnumerable <Diagnostic> Analyze(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocationExpressionSyntax, MemberAccessExpressionSyntax memberAccessExpression)
        {
            string memberName = memberAccessExpression.Name switch
            {
                GenericNameSyntax generic => generic.Identifier.ToString(),
                SimpleNameSyntax name => name.ToString()
            };

            if ((memberName != @"AreEqual") && (memberName != @"AreNotEqual"))
            {
                return(null);
            }

            IMethodSymbol memberSymbol = context.SemanticModel.GetSymbolInfo(memberAccessExpression).Symbol as IMethodSymbol;

            if ((memberSymbol == null) || !memberSymbol.ToString().StartsWith("Microsoft.VisualStudio.TestTools.UnitTesting.Assert"))
            {
                return(null);
            }

            // Assert.AreEqual is incorrectly used if the literal is the second argument (including null) or if the first argument is null
            ArgumentListSyntax argumentList = invocationExpressionSyntax.ArgumentList;

            bool arg0Literal = IsLiteral(argumentList.Arguments[0].Expression, context.SemanticModel);
            bool arg1Literal = IsLiteral(argumentList.Arguments[1].Expression, context.SemanticModel);

            if (!arg0Literal && !arg1Literal)
            {
                return(null);
            }

            if (arg0Literal)
            {
                return(null);
            }

            if (arg1Literal)
            {
                Diagnostic diagnostic = Diagnostic.Create(Rule, invocationExpressionSyntax.GetLocation());
                return(new[] { diagnostic });
            }

            return(null);
        }
 private static bool IsSelectingADifferentMethod(IEnumerable<SyntaxNode> childNodes, SimpleNameSyntax methodName, SyntaxTree tree, IMethodSymbol methodSymbol, ExpressionSyntax invocationExpression, Compilation compilation)
 {
     var parameterExpressions = GetParameterExpressions(childNodes);
     var firstArgument = parameterExpressions.FirstOrDefault();
     var argumentList = CreateArgumentListSyntaxFrom(parameterExpressions.Skip(1));
     var newInvocationStatement = CreateInvocationExpression(firstArgument, methodName, argumentList)
         .WithAdditionalAnnotations(introduceExtensionMethodAnnotation);
     var extensionMethodNamespaceUsingDirective = SyntaxFactory.UsingDirective(methodSymbol.ContainingNamespace.ToNameSyntax());
     var speculativeRootWithExtensionMethod = tree.GetCompilationUnitRoot()
         .ReplaceNode(invocationExpression, newInvocationStatement)
         .AddUsings(extensionMethodNamespaceUsingDirective);
     var speculativeTree = speculativeRootWithExtensionMethod.SyntaxTree;
     var speculativeTreeOptions = (CSharpParseOptions)speculativeTree.Options;
     var speculativeTreeWithCorrectLanguageVersion = speculativeTree.WithRootAndOptions(speculativeRootWithExtensionMethod, speculativeTreeOptions.WithLanguageVersion(((CSharpParseOptions)tree.Options).LanguageVersion));
     var speculativeModel = compilation.ReplaceSyntaxTree(tree, speculativeTreeWithCorrectLanguageVersion)
         .GetSemanticModel(speculativeTreeWithCorrectLanguageVersion);
     var speculativeInvocationStatement = speculativeTreeWithCorrectLanguageVersion.GetCompilationUnitRoot().GetAnnotatedNodes(introduceExtensionMethodAnnotation).Single() as InvocationExpressionSyntax;
     var speculativeExtensionMethodSymbol = speculativeModel.GetSymbolInfo(speculativeInvocationStatement.Expression).Symbol as IMethodSymbol;
     var speculativeNonExtensionFormOfTheMethodSymbol = speculativeExtensionMethodSymbol?.GetConstructedReducedFrom();
     return speculativeNonExtensionFormOfTheMethodSymbol == null || speculativeNonExtensionFormOfTheMethodSymbol.ToString() != methodSymbol.ToString();//can't compare equality, as speculative symbol might be different
 }
Example #16
0
        public static bool IsAttribute(AttributeSyntax attribute, SyntaxNodeAnalysisContext context, string name, string fullName, out Location location, out AttributeArgumentSyntax argument)
        {
            location = null;
            argument = default(AttributeArgumentSyntax);

            if (attribute.Name.ToString().Contains(name))
            {
                IMethodSymbol memberSymbol = context.SemanticModel.GetSymbolInfo(attribute).Symbol as IMethodSymbol;
                if (memberSymbol != null && memberSymbol.ToString().StartsWith(fullName))
                {
                    location = attribute.GetLocation();
                    if (attribute.ArgumentList != null && attribute.ArgumentList.Arguments.Count > 0)
                    {
                        argument = attribute.ArgumentList.Arguments.First();
                    }
                    return(true);
                }
            }

            return(false);
        }
Example #17
0
        private List <ConstructorModel> FindContructors(SyntaxNode syntaxNode)
        {
            List <ConstructorDeclarationSyntax> constructorDeclarationSyntaxes = syntaxNode
                                                                                 .DescendantNodes()
                                                                                 .OfType <ConstructorDeclarationSyntax>()
                                                                                 .ToList();

            List <ConstructorModel> result = new List <ConstructorModel>();

            foreach (ConstructorDeclarationSyntax constructorDeclarationSyntax in constructorDeclarationSyntaxes)
            {
                ConstructorModel constructorModel = new ConstructorModel();

                constructorModel.Name = constructorDeclarationSyntax.Identifier.Text;

                IMethodSymbol methodSymbol =
                    SemanticModel.GetDeclaredSymbol(constructorDeclarationSyntax) as IMethodSymbol;

                constructorModel.Fqn             = methodSymbol.ToString();
                constructorModel.Static          = methodSymbol.IsStatic;
                constructorModel.Abstract        = methodSymbol.IsAbstract;
                constructorModel.Sealed          = methodSymbol.IsSealed;
                constructorModel.Async           = methodSymbol.IsAsync;
                constructorModel.Override        = methodSymbol.IsOverride;
                constructorModel.Virtual         = methodSymbol.IsVirtual;
                constructorModel.Accessibility   = methodSymbol.DeclaredAccessibility.ToString();
                constructorModel.FirstLineNumber =
                    constructorDeclarationSyntax.GetLocation().GetLineSpan().StartLinePosition.Line + 1;
                constructorModel.LastLineNumber =
                    constructorDeclarationSyntax.GetLocation().GetLineSpan().EndLinePosition.Line + 1;

                _invocationAnalyzer.Analyze(constructorDeclarationSyntax, constructorModel);
                _parameterAnalyzer.Analyze(constructorDeclarationSyntax, constructorModel);

                result.Add(constructorModel);
            }

            return(result);
        }
        public void IsAsyncLibraryConstruct(IMethodSymbol symbol)
        {
            if (symbol.ContainingNamespace.ToString().Equals("System.Threading.Tasks") ||
                symbol.ContainingNamespace.ToString().Equals("System.Threading") ||
                (symbol.ContainingNamespace.ToString().Equals("System.Linq") && (symbol.ContainingType.ToString().Contains("ParallelQuery") || symbol.ContainingType.ToString().Contains("ParallelEnumerable"))) ||
                symbol.ContainingNamespace.ToString().Equals("System.Collections.Concurrent"))
            {
                var libraryUsage = Result.LibraryUsage;

                int temp;
                string key = symbol.ToString();
                
                libraryUsage.TryGetValue(key, out temp);
                libraryUsage[key] = ++temp;
            }
        }
Example #19
0
            public void Add(IMethodSymbol ms)
            {
                if (IsLibrary)
                    return;
                FlatArrayBuilder fab = new FlatArrayBuilder();
                fab.Add(FlatValue.Int32(ms.IsStatic ? (int)ClassMemberType.StaticMethod : (int)ClassMemberType.Method));
                fab.Add(FlatValue.String(ms.GetFullyQualifiedName()));

                Function f;
                if (!Chunk.Functions.TryGetValue(ms, out f))
                {
                    throw new LS2ILMethodException("Method not found " + ms.ToString());
                }

                fab.Add(FlatValue.Int32(f.NumFunction));

                // input declarations
                fab.Add(GenerateInputDeclarations(ms).GetFlatValue());

                Members.Add(fab.GetFlatValue());
            }
        private void DetectBlockingOperations(InvocationExpressionSyntax methodCall, IMethodSymbol methodCallSymbol)
        {

            var methodDeclaration = methodCall.FirstAncestorOrSelf<MethodDeclarationSyntax>();
            var replacement = ((IMethodSymbol)methodCallSymbol.OriginalDefinition).DetectSynchronousUsages(SemanticModel);

            if (methodDeclaration != null)
            {
                if (replacement != "None")
                {
                    Logs.TempLog6.Info(@"{0}{1}{2}{3}**********************************************",
                                        Document.FilePath,
                                        System.Environment.NewLine + System.Environment.NewLine + "BLOCKING METHODCALL: " + methodCallSymbol.ToString(),
                                        System.Environment.NewLine + System.Environment.NewLine + "REPLACE IT WITH: " + replacement,
                                        methodDeclaration.ToLog());
                }
            }
        }
Example #21
0
 static bool IsStringFormatInvocation(IMethodSymbol symbol)
 {
     return(symbol.ToString().StartsWith("string.Format("));
 }
        private static bool IsSelectingADifferentMethod(IEnumerable <SyntaxNode> childNodes, SimpleNameSyntax methodName, SyntaxTree tree, IMethodSymbol methodSymbol, ExpressionSyntax invocationExpression, Compilation compilation)
        {
            var parameterExpressions   = GetParameterExpressions(childNodes);
            var firstArgument          = parameterExpressions.FirstOrDefault();
            var argumentList           = CreateArgumentListSyntaxFrom(parameterExpressions.Skip(1));
            var newInvocationStatement = CreateInvocationExpression(firstArgument, methodName, argumentList)
                                         .WithAdditionalAnnotations(introduceExtensionMethodAnnotation);
            var extensionMethodNamespaceUsingDirective = SyntaxFactory.UsingDirective(methodSymbol.ContainingNamespace.ToNameSyntax());
            var speculativeRootWithExtensionMethod     = tree.GetCompilationUnitRoot()
                                                         .ReplaceNode(invocationExpression, newInvocationStatement)
                                                         .AddUsings(extensionMethodNamespaceUsingDirective);
            var speculativeTree        = speculativeRootWithExtensionMethod.SyntaxTree;
            var speculativeTreeOptions = (CSharpParseOptions)speculativeTree.Options;
            var speculativeTreeWithCorrectLanguageVersion = speculativeTree.WithRootAndOptions(speculativeRootWithExtensionMethod, speculativeTreeOptions.WithLanguageVersion(((CSharpParseOptions)tree.Options).LanguageVersion));
            var speculativeModel = compilation.ReplaceSyntaxTree(tree, speculativeTreeWithCorrectLanguageVersion)
                                   .GetSemanticModel(speculativeTreeWithCorrectLanguageVersion);
            var speculativeInvocationStatement               = speculativeTreeWithCorrectLanguageVersion.GetCompilationUnitRoot().GetAnnotatedNodes(introduceExtensionMethodAnnotation).Single() as InvocationExpressionSyntax;
            var speculativeExtensionMethodSymbol             = speculativeModel.GetSymbolInfo(speculativeInvocationStatement.Expression).Symbol as IMethodSymbol;
            var speculativeNonExtensionFormOfTheMethodSymbol = speculativeExtensionMethodSymbol?.GetConstructedReducedFrom();

            return(speculativeNonExtensionFormOfTheMethodSymbol == null || speculativeNonExtensionFormOfTheMethodSymbol.ToString() != methodSymbol.ToString());//can't compare equality, as speculative symbol might be different
        }
        public static MethodBase ToCSharpMethod(this IMethodSymbol methodSymbol, List <NamedTypeBase> types, SemanticModel model, NamedTypeBase parentType, LoggerProvider logprovider)
        {
            if (methodSymbol == null)
            {
                return(null);
            }

            INamedType drt = null;

            //hack
            if (methodSymbol.ReturnType.TypeKind != TypeKind.TypeParameter)
            {
                drt = types.FirstOrDefault(t => t == methodSymbol.ReturnType.ToCSharpNamedType(logprovider));
                if (drt == null && !methodSymbol.ReturnsVoid)
                {
                    logprovider.WriteToLog(string.Format("Cannot find type for {0} as the non-void declared return type of method {1}, creating empty type manually", methodSymbol.ReturnType.ToString(), methodSymbol.ToString()));
                    types.Add(methodSymbol.ReturnType.ToCSharpNamedType(logprovider));
                }
            }
            List <IMethodParameter> parameters = new List <IMethodParameter>();

            foreach (var paramSymbol in methodSymbol.Parameters)
            {
                parameters.Add(paramSymbol.ToCSharpMethodParameter(types, logprovider));
            }

            return(new CSharpMethod
            {
                IsAbstract = methodSymbol.IsAbstract,
                IsOverride = methodSymbol.IsOverride,
                IsStatic = methodSymbol.IsStatic,
                IsVirtual = methodSymbol.IsVirtual,
                Parent = parentType,
                Name = methodSymbol.Name,
                IsCtor = (methodSymbol.MethodKind == MethodKind.Constructor),
                Visibility = methodSymbol.DeclaredAccessibility.ToVisibilityModifierBase(logprovider),
                DeclaredReturnType = drt,
                Parameters = parameters,
                ActualReturnTypes = methodSymbol.GetActualReturnTypes(types, model),
                IsGeneric = methodSymbol.IsGenericMethod,
                SourceSymbol = methodSymbol,
                GenericParameters = CSharpModelBuilder.BuildGenericList(methodSymbol.TypeArguments)
            });
        }
        public static string GetKeyValueFor(QueryContext queryContext)
        {
            Workspace               Workspace    = queryContext.workspace;
            Project                 proj         = queryContext.proj;
            Document                doc          = queryContext.doc;
            IMethodSymbol           methodSymbol = queryContext.methodSymbol;
            MethodDeclarationSyntax method       = queryContext.method;
            //Location location = queryContext.location;

            //var invokes = method.DescendantNodes().Where(x=>x is InvocationExpressionSyntax).ToList();
            String method_name = method.Identifier.Text;

            String solution_id = Workspace.CurrentSolution.Id.Id.ToString();

            String project_path         = proj.FilePath;
            String project_name         = proj.Name;
            String project_assemblypath = proj.AssemblyName;
            String project_id           = proj.Id.Id.ToString();

            String document_id      = doc.Id.Id.ToString();
            String document_name    = doc.Name.ToString();
            String document_path    = doc.FilePath.ToString();
            String document_folders = string.Join(",", doc.Folders);

            String textspan_start = method.Span.Start.ToString(); //location.GetMappedLineSpan().Span.Start.ToString();
            String textspan_end   = method.Span.End.ToString();   //location.GetMappedLineSpan().Span.End.ToString();



            String hashCode = toHashCode(methodSymbol, new String[] { solution_id, project_id, document_id, doc.FilePath }).ToString();

            // String method_parameter_list =   method.ParameterList.Parameters.Select(x=>x.ToString());
            String method_languge = method.Language;

            int method_arity = method.Arity;

            String method_declaration_line1 = "";
            {
                String methodstring = method.ToString();
                if (methodstring.Contains("\n"))

                {
                    var i = methodstring.IndexOf("\n");
                    method_declaration_line1 = methodstring.Substring(0, i + 1);
                }
            }
            String method_symbol_name = methodSymbol.Name;


            String method_symbol_defination         = methodSymbol.ToString(); //Microsoft.CodeAnalysis.SemanticModel.GetSymbolInfo(Microsoft.CodeAnalysis.SyntaxNode, System.Threading.CancellationToken)
            String method_symbol_orginal_defination = methodSymbol.OriginalDefinition.ToString();
            String method_symbol_associated_symbol  = "";



            if (methodSymbol.AssociatedSymbol != null)
            {
                method_symbol_associated_symbol = methodSymbol.AssociatedSymbol.ToString();
            }

            String method_symbol_containing_module      = methodSymbol.ContainingModule.ToString();
            String method_symbol_containing_namespace   = methodSymbol.ContainingNamespace.ToString();
            String method_symbol_containing_assembly    = methodSymbol.ContainingAssembly.ToString(); //ContainingAssembly
            bool   method_symbol_HidesBaseMethodsByName = methodSymbol.HidesBaseMethodsByName;
            bool   method_symbol_isAbstract             = methodSymbol.IsAbstract;
            bool   method_symbol_isAsync             = methodSymbol.IsAsync;
            bool   method_symbol_isGenericMethod     = methodSymbol.IsGenericMethod;
            bool   method_symbol_isImplcitlyDeclared = methodSymbol.IsImplicitlyDeclared;
            bool   method_symbol_isOverride          = methodSymbol.IsOverride;
            bool   method_symbol_isSealed            = methodSymbol.IsSealed;
            bool   method_symbol_isStatic            = methodSymbol.IsStatic;
            bool   method_symbol_isVirtual           = methodSymbol.IsVirtual;
            bool   method_symbol_isExtern            = methodSymbol.IsExtern;
            String method_symbol_ReturnType          = methodSymbol.ReturnType.ToString();
            String className = methodSymbol.ContainingType.ToString();



            String[] keys = new String[] {
                "name",
                "method_name",
                "solution_id",
                "project_path",
                "project_name",
                "project_id",
                "document_id",
                "document_name",
                "document_path",
                "document_folders",
                "textspan_start",
                "textspan_end",

                "hashCode",

                "method_arity",
                "method_declaration_line1",
                "method_symbol_name",
                "method_symbol_defination",
                "method_symbol_orginal_defination",
                "method_symbol_associated_symbol",
                "method_symbol_containing_module",
                "method_symbol_containing_namespace",
                "method_symbol_containing_assembly",
                "method_symbol_associated_symbol",
                "method_symbol_containing_module",
                "method_symbol_containing_namespace",
                "method_symbol_containing_assembly",

                "method_symbol_HidesBaseMethodsByName",
                "method_symbol_isAbstract",
                "method_symbol_isAsync",
                "method_symbol_isGenericMethod",
                "method_symbol_isImplcitlyDeclared",
                "method_symbol_isOverride",
                "method_symbol_isSealed",
                "method_symbol_isStatic",
                "method_symbol_isVirtual",
                "method_symbol_isExtern",
                "method_symbol_ReturnType",
                "class_name"
            };


            String[] values = new String[] {
                hashCode,
                method_name,
                solution_id,
                project_path,
                project_name,
                project_id,
                document_id,
                document_name,
                document_path,
                document_folders,

                textspan_start,
                textspan_end,
                hashCode,

                method_arity.ToString(),
                method_declaration_line1,
                method_symbol_name.ToString(),
                method_symbol_defination.ToString(),
                method_symbol_orginal_defination.ToString(),
                method_symbol_associated_symbol,
                method_symbol_containing_module,
                method_symbol_containing_namespace,
                method_symbol_containing_assembly,
                method_symbol_associated_symbol,
                method_symbol_containing_module,
                method_symbol_containing_namespace,
                method_symbol_containing_assembly,
                method_symbol_HidesBaseMethodsByName.ToString(),
                method_symbol_isAbstract.ToString(),
                method_symbol_isAsync.ToString(),
                method_symbol_isGenericMethod.ToString(),
                method_symbol_isImplcitlyDeclared.ToString(),
                method_symbol_isOverride.ToString(),
                method_symbol_isSealed.ToString(),
                method_symbol_isStatic.ToString(),
                method_symbol_isVirtual.ToString(),
                method_symbol_isExtern.ToString(),
                method_symbol_ReturnType.ToString(),
                className
            };

            String querypart = "";

            for (int i = 0; i < values.Length; i++)
            {
                querypart += keys[i] + ":'" + values[i] + "',\n";
            }


            return(querypart);
        }
Example #25
0
File: Task.cs Project: jthelin/Nake
 public Task(IMethodSymbol symbol, bool step)
 {
     CheckSignature(symbol);
     signature = symbol.ToString();
     this.step = step;
 }
Example #26
0
 public override string ToString()
 {
     return(Symbol.ToString());
 }
Example #27
0
File: Task.cs Project: jthelin/Nake
        static void CheckSignature(IMethodSymbol symbol)
        {
            bool hasDuplicateParameters = symbol.Parameters
                .GroupBy(p => p.Name, StringComparer.OrdinalIgnoreCase)
                .Any(p => p.Count() > 1);

            if (!symbol.ReturnsVoid ||
                symbol.IsGenericMethod ||
                symbol.Parameters.Any(p => p.RefKind != RefKind.None || !TypeConverter.IsSupported(p.Type)) ||
                hasDuplicateParameters)
                throw new TaskSignatureViolationException(symbol.ToString());
        }