public async Task<IEnumerable<CodeAction>> GetRefactoringsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindNode(textSpan); var switchStatementNode = node as SwitchStatementSyntax; if (switchStatementNode == null) return null; var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var memberEx = switchStatementNode.Expression as MemberAccessExpressionSyntax; if (memberEx == null) return null; var symbolInfo = semanticModel.GetTypeInfo(memberEx.Name); var enumTypeInfo = symbolInfo.Type; if (enumTypeInfo.TypeKind != TypeKind.Enum) return null; var enumName = enumTypeInfo.Name; var nameSpace = enumTypeInfo.ContainingNamespace.Name; var enumType = Type.GetType(nameSpace + "." + enumName); if (enumType == null) return null; return new[] { CodeAction.Create("Explode Switch", c => ExplodeSwitch(document, root, semanticModel, switchStatementNode, c)) }; }
public PathSyntaxReference(SyntaxNode node) { _tree = node.SyntaxTree; _kind = node.Kind(); _textSpan = node.Span; _pathFromRoot = ComputePathFromRoot(node); }
public OutliningSpan(TextSpan textSpan, TextSpan hintSpan, string bannerText, bool autoCollapse) { this.TextSpan = textSpan; this.BannerText = bannerText; this.HintSpan = hintSpan; this.AutoCollapse = autoCollapse; }
public static bool OverlapsHiddenPosition( this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken) { var result = TryOverlapsHiddenPosition(text, span, isPositionHidden, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); return result; }
public TokenStream(TreeData treeData, OptionSet optionSet, TextSpan spanToFormat, AbstractTriviaDataFactory factory) { using (Logger.LogBlock(FunctionId.Formatting_TokenStreamConstruction, CancellationToken.None)) { // initialize basic info _factory = factory; _treeData = treeData; _optionSet = optionSet; // use some heuristics to get initial size of list rather than blindly start from default size == 4 int sizeOfList = spanToFormat.Length / MagicTextLengthToTokensRatio; _tokens = new List<SyntaxToken>(sizeOfList); _tokens.AddRange(_treeData.GetApplicableTokens(spanToFormat)); Contract.Requires(this.TokenCount > 0); // initialize trivia related info _cachedOriginalTriviaInfo = new TriviaData[this.TokenCount - 1]; _tokenToIndexMap = new Dictionary<SyntaxToken, int>(this.TokenCount); for (int i = 0; i < this.TokenCount; i++) { _tokenToIndexMap.Add(_tokens[i], i); } // Func Cache _getTriviaData = this.GetTriviaData; _getOriginalTriviaData = this.GetOriginalTriviaData; } DebugCheckTokenOrder(); }
public override SignatureHelpState GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (GetOuterMostTupleExpressionInSpan(root, position, syntaxFacts, currentSpan, cancellationToken, out var expression)) { return CommonSignatureHelpUtilities.GetSignatureHelpState(expression, position, getOpenToken: s_getOpenToken, getCloseToken: s_getCloseToken, getArgumentsWithSeparators: s_getArgumentsWithSeparators, getArgumentNames: s_getArgumentNames); } if (GetOuterMostParenthesizedExpressionInSpan(root, position, syntaxFacts, currentSpan, cancellationToken, out var parenthesizedExpression)) { if (currentSpan.Start == parenthesizedExpression.SpanStart) { return new SignatureHelpState( argumentIndex: 0, argumentCount: 0, argumentName: string.Empty, argumentNames: null); } } return null; }
public FileSystemCompletionHelper( CompletionListProvider completionProvider, TextSpan textChangeSpan, ICurrentWorkingDirectoryDiscoveryService fileSystemDiscoveryService, Glyph folderGlyph, Glyph fileGlyph, ImmutableArray<string> searchPaths, IEnumerable<string> allowableExtensions, Func<string, bool> exclude = null, CompletionItemRules itemRules = null) { Debug.Assert(searchPaths.All(path => PathUtilities.IsAbsolute(path))); _completionProvider = completionProvider; _textChangeSpan = textChangeSpan; _searchPaths = searchPaths; _allowableExtensions = allowableExtensions.Select(e => e.ToLowerInvariant()).ToSet(); _fileSystemDiscoveryService = fileSystemDiscoveryService; _folderGlyph = folderGlyph; _fileGlyph = fileGlyph; _exclude = exclude; _itemRules = itemRules; _lazyGetDrives = new Lazy<string[]>(() => IOUtilities.PerformIO(Directory.GetLogicalDrives, SpecializedCollections.EmptyArray<string>())); }
private void AddClassification(TextSpan span, string type) { if (ShouldAddSpan(span)) { _result.Add(new ClassifiedSpan(type, span)); } }
public async Task<IEnumerable<EncapsulateFieldCodeAction>> GetEncapsulateFieldCodeActionsAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var fields = (await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false)).ToImmutableArrayOrEmpty(); if (fields.Length == 0) { return SpecializedCollections.EmptyEnumerable<EncapsulateFieldCodeAction>(); } if (fields.Length == 1) { // there is only one field return EncapsulateOneField(document, span, fields[0], index: 0); } else { // there are multiple fields. var current = SpecializedCollections.EmptyEnumerable<EncapsulateFieldCodeAction>(); if (span.IsEmpty) { // if there is no selection, get action for each field + all of them. for (var i = 0; i < fields.Length; i++) { current = current.Concat(EncapsulateOneField(document, span, fields[i], i)); } } return current.Concat(EncapsulateAllFields(document, span)); } }
public static CompletionItem Create( string displayText, TextSpan span, ISymbol symbol, int contextPosition = -1, int descriptionPosition = -1, string sortText = null, string insertionText = null, Glyph? glyph = null, string filterText = null, bool preselect = false, SupportedPlatformData supportedPlatforms = null, bool isArgumentName = false, ImmutableDictionary<string, string> properties = null, CompletionItemRules rules = null) { return Create( displayText: displayText, span: span, symbols: ImmutableArray.Create(symbol), contextPosition: contextPosition, descriptionPosition: descriptionPosition, sortText: sortText, insertionText: insertionText, glyph: glyph, filterText: filterText, preselect: preselect, supportedPlatforms: supportedPlatforms, isArgumentName: isArgumentName, properties: properties, rules: rules); }
/// <summary> /// Changes the indentation of the current line based on the last /// bit of code typed. /// </summary> /// <param name="changedArea">Area of changed code</param> public void ChangeIndentation(TextSpan changedArea) { TextSpan area = changedArea; string text = source.GetText(area); string line = source.GetLineUptoPosition(area.iStartLine, area.iStartIndex); if (!line.EndsWith(text)) { // if commit includes last bit of text typed, the line won't have it yet // so stick it on for our parsing sanity // ** probably not the best thing to be doing here, but we can't just // get the whole line, because we may be pressing return in the centre // of it line += text; } if (RequiresIndent(line)) { source.SetText(area, text + Indent); // add an indent to the end of the changed text MoveCaret(Indent.Length); // move the caret to the new end of line } else if (RequiresDedent(line)) { source.SetText(area, text.Remove(text.Length - Indent.Length)); // remove an indent MoveCaret(-Indent.Length); // move caret in a bit } }
public static bool CheckIfSpanWithinSequencePoints(TextSpan span, string source, string pdb) { // calculate row and column from span var text = SourceText.From(source); var startLine = text.Lines.GetLineFromPosition(span.Start); var startRow = startLine.LineNumber + 1; var startColumn = span.Start - startLine.Start + 1; var endLine = text.Lines.GetLineFromPosition(span.End); var endRow = endLine.LineNumber + 1; var endColumn = span.End - endLine.Start + 1; var doc = new XmlDocument(); doc.LoadXml(pdb); foreach (XmlNode entry in doc.GetElementsByTagName("sequencePoints")) { foreach (XmlElement item in entry.ChildNodes) { if (startRow.ToString() == item.GetAttribute("startLine") && startColumn.ToString() == item.GetAttribute("startColumn") && endRow.ToString() == item.GetAttribute("endLine") && endColumn.ToString() == item.GetAttribute("endColumn")) { return true; } } } return false; }
protected CommonLibraryNode(CommonLibraryNode node) : base(node) { _fileId = node._fileId; _ownerHierarchy = node._ownerHierarchy; _fileMoniker = node._fileMoniker; _sourceSpan = node._sourceSpan; }
public ConflictLocationInfo(RelatedLocation location) { Debug.Assert(location.ComplexifiedTargetSpan.Contains(location.ConflictCheckSpan) || location.Type == RelatedLocationType.UnresolvableConflict); this.ComplexifiedSpan = location.ComplexifiedTargetSpan; this.DocumentId = location.DocumentId; this.OriginalIdentifierSpan = location.ConflictCheckSpan; }
public void GetAdjustedDiagnosticSpan( DocumentId documentId, Location location, out TextSpan sourceSpan, out FileLinePositionSpan originalLineInfo, out FileLinePositionSpan mappedLineInfo) { sourceSpan = location.SourceSpan; originalLineInfo = location.GetLineSpan(); mappedLineInfo = location.GetMappedLineSpan(); // check quick bail out case. if (location == Location.None) { return; } // Update the original source span, if required. if (!TryAdjustSpanIfNeededForVenus(documentId, originalLineInfo, mappedLineInfo, out var originalSpan, out var mappedSpan)) { return; } if (originalSpan.Start != originalLineInfo.StartLinePosition || originalSpan.End != originalLineInfo.EndLinePosition) { originalLineInfo = new FileLinePositionSpan(originalLineInfo.Path, originalSpan.Start, originalSpan.End); var textLines = location.SourceTree.GetText().Lines; var startPos = textLines.GetPosition(originalSpan.Start); var endPos = textLines.GetPosition(originalSpan.End); sourceSpan = TextSpan.FromBounds(startPos, Math.Max(startPos, endPos)); } if (mappedSpan.Start != mappedLineInfo.StartLinePosition || mappedSpan.End != mappedLineInfo.EndLinePosition) { mappedLineInfo = new FileLinePositionSpan(mappedLineInfo.Path, mappedSpan.Start, mappedSpan.End); } }
protected static SyntaxNode RecoverNode(SyntaxTree tree, TextSpan textSpan, int kind) { var token = tree.GetRoot().FindToken(textSpan.Start, findInsideTrivia: true); var node = token.Parent; while (node != null) { if (node.Span == textSpan && node.RawKind == kind) { return node; } var structuredTrivia = node as IStructuredTriviaSyntax; if (structuredTrivia != null) { node = structuredTrivia.ParentTrivia.Token.Parent; } else { node = node.Parent; } } throw Contract.Unreachable; }
public PathSyntaxReference(SyntaxNode node) { this.tree = node.SyntaxTree; this.kind = node.CSharpKind(); this.textSpan = node.Span; this.pathFromRoot = ComputePathFromRoot(node); }
internal static StatementRange GetStatementRange(string fileName, int startLine, int startColumn) { try { logger.Trace("Line: {0} Column: {1} Source: {2}", startLine, startColumn, fileName); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseFile(fileName); SourceText text = syntaxTree.GetText(); var root = (CompilationUnitSyntax) syntaxTree.GetRoot(); var span = new TextSpan(text.Lines[startLine - 1].Start + startColumn, 1); SyntaxNode node = root.FindNode(span, false, false); if (node is BlockSyntax) return MapBlockSyntax(span, node); while (node is TypeSyntax || node is MemberAccessExpressionSyntax) node = node.Parent; Location location = node.GetLocation(); FileLinePositionSpan mapped = location.GetMappedLineSpan(); return new StatementRange { StartLine = mapped.StartLinePosition.Line, StartColumn = mapped.StartLinePosition.Character, EndLine = mapped.EndLinePosition.Line, EndColumn = mapped.EndLinePosition.Character, }; } catch { return null; } }
public void Ctor2() { var span = new TextSpan(1, 40); Assert.Equal(1, span.Start); Assert.Equal(40, span.Length); Assert.Equal(41, span.End); }
public SignatureHelpModel(TextSpan applicableSpan, IEnumerable<SignatureItem> signatures, SignatureItem signature, int selectedParameter) { Signatures = signatures.ToImmutableArray(); ApplicableSpan = applicableSpan; Signature = signature; SelectedParameter = selectedParameter; }
public static IEnumerable<Diagnostic> GetDocumentDiagnostics(DiagnosticAnalyzer workspaceAnalyzerOpt, Document document, TextSpan span, Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException = null, bool logAnalyzerExceptionAsDiagnostics = false) { using (var testDriver = new TestDiagnosticAnalyzerDriver(document.Project, workspaceAnalyzerOpt, onAnalyzerException, logAnalyzerExceptionAsDiagnostics)) { return testDriver.GetDocumentDiagnostics(workspaceAnalyzerOpt, document, span); } }
public void Ctor1() { var span = new TextSpan(0, 42); Assert.Equal(0, span.Start); Assert.Equal(42, span.Length); Assert.Equal(42, span.End); }
internal ApiLine(string text, TextSpan span, SourceText sourceText, string path) { Text = text; Span = span; SourceText = sourceText; Path = path; }
public async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { // use speculative semantic model to see whether we are on a symbol we can do HR var span = new TextSpan(position, 0); var solution = document.Project.Solution; var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false); var symbol = await SymbolFinder.FindSymbolAtPositionAsync( semanticModel, position, solution.Workspace, cancellationToken).ConfigureAwait(false); if (symbol == null) { return ImmutableArray<DocumentHighlights>.Empty; } symbol = await GetSymbolToSearchAsync(document, position, semanticModel, symbol, cancellationToken).ConfigureAwait(false); if (symbol == null) { return ImmutableArray<DocumentHighlights>.Empty; } // Get unique tags for referenced symbols return await GetTagsForReferencedSymbolAsync( new SymbolAndProjectId(symbol, document.Project.Id), documentsToSearch, solution, cancellationToken).ConfigureAwait(false); }
public CodeRefactoring GetRefactoring(IDocument document, TextSpan textSpan, CancellationToken cancellationToken) { var tree = (SyntaxTree)document.GetSyntaxTree(cancellationToken); var token = tree.GetRoot().FindToken(textSpan.Start); if (token.Parent is ClassDeclarationSyntax || token.Parent is StructDeclarationSyntax) { var t = (TypeDeclarationSyntax)token.Parent; if (!CanInferNonTrivialConstructor(t)) return null; return new CodeRefactoring(new[] { new ReadyCodeAction("Infer Non-Trivial Constructor", document, t, () => { var c = TryInferNonTrivialConstructor(t, document.TryGetSemanticModel()); var i = 0; var ms = t.Members.Insert(i, new[] {c}).List(); return t.With(members: ms); })}); } if (token.Parent is MemberDeclarationSyntax && (token.Parent.Parent is ClassDeclarationSyntax || token.Parent.Parent is StructDeclarationSyntax)) { var m = (MemberDeclarationSyntax)token.Parent; var t = (TypeDeclarationSyntax)m.Parent; if (!CanInferNonTrivialConstructor(t)) return null; return new CodeRefactoring(new[] { new ReadyCodeAction("Infer Non-Trivial Constructor Here", document, t, () => { var c = TryInferNonTrivialConstructor(t, document.TryGetSemanticModel()); var i = t.Members.IndexOf(m); var ms = t.Members.Insert(i, new[] {c}).List(); return t.With(members: ms); })}); } return null; }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var position = completionContext.Position; var document = completionContext.Document; var span = new TextSpan(position, 0); var semanticModel = await document.GetCSharpSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false); var syntaxTree = semanticModel.SyntaxTree; // var ctx = await completionContext.GetSyntaxContextAsync (engine.Workspace, cancellationToken).ConfigureAwait (false); if (syntaxTree.IsInNonUserCode(position, cancellationToken) || syntaxTree.IsPreProcessorDirectiveContext(position, cancellationToken)) { return Enumerable.Empty<CompletionData> (); } if (!syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken)) { return Enumerable.Empty<CompletionData> (); } var node = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position) .Parent; if (node.Kind() == SyntaxKind.ExplicitInterfaceSpecifier) { return await GetCompletionsOffOfExplicitInterfaceAsync( engine, document, semanticModel, position, ((ExplicitInterfaceSpecifierSyntax)node).Name, cancellationToken).ConfigureAwait(false); } return Enumerable.Empty<CompletionData> (); }
/// <summary> /// Traverses the symbol table processing XML documentation comments and optionally writing them to /// a provided stream. /// </summary> /// <param name="compilation">Compilation that owns the symbol table.</param> /// <param name="assemblyName">Assembly name override, if specified. Otherwise the <see cref="ISymbol.Name"/> of the source assembly is used.</param> /// <param name="xmlDocStream">Stream to which XML will be written, if specified.</param> /// <param name="diagnostics">Will be supplemented with documentation comment diagnostics.</param> /// <param name="cancellationToken">To stop traversing the symbol table early.</param> /// <param name="filterTree">Only report diagnostics from this syntax tree, if non-null.</param> /// <param name="filterSpanWithinTree">If <paramref name="filterTree"/> and filterSpanWithinTree is non-null, report diagnostics within this span in the <paramref name="filterTree"/>.</param> public static void WriteDocumentationCommentXml(CSharpCompilation compilation, string assemblyName, Stream xmlDocStream, DiagnosticBag diagnostics, CancellationToken cancellationToken, SyntaxTree filterTree = null, TextSpan? filterSpanWithinTree = null) { StreamWriter writer = null; if (xmlDocStream != null && xmlDocStream.CanWrite) { writer = new StreamWriter( stream: xmlDocStream, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false), bufferSize: 0x400, // Default. leaveOpen: true); // Don't close caller's stream. } using (writer) { var compiler = new DocumentationCommentCompiler(assemblyName ?? compilation.SourceAssembly.Name, compilation, writer, filterTree, filterSpanWithinTree, processIncludes: true, isForSingleSymbol: false, diagnostics: diagnostics, cancellationToken: cancellationToken); compiler.Visit(compilation.SourceAssembly.GlobalNamespace); Debug.Assert(compiler._indentDepth == 0); } if (filterTree != null) { // Will respect the DocumentationMode. UnprocessedDocumentationCommentFinder.ReportUnprocessed(filterTree, filterSpanWithinTree, diagnostics, cancellationToken); } else { foreach (SyntaxTree tree in compilation.SyntaxTrees) { // Will respect the DocumentationMode. UnprocessedDocumentationCommentFinder.ReportUnprocessed(tree, null, diagnostics, cancellationToken); } } }
protected void Test(string code, string allCode, Tuple<string, string>[] expected, CSharpParseOptions options = null) { var start = allCode.IndexOf(code); var length = code.Length; var span = new TextSpan(start, length); var actual = GetClassificationSpans(allCode, span, options: options).ToList(); actual.Sort((t1, t2) => t1.TextSpan.Start - t2.TextSpan.Start); var max = Math.Max(expected.Length, actual.Count); for (int i = 0; i < max; i++) { if (i >= expected.Length) { AssertEx.Fail("Unexpected actual classification: {0}", GetText(actual[i])); } else if (i >= actual.Count) { AssertEx.Fail("Missing classification for: {0}", GetText(expected[i])); } var tuple = expected[i]; var classification = actual[i]; var text = allCode.Substring(classification.TextSpan.Start, classification.TextSpan.Length); Assert.Equal(tuple.Item1, text); Assert.Equal(tuple.Item2, classification.ClassificationType); } }
public SourceDefinitionTreeItem(Document document, TextSpan sourceSpan, ISymbol symbol, ushort glyphIndex) : base(document, sourceSpan, glyphIndex) { _symbolDisplay = symbol.ToDisplayString(definitionDisplayFormat); this.DisplayText = $"[{document.Project.Name}] {_symbolDisplay}"; }
public XmlDocCommentCompletionItem(CompletionListProvider provider, TextSpan filterSpan, string displayText, CompletionItemRules rules) : this(provider, filterSpan, displayText, displayText, string.Empty, rules) { }
public static IOpenParenToken OpenParen(TextSpan span) { return(new OpenParenToken(span)); }
public PlusToken(TextSpan span) : base(span) { }
public NotEqualToken(TextSpan span) : base(span) { }
public static IColonToken Colon(TextSpan span) { return(new ColonToken(span)); }
public EqualsEqualsToken(TextSpan span) : base(span) { }
public SlashToken(TextSpan span) : base(span) { }
public AsteriskToken(TextSpan span) : base(span) { }
public MinusToken(TextSpan span) : base(span) { }
public LessThanDotDotLessThanToken(TextSpan span) : base(span) { }
public static ICommaToken Comma(TextSpan span) { return(new CommaToken(span)); }
public ColonColonDotToken(TextSpan span) : base(span) { }
public DotDotToken(TextSpan span) : base(span) { }
public RightArrowToken(TextSpan span) : base(span) { }
public static ISemicolonToken Semicolon(TextSpan span) { return(new SemicolonToken(span)); }
public CommaToken(TextSpan span) : base(span) { }
public ColonToken(TextSpan span) : base(span) { }
public CloseParenToken(TextSpan span) : base(span) { }
public SemicolonToken(TextSpan span) : base(span) { }
public OpenParenToken(TextSpan span) : base(span) { }
public static ICloseParenToken CloseParen(TextSpan span) { return(new CloseParenToken(span)); }
public OpenBraceToken(TextSpan span) : base(span) { }
public CloseBraceToken(TextSpan span) : base(span) { }
public GreaterThanToken(TextSpan span) : base(span) { }
public EndOfFileToken(TextSpan span) : base(span) { }
public static ICloseBraceToken CloseBrace(TextSpan span) { return(new CloseBraceToken(span)); }
public static ILeftWaveArrowToken LeftWaveArrow(TextSpan span) { return(new LeftWaveArrowToken(span)); }
public static IQuestionDotToken QuestionDot(TextSpan span) { return(new QuestionDotToken(span)); }
public static IRightWaveArrowToken RightWaveArrow(TextSpan span) { return(new RightWaveArrowToken(span)); }
public static ISlashEqualsToken SlashEquals(TextSpan span) { return(new SlashEqualsToken(span)); }
public static ILessThanColonToken LessThanColon(TextSpan span) { return(new LessThanColonToken(span)); }