本文整理汇总了C#中Document.GetLanguageService方法的典型用法代码示例。如果您正苦于以下问题:C# Document.GetLanguageService方法的具体用法?C# Document.GetLanguageService怎么用?C# Document.GetLanguageService使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Document
的用法示例。
在下文中一共展示了Document.GetLanguageService方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetItemsWorkerAsync
protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
ObjectCreationExpressionSyntax objectCreationExpression;
if (!TryGetObjectCreationExpression(root, position, document.GetLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out objectCreationExpression))
{
return null;
}
var semanticModel = await document.GetSemanticModelForNodeAsync(objectCreationExpression, cancellationToken).ConfigureAwait(false);
var type = semanticModel.GetTypeInfo(objectCreationExpression, cancellationToken).Type as INamedTypeSymbol;
if (type == null)
{
return null;
}
var within = semanticModel.GetEnclosingNamedType(position, cancellationToken);
if (within == null)
{
return null;
}
var symbolDisplayService = document.Project.LanguageServices.GetService<ISymbolDisplayService>();
var anonymousTypeDisplayService = document.Project.LanguageServices.GetService<IAnonymousTypeDisplayService>();
var documentationCommentFormattingService = document.Project.LanguageServices.GetService<IDocumentationCommentFormattingService>();
var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(objectCreationExpression.ArgumentList);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
return CreateSignatureHelpItems(type.TypeKind == TypeKind.Delegate
? GetDelegateTypeConstructors(objectCreationExpression, semanticModel, symbolDisplayService, anonymousTypeDisplayService, type, within, cancellationToken)
: GetNormalTypeConstructors(document, objectCreationExpression, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, type, within, cancellationToken),
textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken));
}
示例2: GetSnippetsForDocumentAsync
private async Task<IEnumerable<CompletionItem>> GetSnippetsForDocumentAsync(
Document document, int position, Workspace workspace, CancellationToken cancellationToken)
{
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
if (syntaxFacts.IsInNonUserCode(syntaxTree, position, cancellationToken) ||
syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken) ||
syntaxFacts.GetContainingTypeDeclaration(await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false), position) is EnumDeclarationSyntax)
{
return SpecializedCollections.EmptyEnumerable<CompletionItem>();
}
var span = new TextSpan(position, 0);
var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
var isPossibleTupleContext = syntaxFacts.IsPossibleTupleContext(syntaxTree, position, cancellationToken);
if (semanticFacts.IsPreProcessorDirectiveContext(semanticModel, position, cancellationToken))
{
var directive = syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition(position, includeDirectives: true).GetAncestor<DirectiveTriviaSyntax>();
if (directive.DirectiveNameToken.IsKind(
SyntaxKind.IfKeyword,
SyntaxKind.RegionKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.ElifKeyword,
SyntaxKind.ErrorKeyword,
SyntaxKind.LineKeyword,
SyntaxKind.PragmaKeyword,
SyntaxKind.EndIfKeyword,
SyntaxKind.UndefKeyword,
SyntaxKind.EndRegionKeyword,
SyntaxKind.WarningKeyword))
{
return SpecializedCollections.EmptyEnumerable<CompletionItem>();
}
return await GetSnippetCompletionItemsAsync(workspace, semanticModel, isPreProcessorContext: true,
isTupleContext: isPossibleTupleContext, cancellationToken: cancellationToken).ConfigureAwait(false);
}
if (semanticFacts.IsGlobalStatementContext(semanticModel, position, cancellationToken) ||
semanticFacts.IsExpressionContext(semanticModel, position, cancellationToken) ||
semanticFacts.IsStatementContext(semanticModel, position, cancellationToken) ||
semanticFacts.IsTypeContext(semanticModel, position, cancellationToken) ||
semanticFacts.IsTypeDeclarationContext(semanticModel, position, cancellationToken) ||
semanticFacts.IsNamespaceContext(semanticModel, position, cancellationToken) ||
semanticFacts.IsNamespaceDeclarationNameContext(semanticModel, position, cancellationToken) ||
semanticFacts.IsMemberDeclarationContext(semanticModel, position, cancellationToken) ||
semanticFacts.IsLabelContext(semanticModel, position, cancellationToken))
{
return await GetSnippetCompletionItemsAsync(workspace, semanticModel, isPreProcessorContext: false,
isTupleContext: isPossibleTupleContext, cancellationToken: cancellationToken).ConfigureAwait(false);
}
return SpecializedCollections.EmptyEnumerable<CompletionItem>();
}
示例3: GetCompletionListAsync
/// <summary>
/// Returns the <see cref="CompletionList"/> for the specified <paramref name="position"/>
/// in the <paramref name="document"/>.
/// </summary>
public static Task<CompletionList> GetCompletionListAsync(
Document document,
int position,
CompletionTriggerInfo triggerInfo,
OptionSet options = null,
IEnumerable<CompletionListProvider> providers = null,
CancellationToken cancellationToken = default(CancellationToken))
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
var completionService = document.GetLanguageService<ICompletionService>();
if (completionService != null)
{
options = options ?? document.Project.Solution.Workspace.Options;
providers = providers ?? GetDefaultCompletionListProviders(document);
return completionService.GetCompletionListAsync(document, position, triggerInfo, options, providers, cancellationToken);
}
else
{
if (s_emptyCompletionListTask == null)
{
var value = Task.FromResult(new CompletionList(ImmutableArray<CompletionItem>.Empty));
Interlocked.CompareExchange(ref s_emptyCompletionListTask, value, null);
}
return s_emptyCompletionListTask;
}
}
示例4: IsThirdPartyNavigationAllowed
private static bool IsThirdPartyNavigationAllowed(ISymbol symbolToNavigateTo, int caretPosition, Document document, CancellationToken cancellationToken)
{
var syntaxRoot = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();
var containingTypeDeclaration = syntaxFactsService.GetContainingTypeDeclaration(syntaxRoot, caretPosition);
if (containingTypeDeclaration != null)
{
var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var containingTypeSymbol = semanticModel.GetDeclaredSymbol(containingTypeDeclaration, cancellationToken) as ITypeSymbol;
// Allow third parties to navigate to all symbols except types/constructors
// if we are navigating from the corresponding type.
if (containingTypeSymbol != null &&
(symbolToNavigateTo is ITypeSymbol || symbolToNavigateTo.IsConstructor()))
{
var candidateTypeSymbol = symbolToNavigateTo is ITypeSymbol
? symbolToNavigateTo
: symbolToNavigateTo.ContainingType;
if (containingTypeSymbol == candidateTypeSymbol)
{
// We are navigating from the same type, so don't allow third parties to perform the navigation.
// This ensures that if we navigate to a class from within that class, we'll stay in the same file
// rather than navigate to, say, XAML.
return false;
}
}
}
return true;
}
示例5: AddSourceToAsync
public async Task<Document> AddSourceToAsync(Document document, ISymbol symbol, CancellationToken cancellationToken)
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
var newSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var rootNamespace = newSemanticModel.GetEnclosingNamespace(0, cancellationToken);
// Add the interface of the symbol to the top of the root namespace
document = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync(
document.Project.Solution,
rootNamespace,
CreateCodeGenerationSymbol(document, symbol),
CreateCodeGenerationOptions(newSemanticModel.SyntaxTree.GetLocation(new TextSpan()), symbol),
cancellationToken).ConfigureAwait(false);
var docCommentFormattingService = document.GetLanguageService<IDocumentationCommentFormattingService>();
var docWithDocComments = await ConvertDocCommentsToRegularComments(document, docCommentFormattingService, cancellationToken).ConfigureAwait(false);
var docWithAssemblyInfo = await AddAssemblyInfoRegionAsync(docWithDocComments, symbol.GetOriginalUnreducedDefinition(), cancellationToken).ConfigureAwait(false);
var node = await docWithAssemblyInfo.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formattedDoc = await Formatter.FormatAsync(
docWithAssemblyInfo, SpecializedCollections.SingletonEnumerable(node.FullSpan), options: null, rules: GetFormattingRules(docWithAssemblyInfo), cancellationToken: cancellationToken).ConfigureAwait(false);
var reducers = this.GetReducers();
return await Simplifier.ReduceAsync(formattedDoc, reducers, null, cancellationToken).ConfigureAwait(false);
}
示例6: FixAllAsync
protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var generator = editor.Generator;
var root = editor.OriginalRoot;
foreach (var diagnostic in diagnostics)
{
var conditionalExpression = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true);
var conditionExpression = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan);
var whenPart = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan);
syntaxFacts.GetPartsOfConditionalExpression(
conditionalExpression, out var condition, out var whenTrue, out var whenFalse);
editor.ReplaceNode(conditionalExpression,
(c, g) => {
syntaxFacts.GetPartsOfConditionalExpression(
c, out var currentCondition, out var currentWhenTrue, out var currentWhenFalse);
return whenPart == whenTrue
? g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenTrue))
: g.CoalesceExpression(conditionExpression, syntaxFacts.WalkDownParentheses(currentWhenFalse));
});
}
return SpecializedTasks.EmptyTask;
}
示例7: StartInlineSession
public InlineRenameSessionInfo StartInlineSession(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken)
{
if (_activeRenameSession != null)
{
throw new InvalidOperationException(EditorFeaturesResources.AnActiveInlineRenameSessionIsActive);
}
var editorRenameService = document.GetLanguageService<IEditorInlineRenameService>();
var renameInfo = editorRenameService.GetRenameInfoAsync(document, textSpan.Start, cancellationToken).WaitAndGetResult(cancellationToken);
if (!renameInfo.CanRename)
{
return new InlineRenameSessionInfo(renameInfo.LocalizedErrorMessage);
}
var snapshot = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).FindCorrespondingEditorTextSnapshot();
ActiveSession = new InlineRenameSession(
this,
document.Project.Solution.Workspace,
renameInfo.TriggerSpan.ToSnapshotSpan(snapshot),
renameInfo,
_waitIndicator,
_textBufferAssociatedViewService,
_textBufferFactoryService,
_refactorNotifyServices,
_aggregateListener);
return new InlineRenameSessionInfo(ActiveSession);
}
示例8: GetDesiredIndentation
public IndentationResult? GetDesiredIndentation(
Document document, int lineNumber, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var sourceText = root.SyntaxTree.GetText(cancellationToken);
var documentOptions = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var lineToBeIndented = sourceText.Lines[lineNumber];
var formattingRules = GetFormattingRules(document, lineToBeIndented.Start);
// There are two important cases for indentation. The first is when we're simply
// trying to figure out the appropriate indentation on a blank line (i.e. after
// hitting enter at the end of a line, or after moving to a blank line). The
// second is when we're trying to figure out indentation for a non-blank line
// (i.e. after hitting enter in the middle of a line, causing tokens to move to
// the next line). If we're in the latter case, we defer to the Formatting engine
// as we need it to use all its rules to determine where the appropriate location is
// for the following tokens to go.
if (ShouldUseSmartTokenFormatterInsteadOfIndenter(formattingRules, root, lineToBeIndented, documentOptions, cancellationToken))
{
return null;
}
var indenter = GetIndenter(
document.GetLanguageService<ISyntaxFactsService>(),
root.SyntaxTree, lineToBeIndented, formattingRules,
documentOptions, cancellationToken);
return indenter.GetDesiredIndentation(document);
}
示例9: AddSyntacticClassificationsAsync
public async Task AddSyntacticClassificationsAsync(Document document, TextSpan textSpan, List<ClassifiedSpan> result, CancellationToken cancellationToken)
{
var classificationService = document.GetLanguageService<IClassificationService>();
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
classificationService.AddSyntacticClassifications(syntaxTree, textSpan, result, cancellationToken);
}
示例10: GetUpdatedDocumentAsync
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
// if nothing can be fixed, return the unchanged node
var newRoot = root;
var kind = nodeToFix.CSharpKind();
var syntaxFactoryService = document.GetLanguageService<SyntaxGenerator>();
switch (kind)
{
case SyntaxKind.Argument:
// StringComparison.CurrentCulture => StringComparison.Ordinal
// StringComparison.CurrentCultureIgnoreCase => StringComparison.OrdinalIgnoreCase
var argument = (ArgumentSyntax)nodeToFix;
var memberAccess = argument.Expression as MemberAccessExpressionSyntax;
if (memberAccess != null)
{
// preserve the "IgnoreCase" suffix if present
bool isIgnoreCase = memberAccess.Name.GetText().ToString().EndsWith(CA1309DiagnosticAnalyzer.IgnoreCaseText);
var newOrdinalText = isIgnoreCase ? CA1309DiagnosticAnalyzer.OrdinalIgnoreCaseText : CA1309DiagnosticAnalyzer.OrdinalText;
var newIdentifier = syntaxFactoryService.IdentifierName(newOrdinalText);
var newMemberAccess = memberAccess.WithName((SimpleNameSyntax)newIdentifier).WithAdditionalAnnotations(Formatter.Annotation);
newRoot = root.ReplaceNode(memberAccess, newMemberAccess);
}
break;
case SyntaxKind.IdentifierName:
// string.Equals(a, b) => string.Equals(a, b, StringComparison.Ordinal)
// string.Compare(a, b) => string.Compare(a, b, StringComparison.Ordinal)
var identifier = (IdentifierNameSyntax)nodeToFix;
var invokeParent = identifier.GetAncestor<InvocationExpressionSyntax>();
if (invokeParent != null)
{
var methodSymbol = model.GetSymbolInfo(identifier).Symbol as IMethodSymbol;
if (methodSymbol != null && CanAddStringComparison(methodSymbol))
{
// append a new StringComparison.Ordinal argument
var newArg = syntaxFactoryService.Argument(CreateOrdinalMemberAccess(syntaxFactoryService, model))
.WithAdditionalAnnotations(Formatter.Annotation);
var newInvoke = invokeParent.AddArgumentListArguments((ArgumentSyntax)newArg).WithAdditionalAnnotations(Formatter.Annotation);
newRoot = root.ReplaceNode(invokeParent, newInvoke);
}
}
break;
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
// "a == b" => "string.Equals(a, b, StringComparison.Ordinal)"
// "a != b" => "!string.Equals(a, b, StringComparison.Ordinal)"
var binaryExpression = (BinaryExpressionSyntax)nodeToFix;
var invocation = CreateEqualsExpression(syntaxFactoryService, model, binaryExpression.Left, binaryExpression.Right, kind == SyntaxKind.EqualsExpression).WithAdditionalAnnotations(Formatter.Annotation);
newRoot = root.ReplaceNode(nodeToFix, invocation);
break;
}
if (newRoot == root)
{
return Task.FromResult(document);
}
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
示例11: GetDiagnosticsAsync
protected override async Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync(Document document, CancellationToken cancellationToken = default(CancellationToken))
{
if (!document.IsOpen())
{
return null;
}
if (document.SourceCodeKind == SourceCodeKind.Interactive)
{
// It's common to type usings in a submission that are intended for a future
// submission. We do not want to offer to remove these.
return null;
}
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var service = document.GetLanguageService<IRemoveUnnecessaryImportsService>();
var unnecessaryUsings = service.GetUnnecessaryImports(document, model, model.SyntaxTree.GetRoot(cancellationToken), cancellationToken);
if (unnecessaryUsings == null)
{
return null;
}
var contiguousSpans = unnecessaryUsings.GetContiguousSpans();
return CreateClassificationDiagnostics(contiguousSpans, model, document, cancellationToken).Concat(
CreateFixableDiagnostics(unnecessaryUsings, model, document, cancellationToken));
}
示例12: ImplementAbstractClassAsync
private async Task<Document> ImplementAbstractClassAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IImplementAbstractClassService>();
return await service.ImplementAbstractClassAsync(
document,
await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false),
node,
cancellationToken).ConfigureAwait(false);
}
示例13: CreateCodeGenerationSymbol
private static INamespaceOrTypeSymbol CreateCodeGenerationSymbol(Document document, ISymbol symbol)
{
symbol = symbol.GetOriginalUnreducedDefinition();
var topLevelNamespaceSymbol = symbol.ContainingNamespace;
var topLevelNamedType = MetadataAsSourceHelpers.GetTopLevelContainingNamedType(symbol);
var canImplementImplicitly = document.GetLanguageService<ISemanticFactsService>().SupportsImplicitInterfaceImplementation;
var docCommentFormattingService = document.GetLanguageService<IDocumentationCommentFormattingService>();
INamespaceOrTypeSymbol wrappedType = new WrappedNamedTypeSymbol(topLevelNamedType, canImplementImplicitly, docCommentFormattingService);
return topLevelNamespaceSymbol.IsGlobalNamespace
? wrappedType
: CodeGenerationSymbolFactory.CreateNamespaceSymbol(
topLevelNamespaceSymbol.ToDisplayString(SymbolDisplayFormats.NameFormat),
null,
new[] { wrappedType });
}
示例14: CheckCodeContext
protected virtual bool CheckCodeContext(Document document, int position, char openingBrace, CancellationToken cancellationToken)
{
this.AssertIsForeground();
// check that the user is not typing in a string literal or comment
var tree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();
return !syntaxFactsService.IsInNonUserCode(tree, position, cancellationToken);
}
示例15: CreateChangedDocumentAsync
private async Task<Document> CreateChangedDocumentAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var node = root.FindNode(span, findInsideTrivia: true, getInnermostNodeForTie: true);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var generator = document.GetLanguageService<SyntaxGenerator>();
var typeSymbol = (ITypeSymbol)semanticModel.GetSymbolInfo(node, cancellationToken).Symbol;
var replacementNode = generator.TypeExpression(typeSymbol).WithTriviaFrom(node);
return document.WithSyntaxRoot(root.ReplaceNode(node, replacementNode));
}