本文整理汇总了C#中Microsoft.CodeAnalysis.Document.GetSyntaxTreeAsync方法的典型用法代码示例。如果您正苦于以下问题:C# Document.GetSyntaxTreeAsync方法的具体用法?C# Document.GetSyntaxTreeAsync怎么用?C# Document.GetSyntaxTreeAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CodeAnalysis.Document
的用法示例。
在下文中一共展示了Document.GetSyntaxTreeAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetSyntaxTreeSynchronously
public static SyntaxTree GetSyntaxTreeSynchronously(Document document, CancellationToken cancellationToken) {
//TODO: Roslyn 2.0: use document.GetSyntaxTreeSynchronously()
SyntaxTree syntaxTree;
if (document.TryGetSyntaxTree(out syntaxTree))
return syntaxTree;
return document.GetSyntaxTreeAsync(cancellationToken).GetAwaiter().GetResult();
}
示例2: GetAdjustedContextPoint
protected override int GetAdjustedContextPoint(int contextPoint, Document document)
{
// Determine the position in the buffer at which to end the tracking span representing
// the part of the imagininary buffer before the text in the view.
var tree = document.GetSyntaxTreeAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var token = tree.FindTokenOnLeftOfPosition(contextPoint, CancellationToken.None);
// Special case to handle class designer because it asks for debugger IntelliSense using
// spans between members.
if (contextPoint > token.Span.End &&
token.IsKindOrHasMatchingText(SyntaxKind.CloseBraceToken) &&
token.Parent.IsKind(SyntaxKind.Block) &&
token.Parent.Parent is MemberDeclarationSyntax)
{
return contextPoint;
}
if (token.IsKindOrHasMatchingText(SyntaxKind.CloseBraceToken) &&
token.Parent.IsKind(SyntaxKind.Block))
{
return token.SpanStart;
}
return token.FullSpan.End;
}
示例3: GetItemAsync
public async Task<QuickInfoItem> GetItemAsync(
Document document,
int position,
CancellationToken cancellationToken)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = await tree.GetTouchingTokenAsync(position, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var state = await GetQuickInfoItemAsync(document, token, position, cancellationToken).ConfigureAwait(false);
if (state != null)
{
return state;
}
if (ShouldCheckPreviousToken(token))
{
var previousToken = token.GetPreviousToken();
if ((state = await GetQuickInfoItemAsync(document, previousToken, position, cancellationToken).ConfigureAwait(false)) != null)
{
return state;
}
}
return null;
}
示例4: InternalGetParameterDataProviderAsync
public async Task<ParameterHintingResult> InternalGetParameterDataProviderAsync (Document document, SemanticModel semanticModel, int position, CancellationToken cancellationToken, int recCount)
{
if (position == 0 || recCount > 1)
return ParameterHintingResult.Empty;
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var tokenLeftOfPosition = tree.FindTokenOnLeftOfPosition (position, cancellationToken);
if (tokenLeftOfPosition.IsKind (SyntaxKind.LessThanToken)) {
var startToken = tokenLeftOfPosition.GetPreviousToken();
return HandleTypeParameterCase(semanticModel, startToken.Parent, cancellationToken);
}
var context = SyntaxContext.Create(workspace, document, semanticModel, position, cancellationToken);
var targetParent = context.TargetToken.Parent;
if (targetParent == null)
return ParameterHintingResult.Empty;
if (context.TargetToken.IsKind (SyntaxKind.IdentifierName)) {
targetParent = targetParent.Parent;
}
if (context.TargetToken.IsKind (SyntaxKind.CloseParenToken) || context.TargetToken.IsKind (SyntaxKind.CloseBracketToken) || context.TargetToken.IsKind (SyntaxKind.GreaterThanToken))
targetParent = targetParent.Parent;
var node = targetParent.Parent;
// case: identifier<arg1,|
if (node == null) {
if (context.LeftToken.Kind() == SyntaxKind.CommaToken) {
targetParent = context.LeftToken.GetPreviousToken().Parent;
node = targetParent.Parent;
if (node.Kind() == SyntaxKind.LessThanExpression) {
return HandleTypeParameterCase(semanticModel, ((BinaryExpressionSyntax)node).Left, cancellationToken);
}
}
return ParameterHintingResult.Empty;
}
if (node.IsKind (SyntaxKind.Argument)) {
node = node.Parent.Parent;
} else {
if (!(targetParent is BaseArgumentListSyntax) && !(targetParent is AttributeArgumentListSyntax) && !(targetParent is InitializerExpressionSyntax)) {
if (position == targetParent.Span.Start)
return ParameterHintingResult.Empty;
return await InternalGetParameterDataProviderAsync (document, semanticModel, targetParent.Span.Start, cancellationToken, recCount + 1).ConfigureAwait (false);
}
}
switch (node.Kind()) {
case SyntaxKind.Attribute:
return HandleAttribute(semanticModel, node, cancellationToken);
case SyntaxKind.ThisConstructorInitializer:
case SyntaxKind.BaseConstructorInitializer:
return HandleConstructorInitializer(semanticModel, node, cancellationToken);
case SyntaxKind.ObjectCreationExpression:
return HandleObjectCreationExpression(semanticModel, node, cancellationToken);
case SyntaxKind.InvocationExpression:
return HandleInvocationExpression(semanticModel, (InvocationExpressionSyntax)node, cancellationToken);
case SyntaxKind.ElementAccessExpression:
return HandleElementAccessExpression(semanticModel, (ElementAccessExpressionSyntax)node, cancellationToken);
}
return ParameterHintingResult.Empty;
}
示例5: RemoveUnnecessaryUsings
private static Document RemoveUnnecessaryUsings(Document doc, Compilation compilation)
{
#region CodeContracts
Contract.Requires(doc != null);
Contract.Requires(compilation != null);
Contract.Ensures(Contract.Result<Document>() != null);
#endregion CodeContracts
var st = doc.GetSyntaxTreeAsync().Result;
var sm = doc.GetSemanticModelAsync().Result;
//var assembly = Assembly.LoadFrom(@"C:\cci\Microsoft.Research\Imported\Tools\Roslyn\v4.5.1\Microsoft.CodeAnalysis.CSharp.Features.dll");
//var assembly = Assembly.LoadFrom(@"C:\cci\Microsoft.Research\CCTools\ReviewBot\bin\Debug\Microsoft.CodeAnalysis.CSharp.Features.dll");
//var assembly = Assembly.LoadFrom(@"..\..\..\packages\Microsoft.CodeAnalysis.Features.0.7.4040207-beta\lib\net45\Microsoft.CodeAnalysis.CSharp.Features.dll");
//var assembly = Assembly.LoadFrom(@"C:\Users\t-scottc\Desktop\Signed_20140201.1\Microsoft.CodeAnalysis.CSharp.Features.dll");
//var assembly = Assembly.LoadFrom(@"C:\Users\t-scottc\workspace\roslyn\Binaries\Debug\Microsoft.CodeAnalysis.CSharp.Workspaces.dll");
Assembly assembly;
if (TryGetMicrosoftCodeAnalysisCSharpFeatures(out assembly))
{
var type = assembly.GetType("Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryImports.CSharpRemoveUnnecessaryImportsService");
var method = type.GetMethod("RemoveUnnecessaryImports");
var service = Activator.CreateInstance(type);
return method.Invoke(service, new object[] { doc, sm, st.GetRoot(), CancellationToken.None }) as Document;
}
else
{
Output.WriteWarning("Can't run the refactoring to remove using");
return doc;
}
}
示例6: AnalyzeSyntaxAsync
public async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
if (!document.SupportsSyntaxTree)
{
return;
}
// getting tree is cheap since tree always stays in memory
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var length = tree.Length;
while (true)
{
if (_map.TryAdd(document.Id, length))
{
Interlocked.Add(ref _size, length);
return;
}
long size;
if (_map.TryGetValue(document.Id, out size))
{
if (size == length)
{
return;
}
if (_map.TryUpdate(document.Id, length, size))
{
Interlocked.Add(ref _size, length - size);
return;
}
}
}
}
示例7: GetFormattingChangesAfterKeystroke
public static async Task<IEnumerable<LinePositionSpanTextChange>> GetFormattingChangesAfterKeystroke(Workspace workspace, OptionSet options, Document document, int position, char character)
{
var tree = await document.GetSyntaxTreeAsync();
if (character == '\n')
{
// format previous line on new line
var lines = (await document.GetTextAsync()).Lines;
var targetLine = lines[lines.GetLineFromPosition(position).LineNumber - 1];
if (!string.IsNullOrWhiteSpace(targetLine.Text.ToString(targetLine.Span)))
{
return await GetFormattingChangesForRange(workspace, options, document, targetLine.Start, targetLine.End);
}
}
else if (character == '}' || character == ';')
{
// format after ; and }
var node = FindFormatTarget(tree, position);
if (node != null)
{
return await GetFormattingChangesForRange(workspace, options, document, node.FullSpan.Start, node.FullSpan.End);
}
}
return Enumerable.Empty<LinePositionSpanTextChange>();
}
示例8: MoveClassIntoNewFileAsync
async Task<Solution> MoveClassIntoNewFileAsync(Document document, ClassStatementSyntax typeDecl, string className, CancellationToken cancellationToken)
{
// symbol representing the type
var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
var typeSymbol = semanticModel.GetDeclaredSymbol(typeDecl, cancellationToken);
// remove type from current files
var currentSyntaxTree = await document.GetSyntaxTreeAsync();
var currentRoot = await currentSyntaxTree.GetRootAsync();
//In VB you have to remove th parent of det declaration node. That is the "ClassBlockSyntax"
var replacedRoot = currentRoot.RemoveNode(typeDecl.Parent, SyntaxRemoveOptions.KeepNoTrivia);
document = document.WithSyntaxRoot(replacedRoot);
// create new tree for a new file
// we drag all the imports because we don't know which are needed
// and there is no easy way to find out which
var currentUsings = currentRoot.DescendantNodesAndSelf().Where(s => s is ImportsStatementSyntax);
var currentNs = (NamespaceStatementSyntax)currentRoot.DescendantNodesAndSelf().First(s => s is NamespaceStatementSyntax);
SyntaxList<StatementSyntax> c;
if(currentNs != null)
{
//We have to wrap the content of the class in the namespace.
var temp = SyntaxFactory.SingletonList(
SyntaxFactory.NamespaceBlock(
SyntaxFactory.NamespaceStatement(SyntaxFactory.ParseName(currentNs.Name.ToString())),
SyntaxFactory.SingletonList(typeDecl.Parent),
SyntaxFactory.EndNamespaceStatement()
));
c = SyntaxFactory.List(temp.Select(i => ((StatementSyntax)i)));
}
else
{
c = SyntaxFactory.SingletonList(typeDecl.Parent);
}
var newFileTree = SyntaxFactory.CompilationUnit()
.WithImports(SyntaxFactory.List(currentUsings.Select(i => ((ImportsStatementSyntax)i))))
.WithMembers(c)
.WithoutLeadingTrivia()
.NormalizeWhitespace();
var codeText = newFileTree.ToFullString();
//TODO: handle name conflicts
var newDocument = document.Project.AddDocument(className, SourceText.From(codeText), document.Folders);
newDocument = await RemoveUnusedImportDirectivesAsync(newDocument, cancellationToken);
return newDocument.Project.Solution;
}
示例9: AddMissingEnumFields
//--- Class Methods ---
private static async Task<Document> AddMissingEnumFields(Document document, SyntaxToken typeDecl, CancellationToken cancellationToken) {
var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
var node = (SwitchStatementSyntax)typeDecl.Parent;
IdentifierNameSyntax switchVariable;
var missingMembers = EnumSwitchAnalysis.GetMissingEnumMembers(node, semanticModel, out switchVariable);
if(missingMembers.Any()) {
// get existing switchSections
var existingSections = node.Sections.ToList();
SwitchSectionSyntax defaultSection = null;
if(existingSections.Any() && existingSections.Last().DescendantNodes().OfType<DefaultSwitchLabelSyntax>().Any()) {
defaultSection = existingSections.Last();
existingSections = existingSections.Take(existingSections.Count - 1).ToList();
}
// generate missing case statements
var switchVariableTypeInfo = semanticModel.GetTypeInfo(switchVariable);
var newCaseStatements = missingMembers.Select(missingMember =>
SyntaxFactory.CaseSwitchLabel(
SyntaxFactory.Token(SyntaxKind.CaseKeyword),
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName(switchVariableTypeInfo.Type.Name),
SyntaxFactory.IdentifierName(missingMember.Name)
),
SyntaxFactory.Token(SyntaxKind.ColonToken)
)
).Select(caseSection => SyntaxFactory.SwitchSection(
SyntaxFactory.List<SwitchLabelSyntax>(new[] { caseSection }),
SyntaxFactory.List<StatementSyntax>().Add(
SyntaxFactory.ThrowStatement(
SyntaxFactory.ObjectCreationExpression(
SyntaxFactory.ParseTypeName(nameof(NotImplementedException)),
SyntaxFactory.ArgumentList(),
null
)
)
)
)).ToImmutableArray();
// insert case statements after the last one
var tree = await document.GetSyntaxTreeAsync(cancellationToken);
var root = (CompilationUnitSyntax)tree.GetRoot(cancellationToken);
var switchStatement = SyntaxFactory.SwitchStatement(
SyntaxFactory.IdentifierName(switchVariable.Identifier)
.WithLeadingTrivia(switchVariable.GetLeadingTrivia())
.WithTrailingTrivia(switchVariable.GetTrailingTrivia())
).WithSections(
new SyntaxList<SwitchSectionSyntax>()
.AddRange(existingSections)
.AddRange(newCaseStatements)
.AddRange(defaultSection == null ? Enumerable.Empty<SwitchSectionSyntax>() : new [] { defaultSection })
).WithLeadingTrivia(node.GetLeadingTrivia())
.WithTrailingTrivia(node.GetTrailingTrivia());
root = root.ReplaceNode(node, switchStatement);
return document.WithSyntaxRoot(root);
}
return document;
}
示例10: GetProximityExpressionsAsync
public async Task<IList<string>> GetProximityExpressionsAsync(
Document document,
int position,
CancellationToken cancellationToken)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
return Do(tree, position, cancellationToken);
}
示例11: IsExclusiveAsync
protected override async Task<bool> IsExclusiveAsync(Document document, int caretPosition, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = syntaxTree.FindTokenOnLeftOfPosition(caretPosition, cancellationToken)
.GetPreviousTokenIfTouchingWord(caretPosition);
return IsAfterNameColonArgument(token) || IsAfterNameEqualsArgument(token);
}
示例12: AugmentSelection
/// <summary>
/// The entry point to Gistify's engine. Takes the document and the extent of the selection,
/// and outputs the augmented snippet.
/// </summary>
/// <param name="document"></param>
/// <param name="startPosition"></param>
/// <param name="endPosition"></param>
/// <returns>String with the augmented snippet.</returns>
public static string AugmentSelection(Document document, int startPosition, int endPosition)
{
var tree = document.GetSyntaxTreeAsync().Result;
var model = document.GetSemanticModelAsync().Result;
var objectInfos = DiscoveryWalker.FindObjects(tree, model, startPosition, endPosition);
var augmentedSelection = SyntaxBuilder.AugmentSnippet(objectInfos, tree, startPosition, endPosition);
return augmentedSelection;
}
示例13: GetHelpTermAsync
public override async Task<string> GetHelpTermAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
// For now, find the token under the start of the selection.
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = syntaxTree.GetTouchingToken(span.Start, cancellationToken, findInsideTrivia: true);
if (IsValid(token, span))
{
var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
var result = TryGetText(token, semanticModel, document, cancellationToken, syntaxFacts);
if (string.IsNullOrEmpty(result))
{
var previousToken = token.GetPreviousToken();
if (IsValid(previousToken, span))
{
result = TryGetText(previousToken, semanticModel, document, cancellationToken, syntaxFacts);
}
}
return result;
}
var trivia = root.FindTrivia(span.Start, findInsideTrivia: true);
if (trivia.Span.IntersectsWith(span) && trivia.Kind() == SyntaxKind.PreprocessingMessageTrivia &&
trivia.Token.GetAncestor<RegionDirectiveTriviaSyntax>() != null)
{
return "#region";
}
if (trivia.IsRegularOrDocComment())
{
// just find the first "word" that intersects with our position
var text = await syntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
int start = span.Start;
int end = span.Start;
while (start > 0 && syntaxFacts.IsIdentifierPartCharacter(text[start - 1]))
{
start--;
}
while (end < text.Length - 1 && syntaxFacts.IsIdentifierPartCharacter(text[end]))
{
end++;
}
return text.GetSubText(TextSpan.FromBounds(start, end)).ToString();
}
return string.Empty;
}
示例14: ExplodePropertyAsync
private async Task<Document> ExplodePropertyAsync(SyntaxNode oldRoot, Document document, PropertyDeclarationSyntax property, CancellationToken cancellationToken)
{
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
// Call the Property Exploder. The code refactoring happens here.
var expander = new PropertyExploder(property.Parent, property);
var newRoot = expander.Visit(oldRoot);
// Update code with the refactored Root
return document.WithSyntaxRoot(newRoot);
}
示例15: ReplaceEmptyStringWithStringEmpty
private async Task<Document> ReplaceEmptyStringWithStringEmpty(Document document, SyntaxNode oldNode, CancellationToken cancellationToken)
{
// NOTE: string.Empty
var stringType = SF.PredefinedType(SF.Token(SyntaxKind.StringKeyword));
var empty = SF.IdentifierName("Empty");
var stringEmpty = SF.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, stringType, SF.Token(SyntaxKind.DotToken), empty);
var tree = await document.GetSyntaxTreeAsync();
var node = tree.GetRoot().ReplaceNode(oldNode, stringEmpty);
return document.WithSyntaxRoot(node);
}