本文整理汇总了C#中Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax类的典型用法代码示例。如果您正苦于以下问题:C# MethodDeclarationSyntax类的具体用法?C# MethodDeclarationSyntax怎么用?C# MethodDeclarationSyntax使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MethodDeclarationSyntax类属于Microsoft.CodeAnalysis.CSharp.Syntax命名空间,在下文中一共展示了MethodDeclarationSyntax类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: UpdateMainDocument
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;
}
示例2: GetPreconditions
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);
}
示例3: FindError
protected override string FindError(MethodDeclarationSyntax method)
{
var statements = method.Body.Statements;
return statements.Count != 1
|| !(statements.Single() is ReturnStatementSyntax)
? ShouldBeSingleMethodMessage : null;
}
示例4: CreateParameterClass
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)));
}
示例5: ReturnVoidAsync
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);
}
开发者ID:marcoparenzan,项目名称:CSharpDay2015,代码行数:25,代码来源:AggregateMethodMustReturnVoidOrSelfCodeFixProvider.cs
示例6: VisitMethodDeclaration
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));
}
示例7: VisitMethodDeclaration
public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
{
if (RequiresNullChecks(node.AttributeLists))
{
AddMessage(node, $"method {node.Identifier} needs null checks");
}
}
示例8: VisitMethodDeclaration
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;
}
}
示例9: RemoveAsyncAwait
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);
}
示例10: Run
public void Run(object testObject, MethodDeclarationSyntax method, SemanticModel semanticModel)
{
_semanticModel = semanticModel;
ExecuteSetup(testObject, method);
ExecuteTest(testObject, method);
ExecuteTearDown(testObject, method);
}
示例11: VisitMethodDeclaration
public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
{
var parameterTokens = node.ParameterList.Parameters.Select(p => p.Identifier);
tracker.AddIdentifiers(parameterTokens);
Visit(node.Body);
tracker.RemoveIdentifiers(parameterTokens);
}
示例12: CalculateForMethod
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);
}
示例13: VisitMethodDeclaration
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
));
}
示例14: HandleMethod
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);
}
示例15: RunTest
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;
}