protected CSharpLinesWalker(TextLineCollection lines, CodeMetricsOptions options, CancellationToken cancellationToken) : base(SyntaxWalkerDepth.Trivia) { Lines = lines; Options = options; CancellationToken = cancellationToken; }
public static SelectionResult Create(TextLineCollection lines, TextSpan span) { using (TextLineCollection.Enumerator en = lines.GetEnumerator()) { if (en.MoveNext()) { int i = 0; while (span.Start >= en.Current.EndIncludingLineBreak && en.MoveNext()) { i++; } if (span.Start == en.Current.Start) { int j = i; while (span.End > en.Current.EndIncludingLineBreak && en.MoveNext()) { j++; } if (span.End == en.Current.End || span.End == en.Current.EndIncludingLineBreak) { return(new SelectionResult(i, j)); } } } } return(Fail); }
private static int[] ComputeTokens( TextLineCollection lines, ClassifiedSpan[] classifiedSpans, Dictionary <string, int> tokenTypesToIndex) { using var _ = ArrayBuilder <int> .GetInstance(classifiedSpans.Length, out var data); // We keep track of the last line number and last start character since tokens are // reported relative to each other. var lastLineNumber = 0; var lastStartCharacter = 0; for (var currentClassifiedSpanIndex = 0; currentClassifiedSpanIndex < classifiedSpans.Length; currentClassifiedSpanIndex++) { currentClassifiedSpanIndex = ComputeNextToken( lines, ref lastLineNumber, ref lastStartCharacter, classifiedSpans, currentClassifiedSpanIndex, tokenTypesToIndex, out var deltaLine, out var startCharacterDelta, out var tokenLength, out var tokenType, out var tokenModifiers); data.AddRange(deltaLine, startCharacterDelta, tokenLength, tokenType, tokenModifiers); } return(data.ToArray()); }
private static (int startIndex, int endIndex) GetIndexes(TextLineCollection lines, TextSpan span) { using (TextLineCollection.Enumerator en = lines.GetEnumerator()) { if (en.MoveNext()) { int i = 0; while (span.Start >= en.Current.EndIncludingLineBreak && en.MoveNext()) { i++; } if (span.Start == en.Current.Start) { int j = i; while (span.End > en.Current.EndIncludingLineBreak && en.MoveNext()) { j++; } if (span.End == en.Current.End || span.End == en.Current.EndIncludingLineBreak) { return(i, j); } } } } return(-1, -1); }
public override async Task RegisterCodeFixesAsync(CodeFixContext context) { SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false); if (!TryFindFirstAncestorOrSelf( root, context.Span, out ExpressionSyntax expression, predicate: f => f.IsKind( SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ConditionalAccessExpression))) { return; } Document document = context.Document; Diagnostic diagnostic = context.Diagnostics[0]; CodeAction codeAction = CodeAction.Create( "Fix formatting", ct => { TextLineCollection lines = expression.SyntaxTree.GetText().Lines; TextLine line = lines.GetLineFromPosition(expression.SpanStart); TextSpan span = TextSpan.FromBounds(line.EndIncludingLineBreak, expression.Span.End); return(CodeFixHelpers.FixCallChainAsync(document, expression, span, ct)); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); }
internal static async Task <Document> RemovePreprocessorDirectivesAsync( this Document document, IEnumerable <DirectiveTriviaSyntax> directives, CancellationToken cancellationToken = default) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (directives == null) { throw new ArgumentNullException(nameof(directives)); } SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); SourceText newSourceText = sourceText.WithChanges(GetTextChanges()); return(document.WithText(newSourceText)); IEnumerable <TextChange> GetTextChanges() { TextLineCollection lines = sourceText.Lines; foreach (DirectiveTriviaSyntax directive in directives) { int startLine = directive.GetSpanStartLine(); yield return(new TextChange(lines[startLine].SpanIncludingLineBreak, "")); } } }
public void Execute(GeneratorExecutionContext context) { //Debugger.Launch(); AdditionalText file = context.AdditionalFiles.First(); SourceText fileText = file.GetText(context.CancellationToken); TextLineCollection lines = fileText.Lines; Debug.Assert(lines.Count == 4); BenchmarkSpecification specification = new(); specification.NumPocos = int.Parse(lines[0].ToString()); specification.NumProps = int.Parse(lines[1].ToString()); specification.UseSerializationAttributes = bool.Parse(lines[2].ToString()); specification.Process = (JsonProcess)Enum.Parse(typeof(JsonProcess), lines[3].ToString()); specification.Processor = (JsonProcessor)Enum.Parse(typeof(JsonProcessor), lines[4].ToString()); if (!SpecificationIsValid(specification)) { context.AddSource(BenchmarkSerializationLogicFileName, InvalidSepcificationSourceText); return; } GenerateBenchmarkImplementation(context, specification); }
private static void AdjustBoundaries(DiagnosticDataLocation dataLocation, TextLineCollection lines, out int startLine, out int startColumn, out int endLine, out int endColumn) { startLine = dataLocation?.OriginalStartLine ?? 0; var originalStartColumn = dataLocation?.OriginalStartColumn ?? 0; startColumn = Math.Max(originalStartColumn, 0); if (startLine < 0) { startLine = 0; startColumn = 0; } endLine = dataLocation?.OriginalEndLine ?? 0; var originalEndColumn = dataLocation?.OriginalEndColumn ?? 0; endColumn = Math.Max(originalEndColumn, 0); if (endLine < 0) { endLine = startLine; endColumn = startColumn; } else if (endLine >= lines.Count) { endLine = lines.Count - 1; endColumn = lines[endLine].EndIncludingLineBreak; } }
public static SelectionResult Create(TextLineCollection lines, TextSpan span, int minCount, int maxCount) { ThrowIfNotValidRange(minCount, maxCount); if (lines.Count == 0) { return(Fail); } if (span.IsEmpty) { return(Fail); } SelectionResult result = Create(lines, span); if (!result.Success) { return(Fail); } if (!result.IsInRange(minCount, maxCount)) { return(Fail); } return(result); }
/// <summary> /// Creates a new document with the specified region removed. /// </summary> /// <param name="document"></param> /// <param name="region"></param> /// <param name="cancellationToken"></param> public static async Task <Document> RemoveRegionAsync( this Document document, RegionInfo region, CancellationToken cancellationToken = default) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (!region.Success) { throw new ArgumentException($"{nameof(RegionInfo)} is not initialized.", nameof(region)); } SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); int startLine = region.Directive.GetSpanStartLine(); int endLine = region.EndDirective.GetSpanEndLine(); TextLineCollection lines = sourceText.Lines; TextSpan span = TextSpan.FromBounds( lines[startLine].Start, lines[endLine].EndIncludingLineBreak); var textChange = new TextChange(span, ""); SourceText newSourceText = sourceText.WithChanges(textChange); return(document.WithText(newSourceText)); }
private static string GetLineTextOrEmpty(TextLineCollection lines, int index) { if (index < 0 || index >= lines.Count) { return(string.Empty); } return(lines[index].ToString().TrimEnd()); }
public SelectedTextLineCollection(TextLineCollection lines, TextSpan span) { if (lines == null) { throw new ArgumentNullException(nameof(lines)); } UnderlyingLines = lines; Span = span; }
/// <summary> /// Creates a new <see cref="TextLineCollectionSelection"/> based on the specified list and span. /// </summary> /// <param name="lines"></param> /// <param name="span"></param> /// <returns></returns> public static TextLineCollectionSelection Create(TextLineCollection lines, TextSpan span) { if (lines == null) { throw new ArgumentNullException(nameof(lines)); } SelectionResult result = SelectionResult.Create(lines, span); return(new TextLineCollectionSelection(lines, span, result)); }
public static TextLineCollectionSelection Create(TextLineCollection lines, TextSpan span) { if (lines == null) { throw new ArgumentNullException(nameof(lines)); } (int startIndex, int endIndex) = GetIndexes(lines, span); return(new TextLineCollectionSelection(lines, span, startIndex, endIndex)); }
public void InitCodeLine(TextLineCollection lines) { var lineSpan = Expression.SyntaxTree.GetLineSpan(Expression.Span); var selectedLines = new List <string>(); for (var i = lineSpan.StartLinePosition.Line; i <= lineSpan.EndLinePosition.Line; ++i) { selectedLines.Add(lines[i].ToString()); } _linesTextLowerCase = selectedLines.Join("\n").ToLower(MainWindow.RuCulture); }
public static HighlightSpan CreateHighlightSpan(ClassifiedSpan span, TextLineCollection lines, IEnumerable <string> projects) { var linePos = lines.GetLinePositionSpan(span.TextSpan); return(new HighlightSpan { StartLine = linePos.Start.Line, EndLine = linePos.End.Line, StartColumn = linePos.Start.Character, EndColumn = linePos.End.Character, Kind = span.ClassificationType, Projects = projects }); }
private void Tokenize(TextLineCollection lines) { foreach (var line in lines) { var tokens = this.TokenList.Count; foreach (var function in this.Functions) { function.Invoke(line, this.TokenList); } if (tokens == this.TokenList.Count && line.End > line.Start) { this.TokenList.Add(new Unknown(line)); } } }
private static TextLineCollectionSelection Create(TextLineCollection lines, TextSpan span, int minCount, int maxCount) { if (lines == null) { return(null); } SelectionResult result = SelectionResult.Create(lines, span, minCount, maxCount); if (!result.Success) { return(null); } return(new TextLineCollectionSelection(lines, span, result)); }
private static SourceText RemoveDirectives( SourceText sourceText, IEnumerable <DirectiveTriviaSyntax> directives) { TextLineCollection lines = sourceText.Lines; var changes = new List <TextChange>(); foreach (DirectiveTriviaSyntax directive in directives) { int startLine = directive.GetSpanStartLine(); changes.Add(new TextChange(lines[startLine].SpanIncludingLineBreak, "")); } return(sourceText.WithChanges(changes)); }
public override CodeMetricsInfo CountLogicalLines(SyntaxNode node, SourceText sourceText, CodeMetricsOptions options, CancellationToken cancellationToken) { TextLineCollection lines = sourceText.Lines; var walker = new CSharpLogicalLinesWalker(lines, options, cancellationToken); walker.Visit(node); int whitespaceLineCount = (options.IncludeWhitespace) ? 0 : CountWhitespaceLines(node, sourceText); return(new CodeMetricsInfo( totalLineCount: lines.Count, codeLineCount: walker.LogicalLineCount, whitespaceLineCount: whitespaceLineCount, commentLineCount: walker.CommentLineCount, preprocessorDirectiveLineCount: walker.PreprocessorDirectiveLineCount, blockBoundaryLineCount: 0)); }
public static void WriteSpellingDiagnostic( SpellingDiagnostic diagnostic, SpellingFixerOptions options, SourceText sourceText, string baseDirectoryPath, string indentation, Verbosity verbosity) { WriteDiagnostic(diagnostic.Diagnostic, baseDirectoryPath, default(IFormatProvider), indentation, verbosity); TextSpan span = diagnostic.Span; TextLineCollection lines = sourceText.Lines; int lineIndex = lines.IndexOf(span.Start); TextLine line = lines[lineIndex]; int start = Math.Max(0, lineIndex - options.CodeContext); for (int i = start; i < lineIndex; i++) { WriteTextLine(i); } int index = span.Start - line.Span.Start; string text = line.ToString(); Write(indentation, verbosity); Write(text.Substring(0, index), ConsoleColor.DarkGray, verbosity); Write(diagnostic.Value, ConsoleColor.Cyan, verbosity); WriteLine(text.Substring(index + diagnostic.Length), ConsoleColor.DarkGray, verbosity); int max = Math.Min(lines.Count - 1, lineIndex + options.CodeContext); for (int i = lineIndex + 1; i <= max; i++) { WriteTextLine(i); } void WriteTextLine(int i) { Write(indentation, verbosity); WriteLine(lines[i].ToString(), ConsoleColor.DarkGray, verbosity); } }
protected override SyntaxToken GetAdjustedTokenForPragmaRestore( SyntaxToken token, SyntaxNode root, TextLineCollection lines, int indexOfLine) { var nextToken = token.GetNextToken(); if (nextToken.Kind() == SyntaxKind.SemicolonToken && nextToken.Parent is StatementSyntax statement && statement.GetLastToken() == nextToken && token.Parent.FirstAncestorOrSelf <StatementSyntax>() == statement) { // both the current and next tokens belong to the same statement, and the next token // is the final semicolon in a statement. Do not put the pragma before that // semicolon. Place it after the semicolon so the statement stays whole. return(nextToken); } return(token); }
private static async Task <Document> RemoveRegionAsync(Document document, RegionDirectiveTriviaSyntax regionDirective, EndRegionDirectiveTriviaSyntax endRegionDirective, CancellationToken cancellationToken) { SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); int startLine = regionDirective.GetSpanStartLine(); int endLine = endRegionDirective.GetSpanEndLine(); TextLineCollection lines = sourceText.Lines; TextSpan span = TextSpan.FromBounds( lines[startLine].Start, lines[endLine].EndIncludingLineBreak); var textChange = new TextChange(span, ""); SourceText newSourceText = sourceText.WithChanges(textChange); return(document.WithText(newSourceText)); }
public static bool TryCreate(TextLineCollection lines, TextSpan span, out TextLineCollectionSelection selection) { selection = null; if (lines.Count == 0) { return(false); } (int startIndex, int endIndex) = GetIndexes(lines, span); if (startIndex == -1) { return(false); } selection = new TextLineCollectionSelection(lines, span, startIndex, endIndex); return(true); }
public static HashSet <string> GetAffectedClasses(SyntaxNode treeRoot, List <int> affectedLines, string absoluteFileLocation) { HashSet <string> affectedClasses = new HashSet <string>(); TextLineCollection lines = treeRoot.GetText().Lines; string fileName = absoluteFileLocation.Replace(@"\", "/"); var pathArr = fileName.Split('/'); string fileAndParent = $@"{pathArr[pathArr.Length - 2]}/{pathArr[pathArr.Length - 1]}"; foreach (var affectedLine in affectedLines) { if (affectedLine < 1) { continue; // This means the first line of the file has been inserted. This can not be an update to an class. Therefore, skip. } TextSpan lineTextSpan = lines[affectedLine - 1].Span; List <ClassDeclarationSyntax> intersectedClasses = treeRoot.DescendantNodes() .Where(x => x.Span.IntersectsWith(lineTextSpan)) .OfType <ClassDeclarationSyntax>() .ToList(); if (intersectedClasses.Count == 0) { Console.WriteLine($"Affected line {affectedLine} doesn't intersect with a class"); continue; } if (intersectedClasses.Count > 1) { Console.WriteLine($"Affected line {affectedLine} intersects with multiple classes"); continue; } foreach (ClassDeclarationSyntax classDeclaration in intersectedClasses) { string className = classDeclaration.Identifier.ValueText; string classNameWithHash = $"{className}-{fileAndParent.GetHashCode().ToString()}"; affectedClasses.Add(classNameWithHash); } } return(affectedClasses); }
public TextLineCollectionSelection(TextLineCollection lines, TextSpan span) { if (lines == null) { throw new ArgumentNullException(nameof(lines)); } UnderlyingLines = lines; Span = span; using (TextLineCollection.Enumerator en = UnderlyingLines.GetEnumerator()) { if (en.MoveNext()) { int i = 0; while (Span.Start >= en.Current.EndIncludingLineBreak && en.MoveNext()) { i++; } if (Span.Start == en.Current.Start) { int j = i; while (Span.End > en.Current.EndIncludingLineBreak && en.MoveNext()) { j++; } if (Span.End == en.Current.End || Span.End == en.Current.EndIncludingLineBreak) { StartIndex = i; EndIndex = j; } } } } }
public static async Task <Document> RemoveRegionAsync( Document document, RegionDirectiveTriviaSyntax regionDirective, CancellationToken cancellationToken = default(CancellationToken)) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (regionDirective == null) { throw new ArgumentNullException(nameof(regionDirective)); } List <DirectiveTriviaSyntax> list = regionDirective.GetRelatedDirectives(); if (list.Count == 2 && list[1].IsKind(SyntaxKind.EndRegionDirectiveTrivia)) { var endRegionDirective = (EndRegionDirectiveTriviaSyntax)list[1]; SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); int startLine = regionDirective.GetSpanStartLine(); int endLine = endRegionDirective.GetSpanEndLine(); TextLineCollection lines = sourceText.Lines; TextSpan span = TextSpan.FromBounds( lines[startLine].Start, lines[endLine].EndIncludingLineBreak); var textChange = new TextChange(span, string.Empty); SourceText newSourceText = sourceText.WithChanges(textChange); return(document.WithText(newSourceText)); } return(document); }
public static SourceText RemoveDirectives( SourceText sourceText, IEnumerable <DirectiveTriviaSyntax> directives) { if (sourceText == null) { throw new ArgumentNullException(nameof(sourceText)); } TextLineCollection lines = sourceText.Lines; var changes = new List <TextChange>(); foreach (DirectiveTriviaSyntax directive in directives) { int startLine = directive.GetSpanStartLine(); changes.Add(new TextChange(lines[startLine].SpanIncludingLineBreak, string.Empty)); } return(sourceText.WithChanges(changes)); }
public static void WriteLineSpan( TextSpan span, int context, SourceText sourceText, string indentation, Verbosity verbosity) { TextLineCollection lines = sourceText.Lines; int lineIndex = lines.IndexOf(span.Start); TextLine line = lines[lineIndex]; int start = Math.Max(0, lineIndex - context); for (int i = start; i < lineIndex; i++) { WriteTextLine(i); } int index = span.Start - line.Span.Start; string text = line.ToString(); Write(indentation, verbosity); Write(text.Substring(0, index), verbosity); Write(text.Substring(index, span.Length), ConsoleColors.Cyan, verbosity); WriteLine(text.Substring(index + span.Length), verbosity); int max = Math.Min(lines.Count - 1, lineIndex + context); for (int i = lineIndex + 1; i <= max; i++) { WriteTextLine(i); } void WriteTextLine(int i) { Write(indentation, verbosity); WriteLine(lines[i].ToString(), ConsoleColors.DarkGray, verbosity); } }
private void AdjustBoundaries( TextLineCollection lines, out int startLine, out int startColumn, out int endLine, out int endColumn) { startLine = this.OriginalStartLine; startColumn = Math.Max(this.OriginalStartColumn, 0); if (startLine < 0) { startLine = 0; startColumn = 0; } endLine = this.OriginalEndLine; endColumn = Math.Max(this.OriginalEndColumn, 0); if (endLine < 0) { endLine = startLine; endColumn = startColumn; } else if (endLine >= lines.Count) { endLine = lines.Count - 1; endColumn = lines[endLine].EndIncludingLineBreak; } }
internal bool TryGetLines(out TextLineCollection lines) { lines = _lazyLineInfo; return lines != null; }
/// <summary> /// 比較結果を取得します。 /// </summary> /// <param name="level">比較レベル</param> /// <returns>比較結果</returns> public DiffReport Report(DiffEngineLevel level = DiffEngineLevel.SlowPerfect) { CheckFileExist(SourcePath); CheckFileExist(DestinationPath); var d1 = new TextLineCollection(SourcePath); var d2 = new TextLineCollection(DestinationPath); DiffEngine de = new DiffEngine(); de.ProcessDiff(d1, d2, level); return de.DiffReport(); }
protected virtual SyntaxToken GetAdjustedTokenForPragmaRestore(SyntaxToken token, SyntaxNode root, TextLineCollection lines, int indexOfLine) { return token; }