本文整理汇总了C#中Microsoft.CodeAnalysis.SyntaxNode.WithAdditionalAnnotations方法的典型用法代码示例。如果您正苦于以下问题:C# SyntaxNode.WithAdditionalAnnotations方法的具体用法?C# SyntaxNode.WithAdditionalAnnotations怎么用?C# SyntaxNode.WithAdditionalAnnotations使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CodeAnalysis.SyntaxNode
的用法示例。
在下文中一共展示了SyntaxNode.WithAdditionalAnnotations方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Complexify
private SyntaxNode Complexify(SyntaxNode originalNode, SyntaxNode newNode)
{
_isProcessingComplexifiedSpans = true;
_modifiedSubSpans = new List<ValueTuple<TextSpan, TextSpan>>();
var annotation = new SyntaxAnnotation();
newNode = newNode.WithAdditionalAnnotations(annotation);
var speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
Debug.Assert(_speculativeModel != null, "expanding a syntax node which cannot be speculated?");
var oldSpan = originalNode.Span;
var expandParameter = originalNode.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).Count() == 0;
newNode = _simplificationService.Expand(newNode,
_speculativeModel,
annotationForReplacedAliasIdentifier: null,
expandInsideNode: null,
expandParameter: expandParameter,
cancellationToken: _cancellationToken);
speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
newNode = base.Visit(newNode);
var newSpan = newNode.Span;
newNode = newNode.WithoutAnnotations(annotation);
newNode = _renameAnnotations.WithAdditionalAnnotations(newNode, new RenameNodeSimplificationAnnotation() { OriginalTextSpan = oldSpan });
_renameSpansTracker.AddComplexifiedSpan(_documentId, oldSpan, new TextSpan(oldSpan.Start, newSpan.Length), _modifiedSubSpans);
_modifiedSubSpans = null;
_isProcessingComplexifiedSpans = false;
_speculativeModel = null;
return newNode;
}
示例2: RemoveThisQualifier
private Task<Document> RemoveThisQualifier(Document document, SyntaxNode root, SyntaxNode memberAccessNode)
{
return Task.FromResult(
document.WithSyntaxRoot(root.ReplaceNode(memberAccessNode, memberAccessNode.WithAdditionalAnnotations(Simplifier.Annotation))));
}
示例3: AnnotateNodeWithSimplifyAnnotation
private SyntaxNode AnnotateNodeWithSimplifyAnnotation(SyntaxNode node)
{
return node.WithAdditionalAnnotations(Simplifier.Annotation);
}
示例4: ApplyDocComment
private SyntaxNode ApplyDocComment(SyntaxNode node, string docCommentId)
{
if (docCommentId == null)
return node;
// Look up the comment text
string docCommentText = GetDocCommentForId(docCommentId);
// Get the SyntaxTrivia for the comment
SyntaxTree newTree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(docCommentText);
var newTrivia = newTree.GetRoot().GetLeadingTrivia();
if (node.HasLeadingTrivia)
{
SyntaxTriviaList triviaList = node.GetLeadingTrivia();
// Check to see if there are any existing doc comments
var docComments = triviaList
.Where(n => n.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia) || n.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia))
.Select(t => t.GetStructure())
.OfType<DocumentationCommentTriviaSyntax>()
.ToList();
// Append the doc comment (even if the API already has /// comments)
node = node.InsertTriviaBefore(triviaList.First(), newTrivia);
}
else // no leading trivia
{
node = node.WithLeadingTrivia(newTrivia);
}
return node.WithAdditionalAnnotations(Simplifier.Annotation);
}
示例5: GetUpdatedDocumentAsync
public override async Task<Document> GetUpdatedDocumentAsync(
Document document,
IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers,
INamedTypeSymbol classOrStructType,
SyntaxNode classOrStructDecl,
CancellationToken cancellationToken)
{
var result = document;
var compilation = await result.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
// Add an annotation to the type declaration node so that we can find it again to append the dispose pattern implementation below.
result = await result.ReplaceNodeAsync(
classOrStructDecl,
classOrStructDecl.WithAdditionalAnnotations(s_implementingTypeAnnotation),
cancellationToken).ConfigureAwait(false);
var root = await result.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
classOrStructDecl = root.GetAnnotatedNodes(s_implementingTypeAnnotation).Single();
compilation = await result.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
classOrStructType = classOrStructType.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).Symbol as INamedTypeSymbol;
// Use the code generation service to generate all unimplemented members except those that are
// part of the dispose pattern. We can't use the code generation service to implement the dispose
// pattern since the code generation service doesn't support injection of the custom boiler
// plate code required for implementing the dispose pattern.
var idisposable = TryGetSymbolForIDisposable(compilation);
result = await base.GetUpdatedDocumentAsync(
result,
unimplementedMembers.Where(m => !m.Item1.Equals(idisposable)).ToList(),
classOrStructType,
classOrStructDecl,
cancellationToken).ConfigureAwait(false);
// Now append the dispose pattern implementation.
root = await result.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
classOrStructDecl = root.GetAnnotatedNodes(s_implementingTypeAnnotation).Single();
compilation = await result.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
classOrStructType = classOrStructType.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).Symbol as INamedTypeSymbol;
result = Service.ImplementDisposePattern(result, root, classOrStructType, classOrStructDecl.SpanStart, Explicitly);
// Remove the annotation since we don't need it anymore.
root = await result.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
classOrStructDecl = root.GetAnnotatedNodes(s_implementingTypeAnnotation).Single();
result = await result.ReplaceNodeAsync(
classOrStructDecl,
classOrStructDecl.WithoutAnnotations(s_implementingTypeAnnotation),
cancellationToken).ConfigureAwait(false);
return result;
}
开发者ID:Rickinio,项目名称:roslyn,代码行数:49,代码来源:AbstractImplementInterfaceService.DisposePatternCodeAction.cs
示例6: AddNewMember
// public static IUnresolvedMember AddCodeDomMember (MonoDevelop.Projects.Project project, IUnresolvedTypeDefinition type, CodeTypeMember newMember)
// {
// bool isOpen;
// var data = TextFileProvider.Instance.GetTextEditorData (type.Region.FileName, out isOpen);
// var parsedDocument = TypeSystemService.ParseFile (data.FileName, data.MimeType, data.Text);
//
// var insertionPoints = GetInsertionPoints (data, parsedDocument, type);
//
// var suitableInsertionPoint = GetSuitableInsertionPoint (insertionPoints, type, newMember);
//
// var dotNetProject = project as DotNetProject;
// if (dotNetProject == null) {
// LoggingService.LogError ("Only .NET projects are supported.");
// return null;
// }
//
// var generator = dotNetProject.LanguageBinding.GetCodeDomProvider ();
// StringWriter sw = new StringWriter ();
// var options = new CodeGeneratorOptions ();
// options.IndentString = data.GetLineIndent (type.Region.BeginLine) + "\t";
// if (newMember is CodeMemberMethod)
// options.BracingStyle = "C";
// generator.GenerateCodeFromMember (newMember, sw, options);
//
// var code = sw.ToString ();
// if (!string.IsNullOrEmpty (code))
// suitableInsertionPoint.Insert (data, code);
// if (!isOpen) {
// try {
// File.WriteAllText (type.Region.FileName, data.Text);
// } catch (Exception e) {
// LoggingService.LogError (string.Format ("Failed to write file '{0}'.", type.Region.FileName), e);
// MessageService.ShowError (GettextCatalog.GetString ("Failed to write file '{0}'.", type.Region.FileName));
// }
// }
// var newDocument = TypeSystemService.ParseFile (data.FileName, data.MimeType, data.Text);
// return newDocument.ParsedFile.GetMember (suitableInsertionPoint.Location.Line, int.MaxValue);
// }
public static async Task AddNewMember (Projects.Project project, ITypeSymbol type, Location part, SyntaxNode newMember, CancellationToken cancellationToken = default(CancellationToken))
{
if (project == null)
throw new ArgumentNullException (nameof (project));
if (type == null)
throw new ArgumentNullException (nameof (type));
if (newMember == null)
throw new ArgumentNullException (nameof (newMember));
if (!type.IsDefinedInSource ())
throw new ArgumentException ("The given type needs to be defined in source code.", nameof (type));
var ws = MonoDevelop.Ide.TypeSystem.TypeSystemService.GetWorkspace (project.ParentSolution);
var projectId = ws.GetProjectId (project);
var docId = ws.GetDocumentId (projectId, part.SourceTree.FilePath);
var document = ws.GetDocument (docId, cancellationToken);
var root = await document.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false);
var typeDecl = (ClassDeclarationSyntax)root.FindNode (part.SourceSpan);
// for some reason the reducer doesn't reduce this
var systemVoid = newMember.DescendantNodesAndSelf ().OfType<QualifiedNameSyntax> ().FirstOrDefault (ma => ma.ToString () == "System.Void");
if (systemVoid != null) newMember = newMember.ReplaceNode (systemVoid, SyntaxFactory.ParseTypeName ("void"));
var newRoot = root.ReplaceNode (typeDecl, typeDecl.AddMembers ((MemberDeclarationSyntax)newMember.WithAdditionalAnnotations (Simplifier.Annotation, Formatter.Annotation)));
document = document.WithSyntaxRoot (newRoot);
var policy = project.Policies.Get<CSharpFormattingPolicy> ("text/x-csharp");
var textPolicy = project.Policies.Get<TextStylePolicy> ("text/x-csharp");
var projectOptions = policy.CreateOptions (textPolicy);
document = await Formatter.FormatAsync (document, Formatter.Annotation, projectOptions, cancellationToken).ConfigureAwait (false);
document = await Simplifier.ReduceAsync (document, Simplifier.Annotation, projectOptions, cancellationToken).ConfigureAwait (false);
var text = await document.GetTextAsync (cancellationToken).ConfigureAwait (false);
var newSolution = ws.CurrentSolution.WithDocumentText (docId, text);
ws.TryApplyChanges (newSolution);
}
示例7: InsertMemberWithCursor
public static async Task InsertMemberWithCursor (string operation, Projects.Project project, ITypeSymbol type, Location part, SyntaxNode newMember, CancellationToken cancellationToken = default(CancellationToken))
{
if (operation == null)
throw new ArgumentNullException (nameof (operation));
if (project == null)
throw new ArgumentNullException (nameof (project));
if (type == null)
throw new ArgumentNullException (nameof (type));
if (newMember == null)
throw new ArgumentNullException (nameof (newMember));
var ws = MonoDevelop.Ide.TypeSystem.TypeSystemService.GetWorkspace (project.ParentSolution);
var projectId = ws.GetProjectId (project);
var docId = ws.GetDocumentId (projectId, part.SourceTree.FilePath);
var document = ws.GetDocument (docId, cancellationToken);
var root = await document.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false);
var typeDecl = (ClassDeclarationSyntax)root.FindNode (part.SourceSpan);
// for some reason the reducer doesn't reduce this
var systemVoid = newMember.DescendantNodesAndSelf ().OfType<QualifiedNameSyntax> ().FirstOrDefault (ma => ma.ToString () == "System.Void");
if (systemVoid != null) newMember = newMember.ReplaceNode (systemVoid, SyntaxFactory.ParseTypeName ("void"));
var newRoot = root.ReplaceNode (typeDecl, typeDecl.AddMembers ((MemberDeclarationSyntax)newMember.WithAdditionalAnnotations (Simplifier.Annotation, Formatter.Annotation, insertedMemberAnnotation)));
var doc = await IdeApp.Workbench.OpenDocument (part.SourceTree.FilePath, project, true);
var policy = project.Policies.Get<CSharpFormattingPolicy> ("text/x-csharp");
var textPolicy = project.Policies.Get<TextStylePolicy> ("text/x-csharp");
var projectOptions = policy.CreateOptions (textPolicy);
document = document.WithSyntaxRoot (newRoot);
document = await Formatter.FormatAsync (document, Formatter.Annotation, projectOptions, cancellationToken).ConfigureAwait (false);
document = await Simplifier.ReduceAsync (document, Simplifier.Annotation, projectOptions, cancellationToken).ConfigureAwait (false);
root = await document.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false);
var node = root.GetAnnotatedNodes (insertedMemberAnnotation).Single ();
Application.Invoke (async delegate {
var insertionPoints = InsertionPointService.GetInsertionPoints (
doc.Editor,
await doc.UpdateParseDocument (),
type,
part.SourceSpan.Start
);
var options = new InsertionModeOptions (
operation,
insertionPoints,
point => {
if (!point.Success)
return;
var text = node.ToString ();
point.InsertionPoint.Insert (doc.Editor, doc, text);
}
);
doc.Editor.StartInsertionMode (options);
});
}
示例8: OutputNode
public async Task<string> OutputNode (SyntaxNode node, CancellationToken cancellationToken = default(CancellationToken))
{
node = Formatter.Format (node, TypeSystemService.Workspace, FormattingOptions, cancellationToken);
node = node.WithAdditionalAnnotations (Formatter.Annotation, Simplifier.Annotation);
var text = Editor.Text;
string nodeText = node.ToString ();
text = text.Insert (offset, nodeText);
var backgroundDocument = DocumentContext.AnalysisDocument.WithText (SourceText.From (text));
var currentRoot = await backgroundDocument.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false);
node = currentRoot.FindNode (TextSpan.FromBounds(offset, offset + nodeText.Length));
currentRoot = currentRoot.TrackNodes (node);
backgroundDocument = backgroundDocument.WithSyntaxRoot (currentRoot);
backgroundDocument = await Simplifier.ReduceAsync (backgroundDocument, TextSpan.FromBounds (offset, offset + nodeText.Length), FormattingOptions, cancellationToken).ConfigureAwait(false);
backgroundDocument = await Formatter.FormatAsync (backgroundDocument, Formatter.Annotation, FormattingOptions, cancellationToken).ConfigureAwait(false);
var newRoot = await backgroundDocument.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false);
var formattedNode = newRoot.GetCurrentNode (node);
if (formattedNode == null) {
LoggingService.LogError ("Fatal error: Can't find current formatted node in code generator document.");
return nodeText;
}
return formattedNode.ToString ();
}