private static Solution UpdateMainDocument(Document document, SyntaxNode root, MethodDeclarationSyntax method, IEnumerable<IGrouping<Document, ReferenceLocation>> documentGroups)
 {
     var mainDocGroup = documentGroups.FirstOrDefault(dg => dg.Key.Equals(document));
     SyntaxNode newRoot;
     if (mainDocGroup == null)
     {
         newRoot = root.ReplaceNode(method, method.AddModifiers(staticToken));
     }
     else
     {
         var diagnosticNodes = mainDocGroup.Select(referenceLocation => root.FindNode(referenceLocation.Location.SourceSpan)).ToList();
         newRoot = root.TrackNodes(diagnosticNodes.Union(new[] { method }));
         newRoot = newRoot.ReplaceNode(newRoot.GetCurrentNode(method), method.AddModifiers(staticToken));
         foreach (var diagnosticNode in diagnosticNodes)
         {
             var token = newRoot.FindToken(diagnosticNode.GetLocation().SourceSpan.Start);
             var tokenParent = token.Parent;
             if (token.Parent.IsKind(SyntaxKind.IdentifierName)) continue;
             var invocationExpression = newRoot.GetCurrentNode(diagnosticNode).FirstAncestorOrSelfOfType<InvocationExpressionSyntax>()?.Expression;
             if (invocationExpression == null || invocationExpression.IsKind(SyntaxKind.IdentifierName)) continue;
             var memberAccess = invocationExpression as MemberAccessExpressionSyntax;
             if (memberAccess == null) continue;
             var newMemberAccessParent = memberAccess.Parent.ReplaceNode(memberAccess, memberAccess.Name)
                 .WithAdditionalAnnotations(Formatter.Annotation);
             newRoot = newRoot.ReplaceNode(memberAccess.Parent, newMemberAccessParent);
         }
     }
     var newSolution = document.Project.Solution.WithDocumentSyntaxRoot(document.Id, newRoot);
     return newSolution;
 }
 private static ClassDeclarationSyntax CreateParameterClass(string newNameClass, MethodDeclarationSyntax oldMethod)
 {
     var properties = CreateProperties(oldMethod);
     return SyntaxFactory.ClassDeclaration(newNameClass)
         .WithMembers(SyntaxFactory.List<MemberDeclarationSyntax>(properties))
         .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)));
 }
        private async Task<Document> ReturnVoidAsync(Document document, MethodDeclarationSyntax method, CancellationToken cancellationToken)
        {
            var newStatements = new List<StatementSyntax>();
            foreach (var s in method.Body.Statements)
            {
                if (s is ReturnStatementSyntax)
                {
                    continue;
                }
                else
                    newStatements.Add(s);
            }

            var newMethodDeclaration =
                SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName("void").WithLeadingTrivia(method.ReturnType.GetLeadingTrivia()).WithTrailingTrivia(method.ReturnType.GetTrailingTrivia()), method.Identifier)
                .AddModifiers(method.Modifiers.ToArray())
                .WithLeadingTrivia(method.GetLeadingTrivia())
                .WithBody(SyntaxFactory.Block(newStatements))
                ;

            var root = await document.GetSyntaxRootAsync();
            var newRoot = root.ReplaceNode(method, newMethodDeclaration);

            return document.WithSyntaxRoot(newRoot);
        }
		private static StatementSyntax CreateStatement(MethodDeclarationSyntax methodNode, IMethodSymbol methodSymbol)
		{
			var methodParameters = methodSymbol.Parameters;
			var arguments = new string[methodParameters.Length];

			for(var i = 0; i < methodParameters.Length; i++)
			{
				var parameter = methodParameters[i];
				var argument = parameter.Name;

				if (parameter.RefKind.HasFlag(RefKind.Ref))
				{
					argument = $"ref {argument}";
				}
				else if (parameter.RefKind.HasFlag(RefKind.Out))
				{
					argument = $"out {argument}";
				}

				arguments[i] = argument;
			}

			var methodCall = $"base.{methodSymbol.Name}({string.Join(", ", arguments)});{Environment.NewLine}";

			if(!methodSymbol.ReturnsVoid)
			{
				var variableName = MustInvokeBaseMethodCallMethodCodeFix.CreateSafeLocalVariableName(
					methodNode, methodSymbol);
				methodCall = $"var {variableName} = {methodCall}";
			}

			return SyntaxFactory.ParseStatement(methodCall).WithAdditionalAnnotations(Formatter.Annotation);
		}
		public void DetectBlockingAsyncCallers(MethodDeclarationSyntax node)
		{
			var symbol = SemanticModel.GetDeclaredSymbol(node);
			if (symbol != null)
			{
				foreach (var refs in SymbolFinder.FindReferencesAsync(symbol, SourceFile.Project.Solution).Result)
				{
					foreach (var loc in refs.Locations)
					{
						var textSpan = loc.Location.SourceSpan;
						var callerNode = loc.Document.GetSyntaxRootAsync().Result.DescendantNodes(textSpan).FirstOrDefault(n => textSpan.Contains(n.Span));
						var callerText = loc.Document.GetTextAsync().Result.Lines.ElementAt(loc.Location.GetLineSpan().StartLinePosition.Line).ToString();
						if (callerText.Contains(".Wait()")) // caller.Contains(".Result")
						{
							Logs.TempLog5.Info("Blocking Caller Name: " + callerText.Trim() + " from this file: " + loc.Document.FilePath);
							var temp = callerNode != null ? callerNode.Ancestors().OfType<MethodDeclarationSyntax>().FirstOrDefault() : null;
							if (temp != null)
							{
								Logs.TempLog5.Info("Blocking Caller Method Node: " + temp.ToLog());
								if (temp.IsAsync())
								{
									Logs.TempLog5.Info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
								}
							}

							Logs.TempLog5.Info("Async method Callee from this file " + SourceFile.FilePath + node.ToLog()+ Logs.Break);
						}
					}
				}
			}
		}
        private async Task<Document> RepairXmlCommentAsync(Document document, MethodDeclarationSyntax methodSyntax, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            var methodSymbol = model.GetDeclaredSymbol(methodSyntax);

            var xml = methodSymbol.GetDocumentationCommentXml();

            var documentTrivia = methodSyntax.GetLeadingTrivia().Where(n => n.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia).Last();

            var documentText = documentTrivia.ToFullString().TrimEnd();
            var invalidXml = Regex.Replace(documentText, @"^\s*///", "", RegexOptions.Multiline);

            var newXml = RpairXml(invalidXml);

            var newDocumentCommentText = Regex.Replace(newXml, @"^", "///", RegexOptions.Multiline) + "\r\n";

            var newDocumentTrivia = SyntaxFactory.ParseLeadingTrivia(newDocumentCommentText)[0];

            var newRoot = root.ReplaceTrivia(documentTrivia, newDocumentTrivia.WithAdditionalAnnotations(Formatter.Annotation));

            var newDocument = document.WithSyntaxRoot(newRoot);

            return newDocument;
        }
        private async Task<Document> RemoveAsyncAwait(Document document, MethodDeclarationSyntax methodDecl, CancellationToken cancellationToken)
        {
            MethodDeclarationSyntax newMethodDecl;

            // (1) Remove async keyword
            var asyncModifier = methodDecl.Modifiers.First(a => a.Kind() == SyntaxKind.AsyncKeyword);
            newMethodDecl = asyncModifier.HasLeadingTrivia 
                ? methodDecl.WithModifiers(methodDecl.Modifiers.Remove(asyncModifier)).WithLeadingTrivia(asyncModifier.LeadingTrivia)
                : methodDecl.WithModifiers(methodDecl.Modifiers.Remove(asyncModifier));

            // (2) If void, convert it to Task
            if (newMethodDecl.ReturnsVoid())
            {
                var newType = SyntaxFactory.ParseTypeName("System.Threading.Tasks.Task").WithAdditionalAnnotations(Simplifier.Annotation).WithTrailingTrivia(newMethodDecl.ReturnType.GetTrailingTrivia());
                newMethodDecl = newMethodDecl.WithReturnType(newType);
            }

            // (3) For all await expressions, remove await and insert return if there is none. 
            var awaitExprs = newMethodDecl.Body.DescendantNodes().OfType<AwaitExpressionSyntax>();

            List<SyntaxReplacementPair> pairs = new List<SyntaxReplacementPair>();

            foreach (var awaitExpr in awaitExprs)
            {
                SyntaxNode oldNode;
                SyntaxNode newNode;
                var newAwaitExpr = awaitExpr;
                // If there is some ConfigureAwait(false), remove it 
                var invoc = awaitExpr.Expression as InvocationExpressionSyntax;
                if (invoc != null)
                {
                    var expr = invoc.Expression as MemberAccessExpressionSyntax;

                    // TODO: Check whether it is ConfigureAwait(false) or ConfigureAwait(true);
                    if (expr != null && expr.Name.Identifier.ValueText == "ConfigureAwait")
                    {
                        newAwaitExpr = awaitExpr.ReplaceNode(awaitExpr.Expression, expr.Expression);
                    }
                }

                if (awaitExpr.Parent.Kind() == SyntaxKind.ReturnStatement)
                {
                    oldNode = awaitExpr;
                    newNode = newAwaitExpr.Expression.WithAdditionalAnnotations(Simplifier.Annotation);
                }
                else
                {
                    oldNode = awaitExpr.Parent;
                    newNode = SyntaxFactory.ReturnStatement(newAwaitExpr.Expression).WithAdditionalAnnotations(Formatter.Annotation).WithTrailingTrivia(oldNode.GetTrailingTrivia());
                }
                pairs.Add(new SyntaxReplacementPair(oldNode, newNode));
            }

            newMethodDecl = newMethodDecl.ReplaceAll(pairs);

            // (4) Replace the old method with the new one.
            var root = await document.GetSyntaxRootAsync().ConfigureAwait(false);
            var newRoot = root.ReplaceNode(methodDecl, newMethodDecl);
            return document.WithSyntaxRoot(newRoot);
        }
 public void Run(object testObject, MethodDeclarationSyntax method, SemanticModel semanticModel)
 {
     _semanticModel = semanticModel;
     ExecuteSetup(testObject, method);
     ExecuteTest(testObject, method);
     ExecuteTearDown(testObject, method);
 }
 public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
 {
     var parameterTokens = node.ParameterList.Parameters.Select(p => p.Identifier);
     tracker.AddIdentifiers(parameterTokens);
     Visit(node.Body);
     tracker.RemoveIdentifiers(parameterTokens);
 }
        public CoverageResult CalculateForMethod(string projectName, MethodDeclarationSyntax method)
        {
            var projects = _testExplorer.GetUnignoredTestProjectsWithCoveredProjectsAsync().Result;
            var project = projects.FirstOrDefault(x => x.Name == projectName);

            if (project == null)
                return new CoverageResult(new LineCoverage[0]);

            var rewritter = new SolutionRewriter(new RewrittenDocumentsStorage(), _auditVariablesRewriter);
            RewrittenDocument rewrittenDocument = rewritter.RewriteDocumentWithAssemblyInfo(project, projects, method.SyntaxTree.FilePath, method.SyntaxTree.ToString());

            LineCoverage[] coverage = null;

            using (var appDomainTestExecutorScriptEngine = new AppDomainTestExecutorScriptEngine())
            {
                var lineCoverageCalc = new LineCoverageCalc(_testExplorer, new RoslynCompiler(),
                    new TestRunner(new NUnitTestExtractor(), appDomainTestExecutorScriptEngine, _solutionExplorer));

                coverage = lineCoverageCalc.CalculateForMethod(project, rewrittenDocument, method);
            }

            _coverageStore.Append(coverage);

            return new CoverageResult(coverage);
        }
        public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            // Not the correct way of getting rid of compiler generated getter/setter
            if (node.AttributeLists.Any(attrList =>
                attrList.Attributes.Any(attr =>
                    attr.Name.ToFullString().Contains("CompilerGeneratedAttribute")))||
                node.Identifier.ToFullString().StartsWith("get_") ||
                node.Identifier.ToFullString().StartsWith("set_") ||
                node.Identifier.ToFullString().StartsWith("add_")||
                node.Identifier.ToFullString().StartsWith("remove_"))
            {
                return null;
            }

            return base.VisitMethodDeclaration(
                node.Update(
                    node.AttributeLists,
                    SyntaxFactory.TokenList(),
                    UpdateReturnType(node.ReturnType),
                    node.ExplicitInterfaceSpecifier,
                    node.Identifier,
                    UpdateTypeParameterList(node.TypeParameterList),
                    UpdateParameterList(node.ParameterList),
                    node.ConstraintClauses,
                    UpdateMethodBody(node.Body, node.ReturnType, node.ParameterList),
                    node.SemicolonToken
                ));
        }
        private Diagnostic HandleMethod(MethodDeclarationSyntax methodDeclaration)
        {
            if (methodDeclaration.ExpressionBody != null)
            {
                return null;
            }

            if (methodDeclaration.DescendantNodesAndTokensAndSelf().Any(x => x.GetLeadingTrivia().Concat(x.GetTrailingTrivia()).Any(y => !y.IsWhitespaceTrivia())))
            {
                return null;
            }

            if (methodDeclaration.Body?.Statements.Count != 1)
            {
                return null;
            }

            var statement = methodDeclaration.Body.Statements.FirstOrDefault();
            var returnStatement = statement?.DescendantNodesAndSelf().OfType<ReturnStatementSyntax>().FirstOrDefault();
            if (returnStatement == null)
            {
                return null;
            }

            return Diagnostic.Create(Rule, returnStatement.GetLocation(), "Method", methodDeclaration.Identifier.ValueText);
        }
		protected override string FindError(MethodDeclarationSyntax method)
		{
			var statements = method.Body.Statements;
			return statements.Count != 1 
				|| !(statements.Single() is ReturnStatementSyntax) 
				? ShouldBeSingleMethodMessage : null;
		}
        private static async Task<Document> ReplacePropertyInDocumentAsync(Document document, MethodDeclarationSyntax method, MethodDeclarationSyntax newMethod, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken);
            var newRoot = root.ReplaceNode(method, new[] { newMethod });

            return document.WithSyntaxRoot(newRoot);
        }
        public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            if (node.HasEventArgsParameter())
                Result.generalAsyncResults.NumEventHandlerMethods++;

            base.VisitMethodDeclaration(node);
        }
 internal static MethodDeclarationSyntax CreateIEnumerableFromParamsArrayMethod(MetaField field, MethodDeclarationSyntax paramsArrayMethod)
 {
     return paramsArrayMethod
         .WithParameterList(SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(
             SyntaxFactory.Parameter(ValuesParameterName.Identifier)
                 .WithType(Syntax.IEnumerableOf(GetFullyQualifiedSymbolName(field.ElementType))))));
 }
 public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax methodSyntax)
 {
     var leadingTrivia = methodSyntax.Identifier.LeadingTrivia;
     var trailingTriva = methodSyntax.Identifier.TrailingTrivia;
     return methodSyntax.ReplaceToken(methodSyntax.Identifier,
         SyntaxFactory.Identifier(leadingTrivia, ToCamelCase(methodSyntax.Identifier.ValueText), trailingTriva));
 }
        public static PreconditionsBlock GetPreconditions(MethodDeclarationSyntax method, SemanticModel semanticModel)
        {
            Contract.Requires(method != null);

            var preconditions = new List<IfThrowPrecondition>();

            // Precondition block ends when something exception precondition check is met.
            foreach (var statement in method.Body.Statements)
            {
                // Currently, If-throw precondition means that
                // if statement has only one statement in the if block
                // and this statement is a throw of type ArgumentException
                var ifThrowStatement = statement as IfStatementSyntax;
                if (ifThrowStatement == null) break;

                var block = ifThrowStatement.Statement as BlockSyntax;
                if (block != null && block.Statements.Count != 1) break;

                var throwStatementCandidate = block != null ? block.Statements[0] : ifThrowStatement.Statement;

                // The only valid case (when the processing should keep going)
                // is when the if block has one statement and that statment is a throw of ArgumentException
                if (IsThrowArgumentExceptionStatement(throwStatementCandidate, semanticModel))
                {
                    preconditions.Add(new IfThrowPrecondition(statement, (ThrowStatementSyntax) throwStatementCandidate));
                }
                else
                {
                    break;
                }
            }

            return new PreconditionsBlock(preconditions);
        }
 public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
 {
     if (RequiresNullChecks(node.AttributeLists))
     {
         AddMessage(node, $"method {node.Identifier} needs null checks");
     }
 }
        public void TestSetup()
        {
            syntaxTree = CSharpSyntaxTree.ParseText(Source);

            ifMethod = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(m => m.Identifier.ValueText == "IfMethod");
            switchMethod = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(m => m.Identifier.ValueText == "SwitchMethod");
        }
		public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
		{
			var visibilityTokens = node.DescendantTokens(_ => true)
				.Where(_ => _.IsKind(SyntaxKind.PublicKeyword) ||
					_.IsKind(SyntaxKind.PrivateKeyword) ||
					_.IsKind(SyntaxKind.ProtectedKeyword) ||
					_.IsKind(SyntaxKind.InternalKeyword)).ToImmutableList();

			if (!visibilityTokens.Any(_ => _.IsKind(SyntaxKind.PublicKeyword)))
			{
				var tokenPosition = 0;

				var newMethod = node.ReplaceTokens(visibilityTokens,
					(_, __) =>
					{
						tokenPosition++;

						return tokenPosition == 1 ?
							SyntaxFactory.Token(
								_.LeadingTrivia,
								SyntaxKind.PublicKeyword,
								_.TrailingTrivia) :
							new SyntaxToken();
					});
				return newMethod;
			}
			else
			{
				return node;
			}
		}
        private static bool IsMethodAttributeAnException(MethodDeclarationSyntax methodDeclaration)
        {
            if (methodDeclaration == null) return false;

            foreach (var attributeList in methodDeclaration.AttributeLists)
            {
                foreach (var attribute in attributeList.Attributes)
                {
                    var identifierName = attribute.Name as IdentifierNameSyntax;
                    string nameText = null;
                    if (identifierName != null)
                    {
                        nameText = identifierName?.Identifier.Text;
                    }
                    else
                    {
                        var qualifiedName = attribute.Name as QualifiedNameSyntax;
                        if (qualifiedName != null)
                            nameText = qualifiedName.Right?.Identifier.Text;
                    }
                    if (nameText == null) continue;
                    if (IsExcludedAttributeName(nameText)) return true;
                }
            }
            return false;
        }
        public LineCoverage[] RunTest(Project project,
            RewrittenDocument rewrittenDocument,
            MethodDeclarationSyntax method,
            ISemanticModel semanticModel,
            string[] rewrittenAssemblies)
        {
            var testClass = method.GetParentClass();
            var rewrittenTestClass =
                rewrittenDocument.SyntaxTree
                    .GetRoot()
                    .DescendantNodes()
                    .OfType<ClassDeclarationSyntax>().First(x => x.Identifier.ToString() == testClass.Identifier.ToString());

            var fixtureDetails = _testsExtractor.GetTestFixtureDetails(rewrittenTestClass, semanticModel);
            var allReferences = _solutionExplorer.GetAllProjectReferences(project.Name);

            fixtureDetails.Cases.RemoveAll(x => x.MethodName != method.Identifier.ToString());

            if (fixtureDetails.Cases.Count == 0)
                return null;

            var compiledTestInfo = new CompiledTestFixtureInfo
            {
                AllReferences = allReferences.Union(rewrittenAssemblies).ToArray(),
                TestDocumentPath = rewrittenDocument.DocumentPath,
                SemanticModel = semanticModel
            };

            var coverage = RunTestFixture(fixtureDetails, compiledTestInfo, project.Name);

            return coverage;
        }
        private static List<PropertyDeclarationSyntax> NewPropertyClassFactory(MethodDeclarationSyntax methodOld)
        {
            var newGetSyntax = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                           .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
            var newSetSyntax = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                                            .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
            var acessorSyntax = SyntaxFactory.AccessorList(
                                SyntaxFactory.Token(SyntaxKind.OpenBraceToken),
                                SyntaxFactory.List(new[] { newGetSyntax, newSetSyntax }),
                                SyntaxFactory.Token(SyntaxKind.CloseBraceToken));
            var properties = new List<PropertyDeclarationSyntax>();
            foreach (ParameterSyntax param in methodOld.ParameterList.Parameters)
            {
                var property = SyntaxFactory.PropertyDeclaration(
                                default(SyntaxList<AttributeListSyntax>),
                                SyntaxFactory.TokenList(new[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword) }),
                                param.Type,
                                default(ExplicitInterfaceSpecifierSyntax),
                                SyntaxFactory.Identifier(FirstLetteToUpper(param.Identifier.Text)),
                                acessorSyntax);
                properties.Add(property);

            }
            return properties;
        }
 private void AnalyzeMethodCodeBlock(CodeBlockAnalysisContext context, MethodDeclarationSyntax methodDeclarationSyntax)
 {
     if (HasMultipleIndentations(methodDeclarationSyntax.Body))
     {
         context.ReportDiagnostic(Diagnostic.Create(Rule, methodDeclarationSyntax.Identifier.GetLocation(), methodDeclarationSyntax.Identifier.Text));
     }
 }
 private Task<Solution> MakePublicAsync(Document document, SyntaxNode root, MethodDeclarationSyntax method)
 {
     var generator = SyntaxGenerator.GetGenerator(document);
     var newMethod = generator.WithAccessibility(method, Accessibility.Public);
     var newRoot = root.ReplaceNode(method, newMethod);
     return Task.FromResult(document.WithSyntaxRoot(newRoot).Project.Solution);
 }
        private SyntaxNode FixMethod(
            bool keepVoid, IMethodSymbol methodSymbol, MethodDeclarationSyntax method,
            ITypeSymbol taskType, INamedTypeSymbol taskOfTType)
        {
            var newReturnType = method.ReturnType;

            if (methodSymbol.ReturnsVoid)
            {
                if (!keepVoid)
                {
                    newReturnType = taskType.GenerateTypeSyntax();
                }
            }
            else
            {
                if (!IsTaskLike(methodSymbol.ReturnType, taskType, taskOfTType))
                {
                    // If it's not already Task-like, then wrap the existing return type
                    // in Task<>.
                    newReturnType = taskOfTType.Construct(methodSymbol.ReturnType).GenerateTypeSyntax();
                }
            }

            var newModifiers = method.Modifiers.Add(s_asyncToken);
            return method.WithReturnType(newReturnType).WithModifiers(newModifiers);
        }
            private SyntaxToken AnnotationResolver(
                SyntaxNode node,
                TriviaLocation location,
                SyntaxAnnotation annotation,
                SyntaxNode callsite,
                MethodDeclarationSyntax method)
            {
                var token = node.GetAnnotatedNodesAndTokens(annotation).FirstOrDefault().AsToken();
                if (token.RawKind != 0)
                {
                    return token;
                }

                switch (location)
                {
                    case TriviaLocation.BeforeBeginningOfSpan:
                        return callsite.GetFirstToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true);
                    case TriviaLocation.AfterEndOfSpan:
                        return callsite.GetLastToken(includeZeroWidth: true).GetNextToken(includeZeroWidth: true);
                    case TriviaLocation.AfterBeginningOfSpan:
                        return method.Body.OpenBraceToken.GetNextToken(includeZeroWidth: true);
                    case TriviaLocation.BeforeEndOfSpan:
                        return method.Body.CloseBraceToken.GetPreviousToken(includeZeroWidth: true);
                }

                return Contract.FailWithReturn<SyntaxToken>("can't happen");
            }
		public static List<ValidatorResult> Validate(MethodDeclarationSyntax methodSyntax, IAsyncRewriterLogger log, CompilationLookup extensionMethodLookup, SemanticModel semanticModel, HashSet<ITypeSymbol> excludeTypes, ITypeSymbol cancellationTokenSymbol)
		{
			var validator = new AsyncMethodValidator(log, extensionMethodLookup, semanticModel, excludeTypes, cancellationTokenSymbol, methodSyntax);

			validator.Visit(methodSyntax);

			return validator.results;
		}
Exemple #30
0
        public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            MethodWalker walker = this.CreateSyntaxWalker<MethodWalker>(node);
            walker.Visit(node);
            this.Methods.Add(walker);

            base.VisitMethodDeclaration(node);
        }
Exemple #31
0
        public static glsl.FunctionDeclarationSyntax Translate(this cs.MethodDeclarationSyntax node)
        {
            var functionDeclaration = new glsl.FunctionDeclarationSyntax();

            return(functionDeclaration.Update(
                       Translate(node.ReturnType),
                       node.Identifier,
                       Translate(node.ParameterList),
                       Translate(node.Body)
                       ));
        }
            public override void VisitMethodDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax node)
            {
                base.VisitMethodDeclaration(node);
                var body = node.Body;

                // partial/abstract method
                if (body == null)
                {
                    return;
                }
                VisitBody("Method", node.Identifier, body, semanticModel.GetDeclaredSymbol(node));
            }
        public override void VisitMethodDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax node)
        {
            var symbol = semanticModel.GetDeclaredSymbol(node);

            if (symbol != null && IsInactiveConditional(symbol))
            {
                Colorize(node, inactiveCodeColor);
            }
            else
            {
                base.VisitMethodDeclaration(node);
                Colorize(node.Identifier, methodDeclarationColor);
            }
        }
Exemple #34
0
        public static List <string> GetAttributesForMethod(CSharpSyntax.MethodDeclarationSyntax node)
        {
            var attributesList = new List <string>();

            foreach (CSharpSyntax.AttributeListSyntax attributeList in node.AttributeLists)
            {
                foreach (CSharpSyntax.AttributeSyntax attribute in attributeList.Attributes)
                {
                    attributesList.Add(attribute.Name.GetText().ToString());
                }
            }

            return(attributesList);
        }
            public override VisualBasicSyntaxNode VisitMethodDeclaration(CSS.MethodDeclarationSyntax node)
            {
                SyntaxList <StatementSyntax>?block = null;

                if (node.Body != null)
                {
                    block = SyntaxFactory.List(node.Body.Statements.SelectMany(s => s.Accept(new MethodBodyVisitor(semanticModel, this))));
                }
                var id         = SyntaxFactory.Identifier(node.Identifier.ValueText, SyntaxFacts.IsKeywordKind(node.Identifier.Kind()), node.Identifier.GetIdentifierText(), TypeCharacter.None);
                var methodInfo = semanticModel.GetDeclaredSymbol(node);

                if (methodInfo?.GetReturnType()?.SpecialType == SpecialType.System_Void)
                {
                    var stmt = SyntaxFactory.SubStatement(
                        SyntaxFactory.List(node.AttributeLists.Select(a => (AttributeListSyntax)a.Accept(this))),
                        ConvertModifiers(node.Modifiers, TokenContext.Member),
                        id, (TypeParameterListSyntax)node.TypeParameterList?.Accept(this),
                        (ParameterListSyntax)node.ParameterList?.Accept(this),
                        null, null, null
                        );
                    if (block == null)
                    {
                        return(stmt);
                    }
                    return(SyntaxFactory.SubBlock(stmt, block.Value));
                }
                else
                {
                    var stmt = SyntaxFactory.FunctionStatement(
                        SyntaxFactory.List(node.AttributeLists.Select(a => (AttributeListSyntax)a.Accept(this))),
                        ConvertModifiers(node.Modifiers, TokenContext.Member),
                        id, (TypeParameterListSyntax)node.TypeParameterList?.Accept(this),
                        (ParameterListSyntax)node.ParameterList?.Accept(this),
                        SyntaxFactory.SimpleAsClause((TypeSyntax)node.ReturnType.Accept(this)), null, null
                        );
                    if (block == null)
                    {
                        return(stmt);
                    }
                    return(SyntaxFactory.FunctionBlock(stmt, block.Value));
                }
            }
Exemple #36
0
        public static List <CSharpSyntax.AttributeSyntax> GetAttributesByName(string attributeName,
                                                                              CSharpSyntax.MethodDeclarationSyntax node)
        {
            var attributesList = new List <CSharpSyntax.AttributeSyntax>();

            if (node?.AttributeLists == null)
            {
                return(attributesList);
            }

            foreach (CSharpSyntax.AttributeListSyntax attributeList in node.AttributeLists)
            {
                foreach (CSharpSyntax.AttributeSyntax attribute in attributeList.Attributes)
                {
                    if (attribute.Name.GetText().ToString().Equals(attributeName))
                    {
                        attributesList.Add(attribute);
                    }
                }
            }

            return(attributesList);
        }
        private static void AnalyzeMethodTypeSymbol(SymbolAnalysisContext context, IMethodSymbol symbol)
        {
            if (symbol.MethodKind == MethodKind.PropertyGet ||
                symbol.MethodKind == MethodKind.PropertySet)
            {
                // Property getters/setters are handled via IPropertySymbol
                return;
            }

            if (IsInternal(context, symbol.ReturnType))
            {
                foreach (var declaringSyntax in symbol.DeclaringSyntaxReferences)
                {
                    var location = declaringSyntax.GetSyntax() switch
                    {
                        CSharpSyntax.MethodDeclarationSyntax s => s.ReturnType.GetLocation(),
                        { } otherSyntax => otherSyntax.GetLocation()
                    };

                    context.ReportDiagnostic(Diagnostic.Create(_descriptor, location, symbol.ReturnType));
                }
            }

            foreach (var paramSymbol in symbol.Parameters.Where(ps => IsInternal(context, ps.Type)))
            {
                foreach (var declaringSyntax in paramSymbol.DeclaringSyntaxReferences)
                {
                    var location = declaringSyntax.GetSyntax() switch
                    {
                        CSharpSyntax.ParameterSyntax s when s.Type != null => s.Type.GetLocation(),
                        { } otherSyntax => otherSyntax.GetLocation()
                    };

                    context.ReportDiagnostic(Diagnostic.Create(_descriptor, location, paramSymbol.Type));
                }
            }
        }
 public virtual void VisitEndMethodDeclaration(CSharpSyntax.MethodDeclarationSyntax node, ExecutionState state)
 {
 }
 public override void VisitEndMethodDeclaration(CSharpSyntax.MethodDeclarationSyntax node, ExecutionState state)
 {
     CheckState(state);
 }