23 types derived from SourceText
GenerateDocumentationAndConfigFiles (1)
Metrics (1)
Metrics.Legacy (1)
Microsoft.CodeAnalysis (7)
Microsoft.CodeAnalysis.Analyzers (1)
Microsoft.CodeAnalysis.AnalyzerUtilities (1)
Microsoft.CodeAnalysis.BannedApiAnalyzers (1)
Microsoft.CodeAnalysis.CodeStyle (1)
Microsoft.CodeAnalysis.EditorFeatures.Text (1)
Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers (1)
Microsoft.CodeAnalysis.PublicApiAnalyzers (1)
Microsoft.CodeAnalysis.ResxSourceGenerator (1)
Microsoft.CodeAnalysis.Test.Utilities (1)
Microsoft.CodeAnalysis.Workspaces (1)
Roslyn.Diagnostics.Analyzers (1)
Test.Utilities (1)
Text.Analyzers (1)
6065 references to SourceText
Analyzer.Utilities.UnitTests (6)
BuildValidator (4)
ConfigurationSchemaGenerator.Tests (2)
EventSourceGenerator (1)
GenerateDocumentationAndConfigFiles (102)
src\Compilers\Core\Portable\EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
src\RoslynAnalyzers\Microsoft.CodeAnalysis.Analyzers\Core\MetaAnalyzers\ReleaseTrackingHelper.cs (8)
46SourceText sourceText,
47Action<string, Version, string, SourceText, TextLine> onDuplicateEntryInRelease,
48Action<TextLine, InvalidEntryKind, string, SourceText> onInvalidEntry,
440public SourceText SourceText { get; }
449TextSpan span, SourceText sourceText,
458TextSpan span, SourceText sourceText,
478TextSpan span, SourceText sourceText,
497TextSpan span, SourceText sourceText,
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\SourceTextExtensions_SharedWithCodeStyle.cs (5)
16public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
32this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
44this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
82public static bool AreOnSameLine(this SourceText text, SyntaxToken token1, SyntaxToken token2)
87public static bool AreOnSameLine(this SourceText text, int pos1, int pos2)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Services\RefactoringHelpers\AbstractRefactoringHelpers.cs (6)
25public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
42private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span)
60SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray<TSyntaxNode> result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
179SourceText sourceText, SyntaxNode root, int location)
251SourceText sourceText, SyntaxToken tokenOnLocation, int location)
533SourceText sourceText,
IdeBenchmarks (1)
IdeCoreBenchmarks (12)
Metrics (68)
src\Compilers\Core\Portable\EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\SourceTextExtensions_SharedWithCodeStyle.cs (5)
16public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
32this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
44this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
82public static bool AreOnSameLine(this SourceText text, SyntaxToken token1, SyntaxToken token2)
87public static bool AreOnSameLine(this SourceText text, int pos1, int pos2)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Services\RefactoringHelpers\AbstractRefactoringHelpers.cs (6)
25public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
42private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span)
60SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray<TSyntaxNode> result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
179SourceText sourceText, SyntaxNode root, int location)
251SourceText sourceText, SyntaxToken tokenOnLocation, int location)
533SourceText sourceText,
Metrics.Legacy (68)
src\Compilers\Core\Portable\EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\SourceTextExtensions_SharedWithCodeStyle.cs (5)
16public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
32this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
44this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
82public static bool AreOnSameLine(this SourceText text, SyntaxToken token1, SyntaxToken token2)
87public static bool AreOnSameLine(this SourceText text, int pos1, int pos2)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Services\RefactoringHelpers\AbstractRefactoringHelpers.cs (6)
25public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
42private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span)
60SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray<TSyntaxNode> result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
179SourceText sourceText, SyntaxNode root, int location)
251SourceText sourceText, SyntaxToken tokenOnLocation, int location)
533SourceText sourceText,
Microsoft.Analyzers.Extra.Tests (10)
Microsoft.Analyzers.Local.Tests (10)
Microsoft.AspNetCore.Analyzer.Testing (3)
Microsoft.AspNetCore.App.Analyzers (14)
Microsoft.AspNetCore.App.Analyzers.Test (7)
Microsoft.AspNetCore.Components.Analyzers.Tests (1)
Microsoft.AspNetCore.Components.SdkAnalyzers.Tests (1)
Microsoft.AspNetCore.Http.Microbenchmarks (7)
Microsoft.AspNetCore.Mvc.Razor.Extensions.UnitTests (2)
Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation (3)
Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.Test (1)
Microsoft.AspNetCore.OpenApi.SourceGenerators (1)
Microsoft.AspNetCore.Razor.Language.UnitTests (5)
Microsoft.AspNetCore.Razor.Microbenchmarks (12)
Microsoft.AspNetCore.Razor.Microbenchmarks.Generator (5)
Microsoft.AspNetCore.Razor.Test.Common (7)
Microsoft.AspNetCore.Razor.Test.Common.Cohosting (13)
RazorProjectBuilder.cs (8)
47private readonly List<(DocumentId id, string name, SourceText text, string filePath)> _documents = [];
48private readonly List<(DocumentId id, string name, SourceText text, string filePath)> _additionalDocuments = [];
49private readonly List<(string name, SourceText text, string filePath)> _analyzerConfigDocuments = [];
56internal DocumentId AddDocument(string filePath, SourceText text)
64internal DocumentId AddAdditionalDocument(string filePath, SourceText text)
72internal void AddAdditionalDocument(DocumentId id, string filePath, SourceText text)
78internal void AddAnalyzerConfigDocument(string filePath, SourceText text)
162text: SourceText.From(globalConfigContent.ToString()),
Microsoft.AspNetCore.Razor.Test.Common.Tooling (17)
Microsoft.AspNetCore.SignalR.Client.SourceGenerator (4)
Microsoft.CodeAnalysis (257)
EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
SourceGeneration\GeneratorContexts.cs (8)
85public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8, checksumAlgorithm: _checksumAlgorithm == SourceHashAlgorithm.None ? SourceHashAlgorithms.Default : _checksumAlgorithm));
88/// Adds a <see cref="SourceText"/> to the compilation
91/// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param>
95public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(hintName, sourceText.WithChecksumAlgorithmIfAny(_checksumAlgorithm));
277public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8));
280/// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases
283/// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param>
287public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(hintName, sourceText);
SourceGeneration\IncrementalContexts.cs (10)
205public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8));
208/// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases
211/// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param>
215public void AddSource(string hintName, SourceText sourceText) => AdditionalSources.Add(hintName, sourceText);
218/// Adds a <see cref="SourceText" /> to the compilation containing the definition of <c>Microsoft.CodeAnalysis.EmbeddedAttribute</c>.
225public void AddEmbeddedAttributeDefinition() => AddSource("Microsoft.CodeAnalysis.EmbeddedAttribute", SourceText.From(_embeddedAttributeDefinition, encoding: Encoding.UTF8));
254public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8, checksumAlgorithm: ChecksumAlgorithm == SourceHashAlgorithm.None ? SourceHashAlgorithms.Default : ChecksumAlgorithm));
257/// Adds a <see cref="SourceText"/> to the compilation
260/// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param>
264public void AddSource(string hintName, SourceText sourceText) => Sources.Add(hintName, sourceText.WithChecksumAlgorithmIfAny(ChecksumAlgorithm));
Text\CompositeText.cs (37)
18/// A composite of a sequence of <see cref="SourceText"/>s.
22private readonly ImmutableArray<SourceText> _segments;
28private CompositeText(ImmutableArray<SourceText> segments, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm)
67internal override ImmutableArray<SourceText> Segments
83public override SourceText GetSubText(TextSpan span)
94var newSegments = ArrayBuilder<SourceText>.GetInstance();
99var segment = _segments[segIndex];
157var segment = _segments[segIndex];
169internal static void AddSegments(ArrayBuilder<SourceText> segments, SourceText text)
182internal static SourceText ToSourceText(ArrayBuilder<SourceText> segments, SourceText original, bool adjustSegments)
194return SourceText.From(string.Empty, original.Encoding, original.ChecksumAlgorithm);
206private static void RemoveSplitLineBreaksAndEmptySegments(ArrayBuilder<SourceText> segments)
216var prevSegment = segments[i - 1];
217var curSegment = segments[i];
223segments.Insert(i, SourceText.From("\r\n"));
246private static void ReduceSegmentCountIfNecessary(ArrayBuilder<SourceText> segments)
267private static int GetMinimalSegmentSizeToUseForCombining(ArrayBuilder<SourceText> segments)
287private static int GetSegmentCountIfCombined(ArrayBuilder<SourceText> segments, int segmentSize)
322private static void CombineSegments(ArrayBuilder<SourceText> segments, int segmentSize)
354var newText = writer.ToSourceText();
363private static readonly ObjectPool<HashSet<SourceText>> s_uniqueSourcesPool
364= new ObjectPool<HashSet<SourceText>>(() => new HashSet<SourceText>(), 5);
369private static void ComputeLengthAndStorageSize(IReadOnlyList<SourceText> segments, out int length, out int size)
376var segment = segments[i];
382foreach (var segment in uniqueSources)
394private static void TrimInaccessibleText(ArrayBuilder<SourceText> segments)
406foreach (var segment in segments)
446var segment = compositeText.Segments[i];
480var segment = _compositeText.Segments[segmentIndex];
500var firstSegment = _compositeText.Segments[firstSegmentIndexInclusive];
510var nextSegment = _compositeText.Segments[nextSegmentIndex];
523var lastSegment = _compositeText.Segments[lastSegmentIndexInclusive];
561var previousSegment = _compositeText.Segments[firstSegmentIndexInclusive - 1];
Text\LargeText.cs (7)
18/// A <see cref="SourceText"/> optimized for very large sources. The text is stored as
26internal const int ChunkSize = SourceText.LargeObjectHeapLimitInChars; // 40K Unicode chars is 80KB which is less than the large object heap limit.
55internal static SourceText Decode(Stream stream, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
62return SourceText.From(string.Empty, encoding, checksumAlgorithm);
81internal static SourceText Decode(TextReader reader, int length, Encoding? encodingOpt, SourceHashAlgorithm checksumAlgorithm)
85return SourceText.From(string.Empty, encodingOpt, checksumAlgorithm);
227/// Called from <see cref="SourceText.Lines"/> to initialize the <see cref="TextLineCollection"/>. Thereafter,
Text\SourceText.cs (58)
91/// Constructs a <see cref="SourceText"/> from text in a string.
97/// If the encoding is not specified the resulting <see cref="SourceText"/> isn't debuggable.
98/// If an encoding-less <see cref="SourceText"/> is written to a file a <see cref="Encoding.UTF8"/> shall be used as a default.
105public static SourceText From(string text, Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
116/// Constructs a <see cref="SourceText"/> from text in a string.
123/// If the encoding is not specified the resulting <see cref="SourceText"/> isn't debuggable.
124/// If an encoding-less <see cref="SourceText"/> is written to a file a <see cref="Encoding.UTF8"/> shall be used as a default.
131public static SourceText From(
154public static SourceText From(Stream stream, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected)
158/// Constructs a <see cref="SourceText"/> from stream content.
180public static SourceText From(
225public static SourceText From(byte[] buffer, int length, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected)
229/// Constructs a <see cref="SourceText"/> from a byte array.
249public static SourceText From(
392/// If an encoding-less <see cref="SourceText"/> is written to a file a <see cref="Encoding.UTF8"/> shall be used as a default.
410internal virtual ImmutableArray<SourceText> Segments
412get { return ImmutableArray<SourceText>.Empty; }
415internal virtual SourceText StorageKey
471/// The container of this <see cref="SourceText"/>.
497/// Gets a <see cref="SourceText"/> that contains the characters in the specified span of this text.
499public virtual SourceText GetSubText(TextSpan span)
506return SourceText.From(string.Empty, this.Encoding, this.ChecksumAlgorithm);
519/// Returns a <see cref="SourceText"/> that has the contents of this text including and after the start position.
521public SourceText GetSubText(int start)
539/// Write this <see cref="SourceText"/> to a text writer.
576/// that were used to produce this <see cref="SourceText"/> (if any of the <c>From</c> methods were used that
577/// take a <c>byte[]</c> or <see cref="Stream"/>). Otherwise, computed by writing this <see cref="SourceText"/>
582/// Two different <see cref="SourceText"/> instances with the same content (see <see cref="ContentEquals"/>) may
588/// Similarly, two different <see cref="SourceText"/> instances with <em>different</em> contents can have the
609/// Produces a hash of this <see cref="SourceText"/> based solely on the contents it contains. Two different
610/// <see cref="SourceText"/> instances that are <see cref="ContentEquals"/> will have the same content hash. Two
611/// instances of <see cref="SourceText"/> with different content are virtually certain to not have the same
771public virtual SourceText WithChanges(IEnumerable<TextChange> changes)
783var segments = ArrayBuilder<SourceText>.GetInstance();
821var subText = this.GetSubText(new TextSpan(position, change.Span.Start - position));
827var segment = SourceText.From(change.NewText!, this.Encoding, this.ChecksumAlgorithm);
844var subText = this.GetSubText(new TextSpan(position, this.Length - position));
848var newText = CompositeText.ToSourceText(segments, this, adjustSegments: true);
872/// <exception cref="ArgumentException">If any changes are not in bounds of this <see cref="SourceText"/>.</exception>
874public SourceText WithChanges(params TextChange[] changes)
882public SourceText Replace(TextSpan span, string newText)
890public SourceText Replace(int start, int length, string newText)
900public virtual IReadOnlyList<TextChangeRange> GetChangeRanges(SourceText oldText)
922public virtual IReadOnlyList<TextChange> GetTextChanges(SourceText oldText)
1019private readonly SourceText _text;
1023public LineInfo(SourceText text, SegmentedList<uint> lineStarts)
1202/// Compares the content with content of another <see cref="SourceText"/>.
1204public bool ContentEquals(SourceText other)
1229/// Implements equality comparison of the content of two different instances of <see cref="SourceText"/>.
1231protected virtual bool ContentEqualsImpl(SourceText other)
1325private readonly SourceText _text;
1327public StaticContainer(SourceText text)
1332public override SourceText CurrentText => _text;
1366/// Otherwise, returns a <see cref="SourceText"/> with the same <see cref="ChecksumAlgorithm"/> as <paramref name="checksumAlgorithm"/>, potentially by wrapping this instance.
1368internal SourceText WithChecksumAlgorithmIfAny(SourceHashAlgorithm checksumAlgorithm)
1378private readonly SourceText _underlying;
1380public SourceTextWithAlgorithm(SourceText underlying, SourceHashAlgorithm checksumAlgorithm) : base(checksumAlgorithm: checksumAlgorithm)
Microsoft.CodeAnalysis.Analyzers (121)
MetaAnalyzers\ReleaseTrackingHelper.cs (8)
46SourceText sourceText,
47Action<string, Version, string, SourceText, TextLine> onDuplicateEntryInRelease,
48Action<TextLine, InvalidEntryKind, string, SourceText> onInvalidEntry,
440public SourceText SourceText { get; }
449TextSpan span, SourceText sourceText,
458TextSpan span, SourceText sourceText,
478TextSpan span, SourceText sourceText,
497TextSpan span, SourceText sourceText,
src\Compilers\Core\Portable\EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\SourceTextExtensions_SharedWithCodeStyle.cs (5)
16public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
32this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
44this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
82public static bool AreOnSameLine(this SourceText text, SyntaxToken token1, SyntaxToken token2)
87public static bool AreOnSameLine(this SourceText text, int pos1, int pos2)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Services\RefactoringHelpers\AbstractRefactoringHelpers.cs (6)
25public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
42private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span)
60SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray<TSyntaxNode> result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
179SourceText sourceText, SyntaxNode root, int location)
251SourceText sourceText, SyntaxToken tokenOnLocation, int location)
533SourceText sourceText,
Microsoft.CodeAnalysis.AnalyzerUtilities (68)
src\Compilers\Core\Portable\EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\SourceTextExtensions_SharedWithCodeStyle.cs (5)
16public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
32this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
44this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
82public static bool AreOnSameLine(this SourceText text, SyntaxToken token1, SyntaxToken token2)
87public static bool AreOnSameLine(this SourceText text, int pos1, int pos2)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Services\RefactoringHelpers\AbstractRefactoringHelpers.cs (6)
25public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
42private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span)
60SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray<TSyntaxNode> result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
179SourceText sourceText, SyntaxNode root, int location)
251SourceText sourceText, SyntaxToken tokenOnLocation, int location)
533SourceText sourceText,
Microsoft.CodeAnalysis.BannedApiAnalyzers (92)
src\Compilers\Core\Portable\EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\SourceTextExtensions_SharedWithCodeStyle.cs (5)
16public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
32this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
44this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
82public static bool AreOnSameLine(this SourceText text, SyntaxToken token1, SyntaxToken token2)
87public static bool AreOnSameLine(this SourceText text, int pos1, int pos2)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Services\RefactoringHelpers\AbstractRefactoringHelpers.cs (6)
25public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
42private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span)
60SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray<TSyntaxNode> result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
179SourceText sourceText, SyntaxNode root, int location)
251SourceText sourceText, SyntaxToken tokenOnLocation, int location)
533SourceText sourceText,
Microsoft.CodeAnalysis.CodeStyle (66)
src\Compilers\Core\Portable\EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\SourceTextExtensions_SharedWithCodeStyle.cs (5)
16public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
32this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
44this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
82public static bool AreOnSameLine(this SourceText text, SyntaxToken token1, SyntaxToken token2)
87public static bool AreOnSameLine(this SourceText text, int pos1, int pos2)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Services\RefactoringHelpers\AbstractRefactoringHelpers.cs (6)
25public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
42private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span)
60SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray<TSyntaxNode> result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
179SourceText sourceText, SyntaxNode root, int location)
251SourceText sourceText, SyntaxToken tokenOnLocation, int location)
533SourceText sourceText,
Microsoft.CodeAnalysis.CodeStyle.Fixes (39)
src\Analyzers\Core\CodeFixes\ConflictMarkerResolution\AbstractConflictMarkerCodeFixProvider.cs (15)
75var text = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
85SyntaxNode root, SourceText text, int position,
146SourceText text, int position,
210var text = startLine.Text!;
228var text = startLine.Text!;
246var text = currentLine.Text!;
316Action<SourceText, ArrayBuilder<TextChange>, int, int, int, int> addEdits,
319var text = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
324var finalText = text.WithChanges(edits);
329SourceText text, ArrayBuilder<TextChange> edits,
342SourceText text, ArrayBuilder<TextChange> edits,
355SourceText text, ArrayBuilder<TextChange> edits,
389private static int GetEndIncludingLineBreak(SourceText text, int position)
405var text = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
444var finalText = text.WithChanges(edits);
Microsoft.CodeAnalysis.CodeStyle.UnitTestUtilities (5)
Microsoft.CodeAnalysis.CSharp (52)
Syntax\CSharpSyntaxTree.cs (10)
379internal static SyntaxTree CreateForDebugger(CSharpSyntaxNode root, SourceText text, CSharpParseOptions options)
415SourceText text,
459return ParseText(SourceText.From(text, encoding, SourceHashAlgorithm.Sha1), options, path, diagnosticOptions, isGeneratedCode, cancellationToken);
470SourceText text,
490SourceText text,
535public override SyntaxTree WithChangedText(SourceText newText)
538if (this.TryGetText(out SourceText? oldText))
554private SyntaxTree WithChanges(SourceText newText, IReadOnlyList<TextChangeRange> changes)
903SourceText text,
920=> ParseText(SourceText.From(text, encoding, SourceHashAlgorithm.Sha1), options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken);
Syntax\SyntaxFactory.cs (10)
1591return CSharpSyntaxTree.ParseText(SourceText.From(text, encoding, SourceHashAlgorithm.Sha1), (CSharpParseOptions?)options, path, diagnosticOptions: null, isGeneratedCode: null, cancellationToken);
1595/// <inheritdoc cref="CSharpSyntaxTree.ParseText(SourceText, CSharpParseOptions?, string, CancellationToken)"/>
1597SourceText text,
1710public static SyntaxTokenParser CreateTokenParser(SourceText sourceText, CSharpParseOptions? options = null)
1950private static SourceText MakeSourceText(string text, int offset)
1952return SourceText.From(text, Encoding.UTF8).GetSubText(offset);
2838return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken);
2845SourceText text,
2866return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode, cancellationToken);
2873SourceText text,
Microsoft.CodeAnalysis.CSharp.CodeStyle (21)
Microsoft.CodeAnalysis.CSharp.CodeStyle.Fixes (35)
Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests (3)
Microsoft.CodeAnalysis.CSharp.EditorFeatures (49)
StringCopyPaste\StringCopyPasteHelpers.cs (12)
30public static char SafeCharAt(SourceText text, int index)
105public static int GetFirstNonWhitespaceIndex(SourceText text, TextLine line)
170public static int SkipU8Suffix(SourceText text, int end)
184public static int GetLongestQuoteSequence(SourceText text, TextSpan span)
187public static int GetLongestOpenBraceSequence(SourceText text, TextSpan span)
190public static int GetLongestCloseBraceSequence(SourceText text, TextSpan span)
198private static int GetLongestCharacterSequence(SourceText text, TextSpan span, char character)
506var text = SourceText.From(change.NewText);
542private static string? GetCommonIndentationPrefix(string? commonIndentPrefix, SourceText text, TextSpan lineWhitespaceSpan)
563public static bool RawContentMustBeMultiLine(SourceText text, ImmutableArray<TextSpan> spans)
582public static bool SpansContainsNewLine(SourceText text, ImmutableArray<TextSpan> spans)
Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests (128)
PdbSourceDocument\AbstractPdbSourceDocumentTests.cs (10)
120protected static async Task<(SourceText?, TextSpan)> GetGeneratedSourceTextAsync(
168var actual = await document.GetTextAsync();
190var sourceText = SourceText.From(source, encoding: encoding ?? Encoding.UTF8);
198SourceText source,
243protected static void CompileTestSource(string path, SourceText source, Project project, Location pdbLocation, Location sourceLocation, bool buildReferenceAssembly, bool windowsPdb, Encoding? fallbackEncoding = null)
251protected static void CompileTestSource(string dllFilePath, string sourceCodePath, string? pdbFilePath, string assemblyName, SourceText source, Project project, Location pdbLocation, Location sourceLocation, bool buildReferenceAssembly, bool windowsPdb, Encoding? fallbackEncoding = null)
256protected static void CompileTestSource(string dllFilePath, string[] sourceCodePaths, string? pdbFilePath, string assemblyName, SourceText[] sources, Project project, Location pdbLocation, Location sourceLocation, bool buildReferenceAssembly, bool windowsPdb, Encoding? fallbackEncoding = null)
337protected sealed class StaticSourceTextContainer(SourceText sourceText) : SourceTextContainer
339public override SourceText CurrentText => sourceText;
PdbSourceDocument\ImplementationAssemblyLookupServiceTests.cs (28)
39var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8);
73var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8);
111var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8);
142var sourceText = SourceText.From(metadataSource, Encoding.UTF8);
167sourceText = SourceText.From("""
199var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8);
223sourceText = SourceText.From("""
256var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8);
280sourceText = SourceText.From("""
307var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8);
331sourceText = SourceText.From("""
354var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8);
378sourceText = SourceText.From("""
412var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8);
436sourceText = SourceText.From("""
474var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8);
498var typeForwardSourceText = SourceText.From(typeForwardSource, Encoding.UTF8);
PdbSourceDocument\PdbSourceDocumentTests.cs (23)
327var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8);
353var sourceText = SourceText.From(metadataSource, encoding: Encoding.UTF8);
385var sourceText = SourceText.From(metadataSource, Encoding.UTF8);
426var sourceText = SourceText.From(metadataSource, Encoding.UTF8);
453sourceText = SourceText.From("""
623CompileTestSource(path, SourceText.From("""
692var encodedSourceText = EncodedStringText.Create(ms, encoding, canBeEmbedded: true);
721var encodedSourceText = EncodedStringText.Create(ms, encoding, canBeEmbedded: true);
750var encodedSourceText = EncodedStringText.Create(ms, encoding, canBeEmbedded: true);
775var sourceText = SourceText.From(source, Encoding.UTF8);
826var sourceText1 = SourceText.From(source1, Encoding.UTF8);
827var sourceText2 = SourceText.From(source2, Encoding.UTF8);
872var result = service.TryAddDocumentToWorkspace(requestPath, new StaticSourceTextContainer(SourceText.From(string.Empty)), out var documentId);
891var openResult = service.TryAddDocumentToWorkspace(file.FilePath, new StaticSourceTextContainer(SourceText.From(string.Empty)), out var documentId);
934var openResult = service.TryAddDocumentToWorkspace(fileOne.FilePath, new StaticSourceTextContainer(SourceText.From(string.Empty)), out var documentId);
945Assert.Throws<System.ArgumentException>(() => service.TryAddDocumentToWorkspace(fileTwo.FilePath, new StaticSourceTextContainer(SourceText.From(string.Empty)), out var documentIdTwo));
Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests (5)
Microsoft.CodeAnalysis.CSharp.Emit.UnitTests (3)
Microsoft.CodeAnalysis.CSharp.Emit2.UnitTests (6)
PDB\PDBTests.cs (4)
47var tree3 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class C { }", encoding: null), path: "Bar.cs");
68var tree4 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class D { public void F() { } }", new UTF8Encoding(false, false)), path: "Baz.cs");
104context.AddSource("hint2", SourceText.From("class G2 { void F() {} }", Encoding.UTF8, checksumAlgorithm: SourceHashAlgorithm.Sha256));
106Assert.Throws<ArgumentException>(() => context.AddSource("hint3", SourceText.From("class G3 { void F() {} }", encoding: null, checksumAlgorithm: SourceHashAlgorithm.Sha256)));
Microsoft.CodeAnalysis.CSharp.Features (151)
Completion\CompletionProviders\CompletionUtilities.cs (8)
20internal static TextSpan GetCompletionItemSpan(SourceText text, int position)
60internal static bool IsTriggerCharacter(SourceText text, int characterPosition, in CompletionOptions options)
99internal static bool IsCompilerDirectiveTriggerCharacter(SourceText text, int characterPosition)
117internal static bool IsTriggerCharacterOrArgumentListCharacter(SourceText text, int characterPosition, in CompletionOptions options)
120private static bool IsArgumentListCharacter(SourceText text, int characterPosition)
126internal static bool IsTriggerAfterSpaceOrStartOfWordCharacter(SourceText text, int characterPosition, in CompletionOptions options)
136private static bool SpaceTypedNotBeforeWord(char ch, SourceText text, int characterPosition)
139public static bool IsStartingNewWord(SourceText text, int characterPosition)
StringIndentation\CSharpStringIndentationService.cs (5)
31var text = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
79SourceText text, SyntaxToken token, ref TemporaryArray<StringIndentationRegion> result, CancellationToken cancellationToken)
94SourceText text, InterpolatedStringExpressionSyntax interpolatedString, ref TemporaryArray<StringIndentationRegion> result, CancellationToken cancellationToken)
137private static bool IgnoreInterpolation(SourceText text, int offset, InterpolationSyntax interpolation)
158private static bool TryGetIndentSpan(SourceText text, ExpressionSyntax expression, out int offset, out TextSpan indentSpan)
Microsoft.CodeAnalysis.CSharp.Features.UnitTests (12)
EditAndContinue\CSharpEditAndContinueAnalyzerTests.cs (12)
296var oldText = await oldDocument.GetTextAsync();
299var newSolution = oldSolution.WithDocumentText(documentId, SourceText.From(source2));
301var newText = await newDocument.GetTextAsync();
364var newSolution = oldSolution.WithDocumentText(documentId, SourceText.From(source2));
428var newSolution = oldSolution.WithDocumentText(documentId, SourceText.From(source2));
510var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2));
580var newSolution = oldSolution.WithDocumentText(documentId, SourceText.From(source2));
620var newSolution = oldSolution.WithDocumentText(documentId, SourceText.From(source2));
661var newSolution = oldSolution.AddDocument(newDocId, "goo.cs", SourceText.From(source2), filePath: Path.Combine(TempRoot.Root, "goo.cs"));
707var newSolution = oldSolution.AddDocument(newDocId, "goo.cs", SourceText.From(source2), filePath: Path.Combine(TempRoot.Root, "goo.cs"));
740var newSolution = oldSolution.AddDocument(documentId, "goo.cs", SourceText.From(source2), filePath: filePath);
797var newSolution = oldSolution.WithDocumentText(documentId, SourceText.From(source2));
Microsoft.CodeAnalysis.CSharp.Scripting (3)
CSharpScript.cs (2)
37return Script.CreateInitialScript<T>(CSharpScriptCompiler.Instance, SourceText.From(code, options?.FileEncoding, SourceHashAlgorithms.Default), options, globalsType, assemblyLoader);
54return Script.CreateInitialScript<T>(CSharpScriptCompiler.Instance, SourceText.From(code, options?.FileEncoding), options, globalsType, assemblyLoader);
Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests (56)
SourceGeneration\AdditionalSourcesCollectionTests.cs (23)
54asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8));
70asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8));
110var exception = Assert.Throws<ArgumentException>(nameof(hintName), () => asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8)));
120asc.Add("file3.cs", SourceText.From("", Encoding.UTF8));
121asc.Add("file1.cs", SourceText.From("", Encoding.UTF8));
122asc.Add("file2.cs", SourceText.From("", Encoding.UTF8));
123asc.Add("file5.cs", SourceText.From("", Encoding.UTF8));
124asc.Add("file4.cs", SourceText.From("", Encoding.UTF8));
144asc.Add(names[i], SourceText.From("", Encoding.UTF8));
166asc.Add(hintName1, SourceText.From("", Encoding.UTF8));
167var exception = Assert.Throws<ArgumentException>("hintName", () => asc.Add(hintName2, SourceText.From("", Encoding.UTF8)));
176asc.Add("hintName1", SourceText.From("", Encoding.UTF8));
177asc.Add("hintName2", SourceText.From("", Encoding.UTF8));
180asc2.Add("hintName3", SourceText.From("", Encoding.UTF8));
181asc2.Add("hintName1", SourceText.From("", Encoding.UTF8));
200asc.Add(addHintName, SourceText.From("", Encoding.UTF8));
212asc.Add(addHintName, SourceText.From("", Encoding.UTF8));
224asc.Add("file1.cs", SourceText.From("", Encoding.UTF8));
225asc.Add("file2.cs", SourceText.From("", Encoding.UTF32));
226asc.Add("file3.cs", SourceText.From("", Encoding.Unicode));
229Assert.Throws<ArgumentException>(() => asc.Add("file4.cs", SourceText.From("")));
232Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null)));
234var exception = Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null)));
SourceGeneration\GeneratorDriverTests.cs (12)
464sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
467Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)));
470Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8)));
495spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
498Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)));
501Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8)));
508spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
590var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); });
620var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); sgc.AddSource("test2", SourceText.From("public class E {}", Encoding.UTF8)); });
760e.AddSource("a", SourceText.From("public class E {}", Encoding.UTF8));
784var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("a", SourceText.From("")); });
Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests (5)
Microsoft.CodeAnalysis.CSharp.Syntax.UnitTests (337)
IncrementalParsing\IncrementalParsingTests.cs (228)
31var itext = SourceText.From(text);
38var itext = SourceText.From(text);
494var text = tree.GetText();
526var text = tree.GetText();
567var text = tree.GetText();
618var initialText = initialTree.GetText();
626var withOpenBraceDeletedText = initialText.WithChanges(new TextChange(openBraceLine.SpanIncludingLineBreak, ""));
837var withCloseBraceDeletedText = withOpenBraceDeletedText.WithChanges(new TextChange(closeBraceLine.SpanIncludingLineBreak, ""));
1391var text = SourceText.From(@"partial class C{}");
1395var newText = text.WithChanges(new TextChange(new TextSpan(0, 8), ""));
1405var text = SourceText.From(@"partial class C{}");
1409var newText = text.WithChanges(new TextChange(new TextSpan(0, 8), ""));
1419SourceText oldText = SourceText.From(@"
1435SourceText oldText = SourceText.From(@"
1451SourceText oldText = SourceText.From(@"
1468SourceText oldText = SourceText.From(@"
1484SourceText oldText = SourceText.From(@"
1497SourceText oldText = SourceText.From(@"
1513SourceText oldText = SourceText.From(@"
1525SourceText oldText = SourceText.From(@"
1537SourceText oldText = SourceText.From(@" class A
1553SourceText oldText = SourceText.From(@"public class TestClass
1566SourceText oldText = SourceText.From(@"using System;
1581SourceText oldText = SourceText.From(@"public class MyClass {
1593SourceText oldText = SourceText.From(@"
1607SourceText startingText = SourceText.From(@"
1628SourceText startingText = SourceText.From(@"
1647SourceText startingText = SourceText.From(@"
1667SourceText oldText = SourceText.From(@"class MyClass
1687SourceText oldText = SourceText.From(@"
1711SourceText oldText = SourceText.From(@"
1735SourceText oldText = SourceText.From(@"interface IGoo
1759SourceText oldText = SourceText.From(@"interface IGoo
1783SourceText oldText = SourceText.From(@"using System.Runtime.CompilerServices;
1805SourceText oldText = SourceText.From(@"class A
1829SourceText oldText = SourceText.From(@"public class MyClass {
1851SourceText oldText = SourceText.From(@"public class MyClass {
1942SourceText oldText = SourceText.From(@"class filesystem{
1961SourceText oldText = SourceText.From(@"class CSTR020mod{ public static void CSTR020() { ON ERROR GOTO ErrorTrap; } }");
1977SourceText oldText = SourceText.From(@"class A
1997SourceText oldText = SourceText.From(@"public class DynClassDrived
2019SourceText oldText = SourceText.From(@"public class MemberClass
2039SourceText oldText = SourceText.From(@"public class MemberClass
2058SourceText oldText = SourceText.From(@"class Test
2080SourceText oldText = SourceText.From(
2107SourceText oldText = SourceText.From(
2133SourceText oldText = SourceText.From(
2158SourceText oldText = SourceText.From(
2180SourceText oldText = SourceText.From(
2235SourceText oldText = SourceText.From(
2257SourceText oldText = SourceText.From(
2278SourceText oldText = SourceText.From(
2299SourceText oldText = SourceText.From(
2322SourceText oldText = SourceText.From(
2343SourceText oldText = SourceText.From(
2363SourceText oldText = SourceText.From(
2381SourceText oldText = SourceText.From(
2402SourceText oldText = SourceText.From(
2425SourceText oldText = SourceText.From(
2442SourceText oldText = SourceText.From(
2460SourceText oldText = SourceText.From(
2478SourceText oldText = SourceText.From(
2499SourceText oldText = SourceText.From(
2534SourceText oldText = SourceText.From(
2558SourceText oldText = SourceText.From(
2576SourceText oldText = SourceText.From(
2594SourceText oldText = SourceText.From(
2613SourceText oldText = SourceText.From(
2644SourceText oldText = SourceText.From(
2669SourceText oldText = SourceText.From(
2688SourceText oldText = SourceText.From(
2706SourceText oldText = SourceText.From(
2725SourceText oldText = SourceText.From(
2744SourceText oldText = SourceText.From(
2765SourceText oldText = SourceText.From(
2784SourceText oldText = SourceText.From(
2811SourceText oldText = SourceText.From(
2839SourceText oldText = SourceText.From(
2861SourceText oldText = SourceText.From(
2880SourceText oldText = SourceText.From(
2912SourceText oldText = SourceText.From(
2945SourceText oldText = SourceText.From(
2971SourceText oldText = SourceText.From(
2996SourceText oldText = SourceText.From(
3026SourceText oldText = SourceText.From(
3055SourceText oldText = SourceText.From(
3076SourceText oldText = SourceText.From(
3108SourceText oldText = SourceText.From(
3136SourceText oldText = SourceText.From(
3174var text = SourceText.From(str);
3177var text2 = text.WithChanges(
3192SourceText oldText = SourceText.From(@"
3200var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), "{"));
3210SourceText oldText = SourceText.From(@"System.Console.WriteLine(true)
3216var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), @"System.Console.WriteLine(false)
3239SourceText oldText = SourceText.From(@"System.Console.WriteLine(true)
3245var newText = oldText.WithInsertAt(
3269SourceText oldText = SourceText.From(@"System.Console.WriteLine(true)
3275var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), @"if (false)
3329var oldIText = oldTree.GetText();
3333var newIText = oldIText.WithChanges(change);
3407var currIText = currTree.GetText();
3447var currIText = currTree.GetText();
3527var oldText = SourceText.From(items[0]);
3531var newText = oldText.WithChanges(change); // f is a method decl parameter
3558var oldText = SourceText.From(@"
3584var newText = SourceText.From(@"
3627var text = tree.GetText();
3648var text = tree.GetText();
3669var text = tree.GetText();
3690var text = tree.GetText();
3711var text = tree.GetText();
3732var text = tree.GetText();
3756var text = tree.GetText();
3780var text = tree.GetText();
3804var text = tree.GetText();
3828var text = tree.GetText();
3852var text = tree.GetText();
3878var text = tree.GetText();
3904var text = tree.GetText();
3929var text = tree.GetText();
3955var text = tree.GetText();
3973var text = tree.GetText();
3991var text = tree.GetText();
4009var text = tree.GetText();
4024var text = tree.GetText();
4038var text = tree.GetText();
4052var text = tree.GetText();
4090var text = tree.GetText();
4111var text = tree.GetText();
4154private static void CommentOutText(SourceText oldText, int locationOfChange, int widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree)
4156var newText = oldText.WithChanges(
4166private static void RemoveText(SourceText oldText, int locationOfChange, int widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree)
4168var newText = oldText.WithChanges(new TextChange(new TextSpan(locationOfChange, widthOfChange), ""));
4188private static void CharByCharIncrementalParse(SourceText oldText, char newChar, out SyntaxTree incrementalTree, out SyntaxTree parsedTree)
4194var newText = oldText.WithChanges(new TextChange(new TextSpan(oldText.Length, 0), newChar.ToString()));
4199private static void TokenByTokenBottomUp(SourceText oldText, string token, out SyntaxTree incrementalTree, out SyntaxTree parsedTree)
4202SourceText newText = SourceText.From(token + oldText.ToString());
Syntax\SyntaxTreeTests.cs (15)
86SyntaxTreeFactoryKind.ParseText => CSharpSyntaxTree.ParseText(SourceText.From(source, Encoding.UTF8, SourceHashAlgorithm.Sha256), parseOptions),
87SyntaxTreeFactoryKind.Subclass => new MockCSharpSyntaxTree(root, SourceText.From(source, Encoding.UTF8, SourceHashAlgorithm.Sha256), parseOptions),
142SourceText.From(""),
149var newTree = tree.WithChangedText(SourceText.From("class C { }"));
157SourceText.From(""),
173SourceText.From(""),
189SourceText.From(""),
247var newText = newTree.GetText();
259var oldText = SourceText.From("class B {}", Encoding.Unicode, SourceHashAlgorithms.Default);
265var newText = newTree.GetText();
289var newText = newTree.GetText();
301var oldText = SourceText.From("class B {}", Encoding.Unicode, SourceHashAlgorithms.Default);
305var newText = newTree.GetText();
TextExtensions.cs (18)
22public static SourceText WithReplace(this SourceText text, int offset, int length, string newText)
27return SourceText.From(newFullText);
30public static SourceText WithReplaceFirst(this SourceText text, string oldText, string newText)
37return SourceText.From(newFullText);
40public static SourceText WithReplace(this SourceText text, int startIndex, string oldText, string newText)
47return SourceText.From(newFullText);
50public static SourceText WithInsertAt(this SourceText text, int offset, string newText)
55public static SourceText WithInsertBefore(this SourceText text, string existingText, string newText)
61return SourceText.From(newFullText);
64public static SourceText WithRemoveAt(this SourceText text, int offset, int length)
69public static SourceText WithRemoveFirst(this SourceText text, string oldText)
Microsoft.CodeAnalysis.CSharp.Test.Utilities (6)
Microsoft.CodeAnalysis.CSharp.Workspaces (30)
Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests (3)
Microsoft.CodeAnalysis.EditorFeatures (138)
EditorConfigSettings\Updater\SettingsUpdateHelper.cs (13)
24public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText,
46public static SourceText? TryUpdateAnalyzerConfigDocument(
47SourceText originalText,
102public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText,
106var updatedText = originalText;
111SourceText? newText;
154private static (SourceText? newText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) UpdateIfExistsInFile(SourceText editorConfigText,
291private static (SourceText? newText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) AddMissingRule(SourceText editorConfigText,
349var result = editorConfigText.WithChanges(new TextChange(new TextSpan(editorConfigText.Length, 0), prefix + newEntry));
EditorConfigSettings\Updater\SettingsUpdaterBase.cs (10)
24protected abstract SourceText? GetNewText(SourceText analyzerConfigDocument, IReadOnlyList<(TOption option, TValue value)> settingsToUpdate, CancellationToken token);
50public async Task<SourceText?> GetChangedEditorConfigAsync(AnalyzerConfigDocument? analyzerConfigDocument, CancellationToken token)
55var originalText = await analyzerConfigDocument.GetValueTextAsync(token).ConfigureAwait(false);
58var newText = GetNewText(originalText, _queue, token);
78var newText = await GetChangedEditorConfigAsync(analyzerConfigDocument, token).ConfigureAwait(false);
84var originalText = await analyzerConfigDocument.GetValueTextAsync(token).ConfigureAwait(false);
88public async Task<SourceText?> GetChangedEditorConfigAsync(SourceText originalText, CancellationToken token)
92var newText = GetNewText(originalText, _queue, token);
InlineRename\InlineRenameSession.cs (7)
193private sealed class NullTextBufferException(Document document, SourceText text) : Exception("Cannot retrieve textbuffer from document.")
197private readonly SourceText _text = text;
213Contract.ThrowIfFalse(document.TryGetText(out var text));
859async Task<ImmutableArray<(DocumentId documentId, string newName, SyntaxNode newRoot, SourceText newText)>> CalculateFinalDocumentChangesAsync(
865using var _ = PooledObjects.ArrayBuilder<(DocumentId documentId, string newName, SyntaxNode newRoot, SourceText newText)>.GetInstance(out var result);
892ImmutableArray<(DocumentId documentId, string newName, SyntaxNode newRoot, SourceText newText)> documentChanges)
934private async Task<Solution> GetFinalSolutionAsync(ImmutableArray<(DocumentId, string, SyntaxNode, SourceText)> documentChanges)
Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities (21)
Microsoft.CodeAnalysis.EditorFeatures.Text (22)
Microsoft.CodeAnalysis.EditorFeatures.UnitTests (53)
Diagnostics\DiagnosticAnalyzerServiceTests.cs (8)
164project = project.AddAnalyzerConfigDocument(".editorconfig", filePath: "z:\\.editorconfig", text: SourceText.From($"""
172var document = project.AddDocument("test.cs", SourceText.From("class A {}"), filePath: "z:\\test.cs");
255loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class A {}"), VersionStamp.Create(), filePath: "test.cs")),
298text: SourceText.From($"""
331loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class A {}"), VersionStamp.Create(), filePath: "test.cs")),
406var text = await additionalDoc.GetTextAsync();
568var text = await document.GetTextAsync();
946return workspace.AddDocument(project.Id, "Empty.cs", SourceText.From("class A { B B {get} }"));
Microsoft.CodeAnalysis.ExternalAccess.Copilot (2)
SemanticSearch\CopilotSemanticSearchUtilities.cs (2)
30public static SyntaxTree CreateSyntaxTree(SolutionServices services, string language, string? filePath, ParseOptions options, SourceText? text, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, SyntaxNode root)
33public static SyntaxTree ParseSyntaxTree(SolutionServices services, string language, string? filePath, ParseOptions options, SourceText text, CancellationToken cancellationToken)
Microsoft.CodeAnalysis.ExternalAccess.FSharp (13)
Completion\FSharpCompletionProviderBase.cs (3)
13public sealed override bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options)
16internal sealed override bool ShouldTriggerCompletion(Host.LanguageServices languageServices, SourceText text, int caretPosition, CompletionTrigger trigger, CompletionOptions options, OptionSet passthroughOptions)
19protected abstract bool ShouldTriggerCompletionImpl(SourceText text, int caretPosition, CompletionTrigger trigger);
Microsoft.CodeAnalysis.ExternalAccess.HotReload (6)
Api\HotReloadMSBuildWorkspace.cs (6)
182var oldText = await textDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
185var newText = await GetSourceTextAsync(path, oldText.Encoding, oldText.ChecksumAlgorithm, cancellationToken).ConfigureAwait(false);
210private static async ValueTask<SourceText> GetSourceTextAsync(string filePath, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken)
219SourceText sourceText;
222sourceText = SourceText.From(stream, encoding, checksumAlgorithm);
237sourceText = SourceText.From(stream, encoding, checksumAlgorithm);
Microsoft.CodeAnalysis.ExternalAccess.HotReload.UnitTests (6)
HotReloadMSBuildWorkspaceTests.cs (3)
46loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class A;", Encoding.UTF8, SourceHashAlgorithm.Sha256), VersionStamp.Create())))
83loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class C;", Encoding.UTF8, SourceHashAlgorithm.Sha256), VersionStamp.Create()))),
88loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class C;", Encoding.UTF8, SourceHashAlgorithm.Sha256), VersionStamp.Create())))
Microsoft.CodeAnalysis.ExternalAccess.OmniSharp (3)
Microsoft.CodeAnalysis.ExternalAccess.Razor.Features (5)
Microsoft.CodeAnalysis.ExternalAccess.Xaml (1)
Microsoft.CodeAnalysis.Features (265)
Completion\CommonCompletionProvider.cs (4)
34public sealed override bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options)
42internal override bool ShouldTriggerCompletion(LanguageServices languageServices, SourceText text, int caretPosition, CompletionTrigger trigger, CompletionOptions options, OptionSet passThroughOptions)
45private bool ShouldTriggerCompletionImpl(SourceText text, int caretPosition, CompletionTrigger trigger, in CompletionOptions options)
50public virtual bool IsInsertionTrigger(SourceText text, int insertedCharacterPosition, CompletionOptions options)
Completion\CommonCompletionUtilities.cs (4)
27public static TextSpan GetWordSpan(SourceText text, int position,
33public static TextSpan GetWordSpan(SourceText text, int position,
60public static bool IsStartingNewWord(SourceText text, int characterPosition, Func<char, bool> isWordStartCharacter, Func<char, bool> isWordCharacter)
185internal static bool IsTextualTriggerString(SourceText text, int characterPosition, string value)
Completion\Providers\CompletionUtilities.cs (4)
73public static CompletionItem SetOriginalIdentifierEnd(CompletionItem item, int position, SourceText text, ISyntaxFactsService syntaxFacts)
82public static KeyValuePair<string, string> GetOriginalIdentifierEndProperty(int position, SourceText text, ISyntaxFactsService syntaxFacts)
85private static int ScanForwardThroughIdentifier(int start, SourceText text, ISyntaxFactsService syntaxFacts)
102public static int GetCurrentSpanEnd(CompletionItem item, SourceText text, ISyntaxFactsService syntaxFacts)
DocumentationComments\AbstractDocumentationCommentSnippetService.cs (8)
42private bool IsAtEndOfDocCommentTriviaOnBlankLine(SourceText text, int endPosition)
79var text = document.Text;
103private List<string>? GetDocumentationCommentLines(SyntaxToken token, SourceText text, in DocumentationCommentOptions options, out string? indentText, out int caretOffset, out int spanToReplaceLength)
145private List<string>? GetDocumentationStubLines(SyntaxToken token, SourceText text, in DocumentationCommentOptions options, out int caretOffset, out int spanToReplaceLength, out string? existingCommentText)
189var text = document.Text;
264var text = document.Text;
316var text = document.Text;
356var text = document.Text;
EditAndContinue\AbstractEditAndContinueAnalyzer.cs (9)
500private static readonly SourceText s_emptySource = SourceText.From("");
709void LogRudeEdits(ImmutableArray<RudeEditDiagnostic> diagnostics, SourceText text, string filePath)
732private static async ValueTask<(Document? document, SourceText text)> GetDocumentContentAsync(Project project, DocumentId documentId, CancellationToken cancellationToken)
734SourceText text;
946SourceText newText,
1109SourceText newText,
1484private static bool TryGetTrackedStatement(ImmutableArray<ActiveStatementLineSpan> activeStatementSpans, ActiveStatementId id, SourceText text, MemberBody body, [NotNullWhen(true)] out SyntaxNode? trackedStatement, out int trackedStatementPart)
2702SourceText newText,
EditAndContinue\CommittedSolution.cs (12)
233var sourceText = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
298var matchingSourceText = maybeMatchingSourceText.Value;
325private async ValueTask<(Optional<SourceText?> matchingSourceText, bool? hasDocument)> TryGetMatchingSourceTextAsync(Document document, SourceText sourceText, Document currentDocument, CancellationToken cancellationToken)
365private static async ValueTask<Optional<SourceText?>> TryGetMatchingSourceTextAsync(
367SourceText sourceText,
383var currentDocumentSourceText = await currentDocument.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
398return SourceText.From(text, defaultEncoding, checksumAlgorithm);
440private static bool IsMatchingSourceText(SourceText sourceText, ImmutableArray<byte> requiredChecksum, SourceHashAlgorithm checksumAlgorithm)
443private static Optional<SourceText?> TryGetPdbMatchingSourceTextFromDisk(
454var sourceText = SourceText.From(fileStream, defaultEncoding, checksumAlgorithm);
ExternalAccess\VSTypeScript\Api\VSTypeScriptCompletionProvider.cs (3)
15public sealed override bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options)
21internal sealed override bool ShouldTriggerCompletion(LanguageServices languageServices, SourceText text, int caretPosition, CompletionTrigger trigger, CompletionOptions options, OptionSet passThroughOptions)
24protected abstract bool ShouldTriggerCompletionImpl(SourceText text, int caretPosition, CompletionTrigger trigger, bool triggerOnTypingLetters);
src\Analyzers\Core\CodeFixes\ConflictMarkerResolution\AbstractConflictMarkerCodeFixProvider.cs (15)
75var text = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
85SyntaxNode root, SourceText text, int position,
146SourceText text, int position,
210var text = startLine.Text!;
228var text = startLine.Text!;
246var text = currentLine.Text!;
316Action<SourceText, ArrayBuilder<TextChange>, int, int, int, int> addEdits,
319var text = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
324var finalText = text.WithChanges(edits);
329SourceText text, ArrayBuilder<TextChange> edits,
342SourceText text, ArrayBuilder<TextChange> edits,
355SourceText text, ArrayBuilder<TextChange> edits,
389private static int GetEndIncludingLineBreak(SourceText text, int position)
405var text = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
444var finalText = text.WithChanges(edits);
Microsoft.CodeAnalysis.Features.Test.Utilities (22)
EditAndContinue\EditAndContinueWorkspaceTestBase.cs (8)
82internal static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig)
128var text = GetAnalyzerConfigText(analyzerConfig);
362IEnumerable<(SourceText text, string filePath)> sources,
481internal static SourceText CreateText(string source, Encoding? encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithms.Default)
484return SourceText.From(new MemoryStream(encoding.GetBytesWithPreamble(source)), encoding, checksumAlgorithm);
487internal static SourceText CreateTextFromFile(string path, Encoding? encoding = null)
490return SourceText.From(stream, encoding ?? Encoding.UTF8, SourceHashAlgorithms.Default);
516var sourceText = CreateText("class DTO {}");
Microsoft.CodeAnalysis.Features.UnitTests (50)
EditAndContinue\EditAndContinueWorkspaceServiceTests.cs (33)
66var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithms.Default), TestOptions.Regular, sourceFileA.Path);
67var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithms.Default), TestOptions.Regular, sourceFileB.Path);
68var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path);
239var source = CreateText("class C;");
934var sourceText = CreateText("class D {}");
998solution = solution.AddDocument(designTimeOnlyDocumentId, designTimeOnlyFileName, SourceText.From(sourceDesignTimeOnly, Encoding.UTF8), filePath: designTimeOnlyFilePath);
1017solution = solution.AddDocument(designTimeOnlyDocumentId, designTimeOnlyFileName, SourceText.From(sourceDesignTimeOnly, Encoding.UTF8), filePath: designTimeOnlyFilePath);
1220AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8, SourceHashAlgorithm.Sha1), filePath: sourceFile.Path);
1627AddDocument(documentId = DocumentId.CreateNewId(projectId), "test.cs", SourceText.From(editorSource, editorEncoding, SourceHashAlgorithm.Sha1), filePath: sourceFile.Path);
1658var documentText = await document.GetTextAsync(CancellationToken.None);
1659var committedText = await committedDocument.GetTextAsync(CancellationToken.None);
1667var committedText = await committedDocument.GetTextAsync(CancellationToken.None);
2560context.AddSource("generated.cs", SourceText.From("generated: " + additionalText, Encoding.UTF8, SourceHashAlgorithm.Sha256));
3079solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null, SourceHashAlgorithms.Default));
3148var sourceText0 = CreateText(source0, sjis, checksumAlg);
3149var sourceText1 = CreateText(source1, sjis, checksumAlg);
3150var sourceText2 = CreateText(source2, sjis, checksumAlg);
3198var committedDocumentText1 = await committedDocument1.GetTextAsync(CancellationToken.None);
3217var committedDocumentText2 = await committedDocument2.GetTextAsync(CancellationToken.None);
3345var sourceText1 = CreateText(source1);
4286var text = await debuggingSession.LastCommittedSolution.GetRequiredProject(document1.Project.Id).GetRequiredDocument(document1.Id).GetTextAsync();
4529var text2 = CreateText(source2);
4545var text0 = CreateText(source0);
4579var text3 = CreateText(source3);
4629var text2 = CreateText(source2);
4743var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None);
4744var sourceTextV2 = CreateText(sourceV2);
4823var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None);
4824var sourceTextV2 = CreateText(sourceV2);
4875var sourceText = CreateText("dummy1");
4948var text1 = await doc1.GetTextAsync();
4949var text2 = await doc2.GetTextAsync();
4951DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text)
Microsoft.CodeAnalysis.LanguageServer (7)
Microsoft.CodeAnalysis.LanguageServer.Protocol (114)
Handler\IDocumentChangeTracker.cs (4)
20ValueTask StartTrackingAsync(DocumentUri documentUri, SourceText initialText, string languageId, int lspVersion, CancellationToken cancellationToken);
21void UpdateTrackedDocument(DocumentUri documentUri, SourceText text, int lspVersion);
27public ValueTask StartTrackingAsync(DocumentUri documentUri, SourceText initialText, string languageId, int lspVersion, CancellationToken cancellationToken)
37public void UpdateTrackedDocument(DocumentUri documentUri, SourceText text, int lspVersion)
Handler\OnAutoInsert\OnAutoInsertHandler.cs (11)
139var sourceText = parsedDocument.Text;
168var sourceText = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
186var newSourceText = sourceText.WithChanges(textChanges);
194var indentedText = GetIndentedText(newSourceText, caretLine, desiredCaretLinePosition, options);
227static SourceText GetIndentedText(
228SourceText textToIndent,
238var indentedText = textToIndent.WithChanges(new TextChange(new TextSpan(lineToIndent.End, 0), indentText));
244var documentText = await oldDocument.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
249static string GetTextChangeTextWithCaretAtLocation(SourceText sourceText, TextChange textChange, LinePosition desiredCaretLinePosition)
285var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
292var sourceTextWithoutQuote = sourceText.WithChanges(new TextChange(new TextSpan(positionOfQuote, 1), string.Empty));
Workspaces\LspWorkspaceManager.cs (5)
106public async ValueTask StartTrackingAsync(DocumentUri uri, SourceText documentText, string languageId, int lspVersion, CancellationToken cancellationToken)
200public void UpdateTrackedDocument(DocumentUri uri, SourceText newSourceText, int lspVersion)
466ImmutableArray<(SourceGeneratedDocumentIdentity Identity, DateTime Generated, SourceText Text)> sourceGeneratedDocuments,
510private static async ValueTask<bool> AreChecksumsEqualAsync(TextDocument document, SourceText lspText, CancellationToken cancellationToken)
512var documentText = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
Microsoft.CodeAnalysis.LanguageServer.Protocol.UnitTests (113)
Completion\CompletionFeaturesTests.cs (4)
596Project project, LanguageServices languageServices, SourceText text, int caretPosition, CompletionTrigger trigger,
610var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
897Project project, LanguageServices languageServices, SourceText text, int caretPosition, CompletionTrigger trigger,
911var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
Workspaces\LspWorkspaceManagerTests.cs (9)
85await testLspServer.TestWorkspace.ChangeDocumentAsync(firstDocument.Id, SourceText.From($"Some more text{markupOne}", System.Text.Encoding.UTF8, SourceHashAlgorithms.Default));
119await testLspServer.TestWorkspace.ChangeDocumentAsync(secondDocument.Id, SourceText.From("Two is now three!", System.Text.Encoding.UTF8, SourceHashAlgorithms.Default));
221var newSolution = testLspServer.TestWorkspace.CurrentSolution.AddDocument(newDocumentId, "NewDoc.cs", SourceText.From("New Doc", System.Text.Encoding.UTF8, SourceHashAlgorithms.Default), filePath: @"C:\NewDoc.cs");
354var changedFirstDocumentText = await changedFirstDocument.GetTextAsync(CancellationToken.None);
355var firstDocumentText = await firstDocument.GetTextAsync(CancellationToken.None);
516.AddDocument(filePath, SourceText.From("ProjectSystemText"), filePath: filePath)
573testLspServer.TestWorkspace.CurrentSolution.WithDocumentText(document.Id, SourceText.From("New Disk Contents")));
608var originalSourceText = await originalDocument.GetTextAsync(CancellationToken.None);
619var newSourceText = await newDocument.GetTextAsync(CancellationToken.None);
Microsoft.CodeAnalysis.LanguageServer.UnitTests (14)
Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers (90)
Microsoft.CodeAnalysis.PublicApiAnalyzers (83)
DeclarePublicApiAnalyzer.cs (8)
134bool TryGetAndValidateApiFiles(CompilationStartAnalysisContext context, bool isPublic, List<Diagnostic> errors, [NotNullWhen(true)] out ImmutableDictionary<AdditionalText, SourceText>? additionalFiles, [NotNullWhen(true)] out ApiData? shippedData, [NotNullWhen(true)] out ApiData? unshippedData)
156private static ApiData ReadApiData(SourceText sourceText, bool isShippedApi)
197private static bool TryGetApiData(CompilationStartAnalysisContext context, bool isPublic, List<Diagnostic> errors, [NotNullWhen(true)] out ImmutableDictionary<AdditionalText, SourceText>? additionalFiles, [NotNullWhen(true)] out ApiData? shippedData, [NotNullWhen(true)] out ApiData? unshippedData)
333out ImmutableDictionary<AdditionalText, SourceText> additionalFiles,
337additionalFiles = ImmutableDictionary<AdditionalText, SourceText>.Empty;
350var text = additionalText.GetText(context.CancellationToken);
363private static bool ValidateApiFiles(ImmutableDictionary<AdditionalText, SourceText> additionalFiles, ApiData shippedData, ApiData unshippedData, bool isPublic, List<Diagnostic> errors)
391private static void ValidateApiList(ImmutableDictionary<AdditionalText, SourceText> additionalFiles, Dictionary<string, ApiLine> publicApiMap, ImmutableArray<ApiLine> apiList, bool isPublic, List<Diagnostic> errors)
DeclarePublicApiAnalyzer.Impl.cs (7)
27private sealed record AdditionalFileInfo(SourceText SourceText, bool IsShippedApi)
29public string GetPath(ImmutableDictionary<AdditionalText, SourceText> additionalFiles)
45public SourceText SourceText => FileInfo.SourceText;
48public string GetPath(ImmutableDictionary<AdditionalText, SourceText> additionalFiles)
51public Location GetLocation(ImmutableDictionary<AdditionalText, SourceText> additionalFiles)
78private readonly ImmutableDictionary<AdditionalText, SourceText> _additionalFiles;
88internal Impl(Compilation compilation, ImmutableDictionary<AdditionalText, SourceText> additionalFiles, ApiData shippedData, ApiData unshippedData, bool isPublic, AnalyzerOptions analyzerOptions)
src\Compilers\Core\Portable\EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\SourceTextExtensions_SharedWithCodeStyle.cs (5)
16public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
32this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
44this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
82public static bool AreOnSameLine(this SourceText text, SyntaxToken token1, SyntaxToken token2)
87public static bool AreOnSameLine(this SourceText text, int pos1, int pos2)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Services\RefactoringHelpers\AbstractRefactoringHelpers.cs (6)
25public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
42private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span)
60SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray<TSyntaxNode> result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
179SourceText sourceText, SyntaxNode root, int location)
251SourceText sourceText, SyntaxToken tokenOnLocation, int location)
533SourceText sourceText,
Microsoft.CodeAnalysis.PublicApiAnalyzers.CodeFixes (39)
DeclarePublicApiFix.cs (21)
101var newSourceText = AddSymbolNamesToSourceText(sourceText: null, new[] { newSymbolName });
106var sourceText = await surfaceAreaDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
107var newSourceText = AddSymbolNamesToSourceText(sourceText, new[] { newSymbolName });
114private static Solution AddPublicApiFiles(Project project, SourceText unshippedText, bool isPublic)
117project = AddAdditionalDocument(project, isPublic ? DeclarePublicApiAnalyzer.PublicShippedFileName : DeclarePublicApiAnalyzer.InternalShippedFileName, SourceText.From(string.Empty));
122static Project AddAdditionalDocument(Project project, string name, SourceText text)
134private static SourceText AddSymbolNamesToSourceText(SourceText? sourceText, IEnumerable<string> newSymbolNames)
146return sourceText?.Replace(new TextSpan(0, sourceText.Length), newText) ?? SourceText.From(newText);
164private static SourceText RemoveSymbolNamesFromSourceText(SourceText sourceText, ImmutableHashSet<string> linesToRemove)
175SourceText newSourceText = sourceText.Replace(new TextSpan(0, sourceText.Length), string.Join(endOfLine, newLines) + sourceText.GetEndOfFileText(endOfLine));
179internal static List<string> GetLinesFromSourceText(SourceText? sourceText)
241var updatedPublicSurfaceAreaText = new List<KeyValuePair<DocumentId, SourceText>>();
242var addedPublicSurfaceAreaText = new List<KeyValuePair<ProjectId, SourceText>>();
250var sourceText = publicSurfaceAreaAdditionalDocument != null ?
310SourceText newSourceText = AddSymbolNamesToSourceText(sourceText, newSymbolNames);
315updatedPublicSurfaceAreaText.Add(new KeyValuePair<DocumentId, SourceText>(publicSurfaceAreaAdditionalDocument.Id, newSourceText));
319addedPublicSurfaceAreaText.Add(new KeyValuePair<ProjectId, SourceText>(project.Id, newSourceText));
325foreach (KeyValuePair<DocumentId, SourceText> pair in updatedPublicSurfaceAreaText)
332foreach (KeyValuePair<ProjectId, SourceText> pair in addedPublicSurfaceAreaText)
Microsoft.CodeAnalysis.Razor.Compiler (30)
Language\RazorSourceDocument.cs (15)
23public SourceText Text { get; }
66var sourceText = SourceText.From(stream, checksumAlgorithm: SourceHashAlgorithm.Sha256);
90var sourceText = SourceText.From(stream, encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256);
118var sourceText = SourceText.From(stream, encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256);
153var sourceText = SourceText.From(stream, checksumAlgorithm: SourceHashAlgorithm.Sha256);
218var sourceText = SourceText.From(content, encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256);
246var sourceText = SourceText.From(content, encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256);
256public static RazorSourceDocument Create(SourceText text, RazorSourceDocumentProperties properties)
271private RazorSourceDocument(SourceText sourceText, RazorSourceDocumentProperties properties)
Microsoft.CodeAnalysis.Razor.UnitTests (1)
Microsoft.CodeAnalysis.Razor.Workspaces (273)
Diagnostics\RazorTranslateDiagnosticsService.cs (13)
84var sourceText = codeDocument.Source.Text;
137SourceText sourceText,
149SourceText sourceText,
179private static bool AppliesToTagHelperTagName(LspDiagnostic diagnostic, SourceText sourceText, RazorSyntaxTree syntaxTree)
216private static bool ShouldFilterHtmlDiagnosticBasedOnErrorCode(LspDiagnostic diagnostic, SourceText sourceText, RazorSyntaxTree syntaxTree)
241static bool IsEscapedAtSign(LspDiagnostic diagnostic, SourceText sourceText)
269static bool IsAtCSharpTransitionInStyleBlock(LspDiagnostic diagnostic, SourceText sourceText, RazorSyntaxTree syntaxTree)
299static bool IsAnyFilteredTooFewElementsError(LspDiagnostic diagnostic, SourceText sourceText, RazorSyntaxTree syntaxTree)
329static bool IsHtmlWithBangAndMatchingTags(LspDiagnostic diagnostic, SourceText sourceText, RazorSyntaxTree syntaxTree)
353static bool IsAnyFilteredInvalidNestingError(LspDiagnostic diagnostic, SourceText sourceText, RazorSyntaxTree syntaxTree)
357static bool IsInvalidNestingWarningWithinComponent(LspDiagnostic diagnostic, SourceText sourceText, RazorSyntaxTree syntaxTree)
372static bool IsInvalidNestingFromBody(LspDiagnostic diagnostic, SourceText sourceText, RazorSyntaxTree syntaxTree)
398SourceText sourceText,
Extensions\LspExtensions_SourceText.cs (15)
12public static int GetPosition(this SourceText text, Position position)
15public static Position GetPosition(this SourceText text, int position)
18public static LspRange GetRange(this SourceText text, TextSpan span)
21public static LspRange GetRange(this SourceText text, SourceSpan span)
24public static LspRange GetRange(this SourceText text, int start, int end)
27public static LspRange GetZeroWidthRange(this SourceText text, int position)
30public static bool IsValidPosition(this SourceText text, Position position)
33public static bool TryGetAbsoluteIndex(this SourceText text, Position position, out int absoluteIndex)
36public static int GetRequiredAbsoluteIndex(this SourceText text, Position position)
39public static TextSpan GetTextSpan(this SourceText text, LspRange range)
42public static bool TryGetSourceLocation(this SourceText text, Position position, out SourceLocation location)
45public static TextChange GetTextChange(this SourceText text, TextEdit edit)
48public static RazorTextChange GetRazorTextChange(this SourceText text, TextEdit edit)
55public static TextEdit GetTextEdit(this SourceText text, TextChange change)
58public static TextEdit GetTextEdit(this SourceText text, RazorTextChange change)
Extensions\SourceTextExtensions.cs (40)
19public static TextChangeRange GetEncompassingTextChangeRange(this SourceText newText, SourceText oldText)
36public static LinePosition GetLinePosition(this SourceText text, int position)
39public static LinePositionSpan GetLinePositionSpan(this SourceText text, TextSpan span)
42public static LinePositionSpan GetLinePositionSpan(this SourceText text, SourceSpan span)
45public static LinePositionSpan GetLinePositionSpan(this SourceText text, int start, int end)
48public static int GetPosition(this SourceText text, LinePosition position)
51public static int GetPosition(this SourceText text, int line, int character)
54public static bool NonWhitespaceContentEquals(this SourceText text, ImmutableArray<TextChange> changes)
74var changedText = text.WithChanges(changes);
82this SourceText text,
83SourceText other,
125public static bool TryGetFirstNonWhitespaceOffset(this SourceText text, out int offset)
128public static bool TryGetFirstNonWhitespaceOffset(this SourceText text, TextSpan span, out int offset)
143public static bool TryGetFirstNonWhitespaceOffset(this SourceText text, TextSpan span, out int offset, out int newLineCount)
174public static bool TryGetLastNonWhitespaceOffset(this SourceText text, TextSpan span, out int offset)
192public static bool IsValidPosition(this SourceText text, LinePosition lspPosition)
195public static bool IsValidPosition(this SourceText text, (int line, int character) lspPosition)
198public static bool IsValidPosition(this SourceText text, int line, int character)
201public static bool TryGetAbsoluteIndex(this SourceText text, LinePosition position, out int absoluteIndex)
204public static bool TryGetAbsoluteIndex(this SourceText text, (int line, int character) position, out int absoluteIndex)
207public static bool TryGetAbsoluteIndex(this SourceText text, int line, int character, out int absoluteIndex)
247public static int GetRequiredAbsoluteIndex(this SourceText text, LinePosition position)
250public static int GetRequiredAbsoluteIndex(this SourceText text, (int line, int character) position)
253public static int GetRequiredAbsoluteIndex(this SourceText text, int line, int character)
258public static TextSpan GetTextSpan(this SourceText text, LinePosition start, LinePosition end)
261public static TextSpan GetTextSpan(this SourceText text, LinePositionSpan span)
264public static TextSpan GetTextSpan(this SourceText text, int startLine, int startCharacter, int endLine, int endCharacter)
277static int GetAbsoluteIndex(SourceText text, int line, int character, string name)
285public static bool TryGetSourceLocation(this SourceText text, LinePosition position, out SourceLocation location)
288public static bool TryGetSourceLocation(this SourceText text, int line, int character, out SourceLocation location)
303public static ImmutableArray<TextChange> MinimizeTextChanges(this SourceText text, ImmutableArray<TextChange> changes)
309public static ImmutableArray<TextChange> MinimizeTextChanges(this SourceText text, ImmutableArray<TextChange> changes, out SourceText originalTextWithChanges)
322/// Determines if the given <see cref="SourceText"/> has more LF line endings ('\n') than CRLF line endings ('\r\n').
324/// <param name="text">The <see cref="SourceText"/> to examine.</param>
326/// <c>true</c> if the <see cref="SourceText"/> is deemed to use LF line endings; otherwise, <c>false</c>.
328public static bool HasLFLineEndings(this SourceText text)
359public static ImmutableArray<TextChange> GetTextChangesArray(this SourceText newText, SourceText oldText)
Formatting\FormattingUtilities.cs (17)
24public static int CountNonWhitespaceChars(SourceText text, int start, int endExclusive)
54var text = line.Text.AssumeNotNull();
100public static void NaivelyUnindentSubstring(SourceText text, TextSpan extractionSpan, System.Text.StringBuilder builder)
140static int GetNormalizedIndentation(SourceText sourceText, TextSpan span)
216public static TextEdit[] FixHtmlTextEdits(SourceText htmlSourceText, TextEdit[] edits)
228internal static SumType<TextEdit, AnnotatedTextEdit>[] FixHtmlTextEdits(SourceText htmlSourceText, SumType<TextEdit, AnnotatedTextEdit>[] edits)
240public static void GetOriginalDocumentChangesFromLineInfo(FormattingContext context, SourceText originalText, ImmutableArray<LineInfo> formattedLineInfo, SourceText formattedText, ILogger logger, Func<int, bool>? shouldKeepInsertedNewlineAtPosition, ref PooledArrayBuilder<TextChange> formattingChanges, out int lastFormattedTextLine)
463var lineText = formattedLine.Text.AssumeNotNull();
484SourceText originalText,
485SourceText formattedText,
526private static bool NextLineIsOnlyAnOpenBrace(SourceText text, int lineNumber)
530private static bool CurrentLineIsOnlyAnOpenBrace(SourceText text, int lineNumber)
538private static bool CurrentLineEndsWithAnOpenBrace(SourceText text, int lineNumber)
564SourceText originalText,
565SourceText formattedText,
682SourceText text,
Formatting\Passes\CSharpOnTypeFormattingPass.cs (14)
52var csharpText = codeDocument.GetCSharpSourceText();
104var normalizedChanges = csharpText.MinimizeTextChanges(changes, out var originalTextWithChanges);
124var originalText = codeDocument.Source.Text;
130var formattedText = ApplyChangesAndTrackChange(originalText, filteredChanges, out _, out var spanAfterFormatting);
140var cleanedText = formattedText;
210private static SourceText ApplyChangesAndTrackChange(SourceText oldText, ImmutableArray<TextChange> changes, out TextSpan spanBeforeChange, out TextSpan spanAfterChange)
212var newText = oldText.WithChanges(changes);
247private static int LineDelta(SourceText text, IEnumerable<TextChange> changes, out int firstLine, out int lastLine)
275var text = context.SourceText;
323var text = context.SourceText;
457var text = context.SourceText;
540private static bool IsOnSingleLine(RazorSyntaxNode node, SourceText text)
554var text = context.SourceText;
Microsoft.CodeAnalysis.Razor.Workspaces.UnitTests (23)
Microsoft.CodeAnalysis.Rebuild (9)
Microsoft.CodeAnalysis.Rebuild.UnitTests (3)
Microsoft.CodeAnalysis.Remote.Razor (30)
Microsoft.CodeAnalysis.Remote.ServiceHub (7)
Microsoft.CodeAnalysis.Remote.Workspaces (1)
Microsoft.CodeAnalysis.ResxSourceGenerator (77)
src\Compilers\Core\Portable\EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\SourceTextExtensions_SharedWithCodeStyle.cs (5)
16public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
32this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
44this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
82public static bool AreOnSameLine(this SourceText text, SyntaxToken token1, SyntaxToken token2)
87public static bool AreOnSameLine(this SourceText text, int pos1, int pos2)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Services\RefactoringHelpers\AbstractRefactoringHelpers.cs (6)
25public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
42private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span)
60SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray<TSyntaxNode> result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
179SourceText sourceText, SyntaxNode root, int location)
251SourceText sourceText, SyntaxToken tokenOnLocation, int location)
533SourceText sourceText,
Microsoft.CodeAnalysis.ResxSourceGenerator.UnitTests (2)
Microsoft.CodeAnalysis.Scripting (12)
Hosting\CommandLine\CommandLineRunner.cs (5)
108SourceText? code = null;
200private int RunScript(ScriptOptions? options, SourceText? code, ErrorLogger? errorLogger, CancellationToken cancellationToken)
231var script = Script.CreateInitialScript<object>(_scriptCompiler, SourceText.From(initialScriptCodeOpt), options, globals.GetType(), assemblyLoaderOpt: null);
258var tree = _scriptCompiler.ParseSubmission(SourceText.From(input.ToString()), options.ParseOptions, cancellationToken);
283newScript = Script.CreateInitialScript<object>(_scriptCompiler, SourceText.From(code ?? string.Empty), options, globals.GetType(), assemblyLoaderOpt: null);
Script.cs (6)
39internal Script(ScriptCompiler compiler, ScriptBuilder builder, SourceText sourceText, ScriptOptions options, Type globalsTypeOpt, Script previousOpt)
54internal static Script<T> CreateInitialScript<T>(ScriptCompiler compiler, SourceText sourceText, ScriptOptions optionsOpt, Type globalsTypeOpt, InteractiveAssemblyLoader assemblyLoaderOpt)
79internal SourceText SourceText { get; }
117return new Script<TResult>(Compiler, Builder, SourceText.From(code ?? "", options.FileEncoding), options, GlobalsType, this);
130return new Script<TResult>(Compiler, Builder, SourceText.From(code, options.FileEncoding), options, GlobalsType, this);
344internal Script(ScriptCompiler compiler, ScriptBuilder builder, SourceText sourceText, ScriptOptions options, Type globalsTypeOpt, Script previousOpt)
Microsoft.CodeAnalysis.Scripting.TestUtilities (3)
Microsoft.CodeAnalysis.Test.Utilities (31)
Microsoft.CodeAnalysis.TestAnalyzerReference (6)
Microsoft.CodeAnalysis.UnitTests (656)
EmbeddedTextTests.cs (29)
39Assert.Throws<ArgumentException>("text", () => EmbeddedText.FromSource("path", SourceText.From("source")));
42Assert.Throws<ArgumentException>("text", () => EmbeddedText.FromSource("path", SourceText.From(new byte[0], 0, Encoding.UTF8, canBeEmbedded: false)));
43Assert.Throws<ArgumentException>("text", () => EmbeddedText.FromSource("path", SourceText.From(new MemoryStream(new byte[0]), Encoding.UTF8, canBeEmbedded: false)));
84AssertEx.Equal(SourceText.CalculateChecksum(new byte[0], 0, 0, SourceHashAlgorithm.Sha1), text.Checksum);
92var checksum = SourceText.CalculateChecksum(new byte[0], 0, 0, SourceHashAlgorithm.Sha1);
103var source = SourceText.From("", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), SourceHashAlgorithm.Sha1);
105var checksum = SourceText.CalculateChecksum(new byte[0], 0, 0, SourceHashAlgorithm.Sha1);
117var checksum = SourceText.CalculateChecksum(bytes, 0, bytes.Length, SourceHashAlgorithm.Sha1);
132var checksum = SourceText.CalculateChecksum(bytes, 0, bytes.Length, SourceHashAlgorithm.Sha1);
145var source = SourceText.From(SmallSource, Encoding.UTF8, SourceHashAlgorithm.Sha1);
159var checksum = SourceText.CalculateChecksum(bytes, 0, bytes.Length, SourceHashAlgorithms.Default);
174var checksum = SourceText.CalculateChecksum(bytes, 0, bytes.Length, SourceHashAlgorithms.Default);
187var source = SourceText.From(LargeSource, Encoding.Unicode, SourceHashAlgorithms.Default);
200var expected = SourceText.From(SmallSource, Encoding.UTF8, SourceHashAlgorithm.Sha1);
203var actual = SourceText.From(new StringReader(SmallSource), SmallSource.Length, Encoding.UTF8, SourceHashAlgorithm.Sha1);
215var expected = SourceText.From(LargeSource, Encoding.UTF8, SourceHashAlgorithm.Sha1);
218var actual = SourceText.From(new StringReader(LargeSource), LargeSource.Length, Encoding.UTF8, SourceHashAlgorithm.Sha1);
235var source = useStream ?
236SourceText.From(new MemoryStream(bytes), Encoding.ASCII, SourceHashAlgorithm.Sha1, canBeEmbedded: true) :
237SourceText.From(bytes, bytes.Length, Encoding.ASCII, SourceHashAlgorithm.Sha1, canBeEmbedded: true);
242AssertEx.Equal(SourceText.CalculateChecksum(bytes, 0, bytes.Length, SourceHashAlgorithm.Sha1), source.GetChecksum());
252var source = EncodedStringText.Create(new MemoryStream(new byte[] { 0xA9, 0x0D, 0x0A }), canBeEmbedded: true);
Text\LargeTextTests.cs (24)
18private static SourceText CreateSourceText(string s, Encoding encoding = null)
31private static SourceText CreateSourceText(Stream stream, Encoding encoding = null)
36private static SourceText CreateSourceText(TextReader reader, int length, Encoding encoding = null)
46var text = CreateSourceText(HelloWorld);
56var text = CreateSourceText(stream);
64var text = CreateSourceText(HelloWorld);
76var text = CreateSourceText(HelloWorld);
123var text = SourceText.From(stream);
155private static void CheckLine(SourceText text, int lineNumber, int start, int length, int newlineLength, string lineText)
199var data = CreateSourceText("goo" + newline + " bar");
212var data = CreateSourceText(text);
223var data = CreateSourceText("goo\r\nbar");
232var data = CreateSourceText("goo\n\rbar\u2028");
244var data = CreateSourceText("goo\r");
254var data = CreateSourceText("goo\r\n");
264var data = CreateSourceText("goo\r\rbar");
277var data = CreateSourceText("goo" + cr + crLf + cr + "bar");
292var data = CreateSourceText("goo" + cr + crLf + lf + "bar");
303var data = CreateSourceText("");
314var data = CreateSourceText(text);
324var data = CreateSourceText(text);
332var expectedSourceText = CreateSourceText(expected);
335var actualSourceText = CreateSourceText(actual, expected.Length);
Text\SourceTextTests.cs (120)
29SourceText[] texts = [SourceText.From(string.Empty), SourceText.From([], 0), SourceText.From(new MemoryStream())];
31foreach (var text1 in texts)
35foreach (var text2 in texts)
43private static void TestIsEmpty(SourceText text)
56Assert.Same(s_utf8, SourceText.From(HelloWorld, s_utf8).Encoding);
57Assert.Same(s_unicode, SourceText.From(HelloWorld, s_unicode).Encoding);
60Assert.Same(s_unicode, SourceText.From(bytes, bytes.Length, s_unicode).Encoding);
61Assert.Equal(utf8NoBOM, SourceText.From(bytes, bytes.Length, null).Encoding);
64Assert.Same(s_unicode, SourceText.From(stream, s_unicode).Encoding);
65Assert.Equal(utf8NoBOM, SourceText.From(stream, null).Encoding);
74Assert.Equal(utf8BOM, SourceText.From(bytes, bytes.Length, s_unicode).Encoding);
75Assert.Equal(utf8BOM, SourceText.From(bytes, bytes.Length, null).Encoding);
78Assert.Equal(utf8BOM, SourceText.From(stream, s_unicode).Encoding);
79Assert.Equal(utf8BOM, SourceText.From(stream, null).Encoding);
85Assert.Equal(SourceHashAlgorithm.Sha1, SourceText.From(HelloWorld).ChecksumAlgorithm);
88Assert.Equal(SourceHashAlgorithm.Sha1, SourceText.From(bytes, bytes.Length).ChecksumAlgorithm);
91Assert.Equal(SourceHashAlgorithm.Sha1, SourceText.From(stream).ChecksumAlgorithm);
113Assert.Equal(algorithm, SourceText.From(HelloWorld, checksumAlgorithm: algorithm).ChecksumAlgorithm);
116Assert.Equal(algorithm, SourceText.From(bytes, bytes.Length, checksumAlgorithm: algorithm).ChecksumAlgorithm);
119Assert.Equal(algorithm, SourceText.From(stream, checksumAlgorithm: algorithm).ChecksumAlgorithm);
135verifyChecksumAndContentHash(SourceText.From(HelloWorld, encodingNoBOM, checksumAlgorithm), checksumNoBOM, expectedContentHash);
136verifyChecksumAndContentHash(SourceText.From(HelloWorld, encodingBOM, checksumAlgorithm), checksumBOM, expectedContentHash);
145verifyChecksumAndContentHash(SourceText.From(bytesNoBOM, bytesNoBOM.Length, null, checksumAlgorithm), checksumNoBOM, expectedContentHash);
146verifyChecksumAndContentHash(SourceText.From(bytesNoBOM, bytesNoBOM.Length, encodingNoBOM, checksumAlgorithm), checksumNoBOM, expectedContentHash);
147verifyChecksumAndContentHash(SourceText.From(bytesNoBOM, bytesNoBOM.Length, encodingBOM, checksumAlgorithm), checksumNoBOM, expectedContentHash);
150verifyChecksumAndContentHash(SourceText.From(bytesBOM, bytesBOM.Length, null, checksumAlgorithm), checksumBOM, expectedContentHash);
151verifyChecksumAndContentHash(SourceText.From(bytesBOM, bytesBOM.Length, encodingNoBOM, checksumAlgorithm), checksumBOM, expectedContentHash);
152verifyChecksumAndContentHash(SourceText.From(bytesBOM, bytesBOM.Length, encodingBOM, checksumAlgorithm), checksumBOM, expectedContentHash);
155verifyChecksumAndContentHash(SourceText.From(streamNoBOM, null, checksumAlgorithm), checksumNoBOM, expectedContentHash);
156verifyChecksumAndContentHash(SourceText.From(streamNoBOM, encodingNoBOM, checksumAlgorithm), checksumNoBOM, expectedContentHash);
157verifyChecksumAndContentHash(SourceText.From(streamNoBOM, encodingBOM, checksumAlgorithm), checksumNoBOM, expectedContentHash);
160verifyChecksumAndContentHash(SourceText.From(streamBOM, null, checksumAlgorithm), checksumBOM, expectedContentHash);
161verifyChecksumAndContentHash(SourceText.From(streamBOM, encodingNoBOM, checksumAlgorithm), checksumBOM, expectedContentHash);
162verifyChecksumAndContentHash(SourceText.From(streamBOM, encodingBOM, checksumAlgorithm), checksumBOM, expectedContentHash);
180verifyChecksumAndContentHash(fromChanges(SourceText.From(HelloWorld, encodingNoBOM, checksumAlgorithm)), checksumNoBOM, expectedContentHash);
181verifyChecksumAndContentHash(fromChanges(SourceText.From(HelloWorld, encodingBOM, checksumAlgorithm)), checksumBOM, expectedContentHash);
186verifyChecksumAndContentHash(fromChanges(SourceText.From(streamNoBOM, encodingNoBOM, checksumAlgorithm)), checksumNoBOM, expectedContentHash);
187verifyChecksumAndContentHash(fromChanges(SourceText.From(streamNoBOM, encodingBOM, checksumAlgorithm)), checksumBOM, expectedContentHash);
190verifyChecksumAndContentHash(fromChanges(SourceText.From(streamBOM, encodingNoBOM, checksumAlgorithm)), checksumBOM, expectedContentHash);
191verifyChecksumAndContentHash(fromChanges(SourceText.From(streamBOM, encodingBOM, checksumAlgorithm)), checksumBOM, expectedContentHash);
195static void verifyChecksumAndContentHash(SourceText text, ImmutableArray<byte> expectedChecksum, ImmutableArray<byte> expectedContentHash)
203static SourceText fromChanges(SourceText text)
207var changed = text.WithChanges(change);
215private static SourceText FromLargeTextWriter(string source, Encoding encoding, SourceHashAlgorithm checksumAlgorithm)
227var f = SourceText.From(HelloWorld, s_utf8);
229Assert.True(f.ContentEquals(SourceText.From(HelloWorld, s_utf8)));
230Assert.False(f.ContentEquals(SourceText.From(HelloWorld + "o", s_utf8)));
231Assert.True(SourceText.From(HelloWorld, s_utf8).ContentEquals(SourceText.From(HelloWorld, s_utf8)));
233var e1 = EncodedStringText.Create(new MemoryStream(s_unicode.GetBytes(HelloWorld)), s_unicode);
234var e2 = EncodedStringText.Create(new MemoryStream(s_utf8.GetBytes(HelloWorld)), s_utf8);
270var allSourceTexts = new List<SourceText>();
283foreach (var sourceText1 in allSourceTexts)
285foreach (var sourceText2 in allSourceTexts)
335Assert.False(SourceText.IsBinary(""));
337Assert.False(SourceText.IsBinary("\0abc"));
338Assert.False(SourceText.IsBinary("a\0bc"));
339Assert.False(SourceText.IsBinary("abc\0"));
340Assert.False(SourceText.IsBinary("a\0b\0c"));
342Assert.True(SourceText.IsBinary("\0\0abc"));
343Assert.True(SourceText.IsBinary("a\0\0bc"));
344Assert.True(SourceText.IsBinary("abc\0\0"));
347Assert.False(SourceText.IsBinary(encoding.GetString(new byte[] { 0x81, 0x8D, 0x8F, 0x90, 0x9D })));
349Assert.False(SourceText.IsBinary("abc def baz aeiouy \u00E4\u00EB\u00EF\u00F6\u00FC\u00FB"));
350Assert.True(SourceText.IsBinary(encoding.GetString(Net461.Resources.System)));
357Assert.Throws<InvalidDataException>(() => SourceText.From(bytes, bytes.Length, throwIfBinaryDetected: true));
360Assert.Throws<InvalidDataException>(() => SourceText.From(stream, throwIfBinaryDetected: true));
367var expectedSourceText = SourceText.From(expected);
370var actualSourceText = SourceText.From(actual, expected.Length);
374Assert.Same(s_utf8, SourceText.From(actual, expected.Length, s_utf8).Encoding);
375Assert.Same(s_unicode, SourceText.From(actual, expected.Length, s_unicode).Encoding);
376Assert.Null(SourceText.From(actual, expected.Length, null).Encoding);
382var expected = new string('l', SourceText.LargeObjectHeapLimitInChars);
383var expectedSourceText = SourceText.From(expected);
386var actualSourceText = SourceText.From(actual, expected.Length);
393Assert.Same(s_utf8, SourceText.From(actual, expected.Length, s_utf8).Encoding);
394Assert.Same(s_unicode, SourceText.From(actual, expected.Length, s_unicode).Encoding);
395Assert.Null(SourceText.From(actual, expected.Length, null).Encoding);
406Encoding actualEncoding = SourceText.TryReadByteOrderMark(data, validLength, out actualPreambleLength);
439var sourceText = SourceText.From("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
458var sourceText = SourceText.From(Text);
470SourceText.From("ABC").Write(TextWriter.Null, TextSpan.FromBounds(4, 4)));
479SourceText.From("ABC").Write(TextWriter.Null, TextSpan.FromBounds(2, 4)));
493var text1 = SourceText.From(content, utf8);
494var text2 = SourceText.From(content, unicode);
525var textWithBOM = SourceText.From(bytesWithBOM, bytesWithBOM.Length, Encoding.UTF8);
526var textNoBOM = SourceText.From(bytesNoBOM, bytesNoBOM.Length, Encoding.UTF8);
540var text1 = SourceText.From("content1");
541var text2 = SourceText.From("content2");
557var text = SourceText.From("content");
579var text1 = SourceText.From(stream1, Encoding.UTF8);
582var text2 = SourceText.From(content, Encoding.UTF8);
599var text1 = SourceText.From(content, Encoding.UTF8);
600var text2 = SourceText.From(content, Encoding.Unicode);
614var text1 = SourceText.From(content, Encoding.UTF8);
615var text2 = SourceText.From(content, Encoding.Unicode);
Text\StringTextDecodingTests.cs (21)
19private static SourceText CreateMemoryStreamBasedEncodedText(string text, Encoding writeEncoding, Encoding readEncodingOpt, SourceHashAlgorithm algorithm = SourceHashAlgorithm.Sha1)
26private static SourceText CreateMemoryStreamBasedEncodedText(byte[] bytes, Encoding readEncodingOpt, SourceHashAlgorithm algorithm = SourceHashAlgorithm.Sha1)
39private static SourceText CreateMemoryStreamBasedEncodedText(byte[] bytes,
59var data = CreateMemoryStreamBasedEncodedText(TestResources.General.ShiftJisSource, () => sjis);
69var data = CreateMemoryStreamBasedEncodedText(TestResources.General.ShiftJisSource, sjis);
78var data = CreateMemoryStreamBasedEncodedText("The quick brown fox jumps over the lazy dog", Encoding.ASCII, readEncodingOpt: null);
88var data = CreateMemoryStreamBasedEncodedText("The quick brown fox jumps over the lazy dog", Encoding.Unicode, readEncodingOpt: null);
97var data = CreateMemoryStreamBasedEncodedText("The quick brown fox jumps over the lazy dog", Encoding.BigEndianUnicode, readEncodingOpt: null);
106var data = CreateMemoryStreamBasedEncodedText("", Encoding.ASCII, readEncodingOpt: null);
116var data = CreateMemoryStreamBasedEncodedText("", Encoding.Unicode, readEncodingOpt: null);
125var data = CreateMemoryStreamBasedEncodedText("", Encoding.BigEndianUnicode, readEncodingOpt: null);
134var data = CreateMemoryStreamBasedEncodedText("", Encoding.UTF8, readEncodingOpt: null, algorithm: SourceHashAlgorithm.Sha256);
170var sourceText = EncodedStringText.Create(stream);
195var sourceText = EncodedStringText.Create(stream);
225var sourceText = EncodedStringText.Create(stream);
244var text = CreateMemoryStreamBasedEncodedText("goo", writeEncoding, readEncoding);
274var text = CreateMemoryStreamBasedEncodedText("goo", writeEncoding, readEncoding);
310var encodedText = EncodedStringText.Create(fs);
324var encodedText = EncodedStringText.Create(fs);
340var sourceText = EncodedStringText.Create(ms);
355var sourceText = EncodedStringText.Create(stream);
Text\StringTextTest.cs (37)
46var data = SourceText.From("goo", Encoding.UTF8);
54var data = SourceText.From("goo");
61var data = SourceText.From(string.Empty);
69Assert.Throws<ArgumentNullException>(() => SourceText.From((string)null, Encoding.UTF8));
75Assert.Throws<ArgumentNullException>(() => SourceText.From((Stream)null, Encoding.UTF8));
76Assert.Throws<ArgumentException>(() => SourceText.From(new TestStream(canRead: false, canSeek: true), Encoding.UTF8));
77Assert.Throws<NotImplementedException>(() => SourceText.From(new TestStream(canRead: true, canSeek: false), Encoding.UTF8));
83var data = SourceText.From(string.Empty, Encoding.UTF8);
108private void CheckLine(SourceText text, int lineNumber, int start, int length, int newlineLength, string lineText)
152var data = SourceText.From("goo" + newLine + " bar");
165var data = SourceText.From(text);
176var data = SourceText.From("goo\r\nbar");
185var data = SourceText.From("goo\n\rbar\u2028");
196var data = SourceText.From("");
207var data = SourceText.From(text);
217var data = SourceText.From(text);
224var data = SourceText.From("The quick brown fox jumps over the lazy dog", Encoding.UTF8);
234var source = SourceText.From(new MemoryStream(bytes), Encoding.ASCII);
249var source = SourceText.From(new MemoryStream(bytes), Encoding.ASCII);
261var source = SourceText.From(new MemoryStream(bytes));
276var source = SourceText.From(stream, Encoding.ASCII);
Text\TextChangeTests.cs (259)
32var text = SourceText.From("Hello World");
33var subText = text.GetSubText(6);
40var text = SourceText.From("Hello World");
41var subText = text.GetSubText(new TextSpan(0, 5));
48var text = SourceText.From("Hello World");
49var subText = text.GetSubText(new TextSpan(6, 5));
56var text = SourceText.From("Hello World");
57var subText = text.GetSubText(new TextSpan(4, 3));
64var text = SourceText.From("Hello World");
65var subText = text.GetSubText(new TextSpan(0, 5));
66var subSubText = subText.GetSubText(new TextSpan(0, 0));
76var text = SourceText.From("Hello World");
77var subText = text.GetSubText(6);
78var subSubText = subText.GetSubText(subText.Length);
87var text = SourceText.From("Hello World");
88var newText = text.Replace(6, 0, "Beautiful ");
95var text = SourceText.From("Hello World");
96var newText = text.Replace(6, 0, "Beautiful ");
109var text = SourceText.From("Hello World");
110var newText = text.WithChanges(
120var text = SourceText.From("Hello World");
133var text = SourceText.From("Hello World");
140var newText = text.WithChanges(changes);
147var text = SourceText.From("Hello World");
155var newText = text.WithChanges(changes);
162var text = SourceText.From("Hello World");
164var newText = text.WithChanges(
174var text = SourceText.From("Hello World");
176var newText = text.WithChanges(
186var text = SourceText.From("Hello World");
193var newText = text.WithChanges(changes);
200var text = SourceText.From("Hello World");
202var newText = text.WithChanges(
212var text = SourceText.From("Hello World", Encoding.Unicode, SourceHashAlgorithms.Default);
213var newText = text.WithChanges(
217var subText = newText.GetSubText(new TextSpan(3, 4));
227var text = SourceText.From("Hello World");
228var newText = text.WithChanges(
237var text = SourceText.From("Hello World");
238var newText = text.WithChanges(
254var text = SourceText.From(new string('.', 2048), Encoding.Unicode, SourceHashAlgorithms.Default); // start bigger than GetText() copy buffer
262var newText = text.WithChanges(changes);
293var changedText = SourceText.From(originalText).WithChanges(changes);
294Assert.Equal(SourceText.From(changedText.ToString()).Lines, changedText.Lines, new TextLineEqualityComparer());
371var text = SourceText.From(str);
391var text = SourceText.From(str);
410var text = SourceText.From("abcdefghijklmnopqrstuvwxyz");
415var subtext = text.GetSubText(new TextSpan(5, 10));
424var text = SourceText.From("abcdefghijklmnopqrstuvwxyz");
426var newText = text.Replace(new TextSpan(0, 20), "");
435var text = SourceText.From("abcdefghijklmnopqrstuvwxyz");
437var newText = text.Replace(new TextSpan(10, 6), "");
446var text = SourceText.From("abcdefghijklmnopqrstuvwxyz");
449var newText = text.Replace(new TextSpan(10, 1), "");
462var text = SourceText.From("abcdefghijklmnopqrstuvwxyz");
465var textWithSegments = text.Replace(new TextSpan(10, 0), "*");
479var text = SourceText.From("abcdefghijklmnopqrstuvwxyz");
482var textWithSegments = text.Replace(new TextSpan(10, 0), "*");
486var textWithFewerSegments = textWithSegments.Replace(new TextSpan(9, 3), "");
499var text = SourceText.From("abcdefghijklmnopqrstuvwxyz");
502var textWithSegments = text.Replace(new TextSpan(0, text.Length), "");
513var t = SourceText.From(a);
543var t = SourceText.From(a);
569SourceText secondEdit;
585private void CreateEdits(out WeakReference weakFirstEdit, out SourceText secondEdit)
587var text = SourceText.From("This is the old text");
588var firstEdit = text.Replace(11, 3, "new");
598var largeText = CreateLargeText(chunk1);
611private SourceText CreateLargeText(params char[][] chunks)
616private ImmutableArray<char[]> GetChunks(SourceText text)
633var text = SourceText.From("small preamble");
635var largeText = CreateLargeText(chunk1);
658var original = SourceText.From("Hello World");
659var change1 = original.WithChanges(new TextChange(new TextSpan(5, 6), string.Empty)); // prepare a ChangedText instance
660var change2 = change1.WithChanges(); // this should not cause exception
669var original = SourceText.From("Hello World");
670var change1 = original.WithChanges(new TextChange(new TextSpan(5, 6), string.Empty)); // prepare a ChangedText instance
671var change2 = change1.WithChanges(new TextChange(new TextSpan(2, 0), string.Empty)); // this should not cause exception
679var original = SourceText.From("Hello World");
680var change1 = original.WithChanges(new TextChange(new TextSpan(6, 0), "Cruel "));
681var change2 = change1.WithChanges(new TextChange(new TextSpan(7, 3), "oo"));
694var original = SourceText.From("01234");
695var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa"));
696var change2 = change1.WithChanges(new TextChange(new TextSpan(2, 0), "bb"));
708var original = SourceText.From("012");
709var change1 = original.WithChanges(new TextChange(new TextSpan(1, 1), "aaa"));
710var change2 = change1.WithChanges(new TextChange(new TextSpan(3, 0), "bb"));
722var original = SourceText.From("01234");
723var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa"));
724var change2 = change1.WithChanges(new TextChange(new TextSpan(2, 1), "bb"));
735var original = SourceText.From("Hello World");
736var change1 = original.WithChanges(new TextChange(new TextSpan(6, 0), "Cruel "));
737var change2 = change1.WithChanges(new TextChange(new TextSpan(2, 14), "ar"));
749var original = SourceText.From("Hello World");
750var change1 = original.WithChanges(new TextChange(new TextSpan(6, 0), "Cruel "));
751var change2 = change1.WithChanges(new TextChange(new TextSpan(4, 6), " Bel"));
763var original = SourceText.From("Hello World");
764var change1 = original.WithChanges(new TextChange(new TextSpan(6, 0), "Cruel "));
765var change2 = change1.WithChanges(new TextChange(new TextSpan(7, 6), "wazy V"));
777var original = SourceText.From("01234");
778var change1 = original.WithChanges(new TextChange(new TextSpan(1, 0), "aa"));
779var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 0), "bb"));
790var original = SourceText.From("01234");
791var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa"));
792var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 0), "bb"));
803var original = SourceText.From("01234");
804var change1 = original.WithChanges(new TextChange(new TextSpan(1, 0), "aa"));
805var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 1), "bb"));
816var original = SourceText.From("01234");
817var change1 = original.WithChanges(new TextChange(new TextSpan(1, 0), "aa"));
818var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 2), "bb"));
829var original = SourceText.From("01234");
830var change1 = original.WithChanges(new TextChange(new TextSpan(1, 0), "aa"));
831var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 3), "bb"));
843var original = SourceText.From("01234");
844var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa"));
845var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 1), "bb"));
857var original = SourceText.From("01234");
858var change1 = original.WithChanges(new TextChange(new TextSpan(1, 3), "aa"));
859var change2 = change1.WithChanges(new TextChange(new TextSpan(1, 3), "bb"));
869var original = SourceText.From("Hell");
870var change1 = original.WithChanges(new TextChange(new TextSpan(4, 0), "o "));
871var change2 = change1.WithChanges(new TextChange(new TextSpan(6, 0), "World"));
883var original = SourceText.From("Hell ");
884var change1 = original.WithChanges(new TextChange(new TextSpan(4, 0), "o"));
885var change2 = change1.WithChanges(new TextChange(new TextSpan(6, 0), "World"));
899var original = SourceText.From("Hell Word");
900var change1 = original.WithChanges(new TextChange(new TextSpan(8, 0), "l"));
901var change2 = change1.WithChanges(new TextChange(new TextSpan(4, 0), "o"));
915var original = SourceText.From("Hell");
916var change1 = original.WithChanges(new TextChange(new TextSpan(4, 0), " World"));
918var change2 = change1.WithChanges(new TextChange(new TextSpan(4, 0), "o"));
930var original = SourceText.From("Hell");
932var final = GetChangesWithoutMiddle(
988var originalText = SourceText.From(string.Join("", Enumerable.Range(0, random.Next(10))));
1012var change1 = originalText.WithChanges(oldChangesBuilder);
1031var change2 = change1.WithChanges(newChangesBuilder);
1069var originalText = SourceText.From("01234");
1070var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 2), "a"));
1071var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 2), "bb"));
1083var original = SourceText.From("01234");
1084var change1 = original.WithChanges(new TextChange(new TextSpan(0, 0), "aa"), new TextChange(new TextSpan(1, 1), "aa"));
1085var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 1), "b"), new TextChange(new TextSpan(2, 2), ""));
1097var originalText = SourceText.From("01234");
1098var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 0), "a"));
1099var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 2), ""), new TextChange(new TextSpan(2, 0), "bb"));
1111var originalText = SourceText.From("01234");
1112var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), "aa"), new TextChange(new TextSpan(3, 1), "aa"));
1113var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 0), "bbb"));
1124var originalText = SourceText.From("012345");
1125var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 3), "a"), new TextChange(new TextSpan(5, 0), "aaa"));
1126var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 2), ""), new TextChange(new TextSpan(3, 1), "bb"));
1138var originalText = SourceText.From("01234567");
1139var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), "aaaaa"), new TextChange(new TextSpan(3, 1), "aaaa"), new TextChange(new TextSpan(6, 1), "aaaaa"));
1140var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 0), "b"), new TextChange(new TextSpan(2, 0), "b"), new TextChange(new TextSpan(3, 4), "bbbbb"), new TextChange(new TextSpan(9, 5), "bbbbb"), new TextChange(new TextSpan(15, 3), ""));
1152var originalText = SourceText.From("01234");
1153var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), "a"));
1154var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 1), "b"), new TextChange(new TextSpan(2, 2), "b"));
1166var originalText = SourceText.From("01234");
1167var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), "aa"));
1168var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 0), "b"), new TextChange(new TextSpan(1, 2), "b"));
1180var originalText = SourceText.From("012345");
1181var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 2), "a"), new TextChange(new TextSpan(3, 2), "a"));
1182var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 3), "bbb"));
1194var originalText = SourceText.From("0123456");
1195var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 4), ""), new TextChange(new TextSpan(5, 1), ""));
1196var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 1), ""), new TextChange(new TextSpan(1, 0), ""));
1208var originalText = SourceText.From("012345");
1209var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 2), ""), new TextChange(new TextSpan(3, 1), ""), new TextChange(new TextSpan(4, 0), ""), new TextChange(new TextSpan(4, 0), ""), new TextChange(new TextSpan(4, 0), ""));
1210var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 1), ""), new TextChange(new TextSpan(1, 1), ""), new TextChange(new TextSpan(2, 0), ""));
1222var originalText = SourceText.From("01234");
1223var change1 = originalText.WithChanges(new TextChange(new TextSpan(0, 1), ""), new TextChange(new TextSpan(2, 1), ""));
1224var change2 = change1.WithChanges(new TextChange(new TextSpan(0, 0), ""), new TextChange(new TextSpan(1, 1), ""));
1246var text = SourceText.From(content);
1256var changedText = text.WithChanges(edits1);
1267var changedText2 = changedText.WithChanges(edits2);
1278private SourceText GetChangesWithoutMiddle(
1279SourceText original,
1280Func<SourceText, SourceText> fnChange1,
1281Func<SourceText, SourceText> fnChange2)
1284SourceText change2;
1297SourceText original,
1298Func<SourceText, SourceText> fnChange1,
1299Func<SourceText, SourceText> fnChange2,
1301out SourceText change2)
1303var c1 = fnChange1(original);
Text\TextLineNewLineTests.cs (100)
18/// Exhaustive tests for <see cref="TextLine"/> properties across all <see cref="SourceText"/>
140/// Creates a <see cref="SourceText"/> with the given <paramref name="content"/> using the
143private static SourceText CreateText(string content, TextKind kind) => kind switch
145TextKind.String => SourceText.From(content),
152private static SourceText CreateLargeText(string content)
155return SourceText.From(content);
164private static SourceText CreateSubText(string content)
168var full = SourceText.From(prefix + content + suffix);
176private static SourceText CreateCompositeFromContent(string content)
179return SourceText.From(content);
185private static SourceText CreateLargeTextWithChunks(params string[] chunks)
193private static SourceText CreateCompositeText(params string[] segments)
195var builder = ArrayBuilder<SourceText>.GetInstance();
197builder.Add(SourceText.From(segment));
199var reference = SourceText.From(string.Concat(segments));
200var result = CompositeText.ToSourceText(builder, reference, adjustSegments: false);
210SourceText text, int lineNumber,
228private static void AssertLinesMatch(SourceText reference, SourceText actual)
261var text = CreateText("abc" + newLine + "def", kind);
270var text = CreateText("abc" + newLine, kind);
279var text = CreateText(newLine + "abc", kind);
288var text = CreateText(newLine, kind);
297var text = CreateText(newLine + newLine, kind);
307var text = CreateText(newLine + newLine + newLine, kind);
317var text = CreateText("a" + newLine1 + "b" + newLine2 + "c", kind);
327var text = CreateText("", kind);
335var text = CreateText("hello world", kind);
343var text = CreateText("abc\rdef\nghi", kind);
353var text = CreateText("abc\n\rdef", kind);
363var text = CreateText("a\nb\rc\r\nd\u0085e\u2028f\u2029g", kind);
377var text = CreateText("a\r\n\r\nb", kind);
387var text = CreateText("a\r\r\nb", kind);
397var text = CreateText("a\r\n\rb", kind);
414var text1 = CreateText(content, kind1);
415var text2 = CreateText(content, kind2);
436SourceText.From("abc" + newLine + "def"),
450SourceText.From("abc" + newLine + "def"),
457var text = CreateLargeTextWithChunks("abc\r", "\ndef");
458AssertLinesMatch(SourceText.From("abc\r\ndef"), text);
467AssertLinesMatch(SourceText.From("\r\n"), CreateLargeTextWithChunks("\r", "\n"));
474SourceText.From("abc\rdef"),
482SourceText.From("ab\r\ncd\r\nef"),
490SourceText.From("a\rb\r\nc"),
508AssertLinesMatch(SourceText.From(content), CreateLargeTextWithChunks(chunks));
516var fullText = SourceText.From("abc\r\ndef");
518AssertLinesMatch(SourceText.From("abc\r"), subText);
526var fullText = SourceText.From("abc\r\ndef");
528SourceText.From("\ndef"),
535var fullText = SourceText.From("abc\r\ndef");
537SourceText.From("\r"),
544var fullText = SourceText.From("abc\r\ndef");
546SourceText.From("\n"),
553var fullText = SourceText.From("\r\nabc");
554AssertLinesMatch(SourceText.From("\r"), new SubText(fullText, new TextSpan(0, 1)));
555AssertLinesMatch(SourceText.From("\nabc"), new SubText(fullText, new TextSpan(1, 4)));
561var fullText = SourceText.From("abc\r\n");
562AssertLinesMatch(SourceText.From("abc\r"), new SubText(fullText, new TextSpan(0, 4)));
563AssertLinesMatch(SourceText.From("\n"), new SubText(fullText, new TextSpan(4, 1)));
569var fullText = SourceText.From("a\r\nb\r\nc");
570AssertLinesMatch(SourceText.From("a\r"), new SubText(fullText, new TextSpan(0, 2)));
571AssertLinesMatch(SourceText.From("\nb\r\nc"), new SubText(fullText, new TextSpan(2, 5)));
588var fullText = SourceText.From(content);
593var reference = SourceText.From(content[start..end]);
605var composite = CreateCompositeText("abc\r", "\ndef");
606AssertLinesMatch(SourceText.From("abc\r\ndef"), composite);
613SourceText.From("ab\r\ncd\r\nef"),
621SourceText.From("abc\rdef"),
628var reference = SourceText.From(content);
631var composite = CreateCompositeText(content[..split], content[split..]);
639var reference = SourceText.From(content);
644var composite = CreateCompositeText(
660var text = SourceText.From("abc\ndef");
672var text = SourceText.From("abc\ndef");
686var textLF = SourceText.From("abc\ndef");
687var textCRLF = SourceText.From("abc\r\ndef");
700var text1 = SourceText.From("abc");
701var text2 = SourceText.From("abc");
713var text = SourceText.From("abc\ndef");
724var text = CreateText("abc\ndef\r\nghi", kind);
Text\TextUtilitiesTests.cs (8)
35Assert.Equal(0, TextUtilities.GetLengthOfLineBreak(SourceText.From("aoeu"), 0));
36Assert.Equal(0, TextUtilities.GetLengthOfLineBreak(SourceText.From("aoeu"), 2));
45Assert.Equal(1, TextUtilities.GetLengthOfLineBreak(SourceText.From("\naoeu"), 0));
46Assert.Equal(1, TextUtilities.GetLengthOfLineBreak(SourceText.From("a\nbaou"), 1));
47Assert.Equal(0, TextUtilities.GetLengthOfLineBreak(SourceText.From("a\n"), 0));
56Assert.Equal(2, TextUtilities.GetLengthOfLineBreak(SourceText.From("\r\n"), 0));
57Assert.Equal(1, TextUtilities.GetLengthOfLineBreak(SourceText.From("\n\r"), 0));
66Assert.Equal(1, TextUtilities.GetLengthOfLineBreak(SourceText.From("\r"), 0));
Microsoft.CodeAnalysis.VisualBasic (43)
Syntax\SyntaxNodeFactories.vb (6)
50Return ParseSyntaxTree(SourceText.From(text, encoding, SourceHashAlgorithm.Sha1), options, path, cancellationToken)
57text As SourceText,
79Return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, cancellationToken)
86text As SourceText,
287Friend Shared Function MakeSourceText(text As String, offset As Integer) As SourceText
288Return SourceText.From(text, Encoding.UTF8).GetSubText(offset)
Microsoft.CodeAnalysis.Workspaces (382)
Shared\Extensions\SourceTextExtensions.cs (12)
36public static void GetLineAndOffset(this SourceText text, int position, out int lineNumber, out int offset)
44public static int GetOffset(this SourceText text, int position)
51this SourceText text,
62public static TextChangeRange GetEncompassingTextChangeRange(this SourceText newText, SourceText oldText)
79public static int IndexOf(this SourceText text, string value, int startIndex, bool caseSensitive)
110public static int LastIndexOf(this SourceText text, string value, int startIndex, bool caseSensitive)
146public static bool ContentEquals(this SourceText text, int position, string value)
164public static int IndexOfNonWhiteSpace(this SourceText text, int start, int length)
177public static void WriteTo(this SourceText sourceText, ObjectWriter writer, CancellationToken cancellationToken)
195private static void WriteChunksTo(SourceText sourceText, ObjectWriter writer, int length, CancellationToken cancellationToken)
226public static SourceText ReadFrom(ITextFactoryService textService, ObjectReader reader, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken)
src\Compilers\Core\Portable\EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\SourceTextExtensions_SharedWithCodeStyle.cs (5)
16public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
32this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
44this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
82public static bool AreOnSameLine(this SourceText text, SyntaxToken token1, SyntaxToken token2)
87public static bool AreOnSameLine(this SourceText text, int pos1, int pos2)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Services\RefactoringHelpers\AbstractRefactoringHelpers.cs (6)
25public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
42private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span)
60SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray<TSyntaxNode> result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
179SourceText sourceText, SyntaxNode root, int location)
251SourceText sourceText, SyntaxToken tokenOnLocation, int location)
533SourceText sourceText,
Workspace\Host\TextFactory\TextFactoryService.cs (4)
25public SourceText CreateText(Stream stream, Encoding? defaultEncoding, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken)
31public SourceText CreateText(TextReader reader, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm, CancellationToken cancellationToken)
36? SourceText.From(textReaderWithLength, textReaderWithLength.Length, encoding, checksumAlgorithm)
37: SourceText.From(reader.ReadToEnd(), encoding, checksumAlgorithm);
Workspace\Solution\DocumentState.cs (12)
106var text = await this.GetTextAsync(cancellationToken).ConfigureAwait(false);
166var text = textAndVersion.Text;
239var newText = newTextAndVersion.Text;
242var oldText = oldTree.GetText(cancellationToken);
250private static TreeAndVersion MakeNewTreeAndVersion(SyntaxTree oldTree, SourceText oldText, VersionStamp oldVersion, SyntaxTree newTree, SourceText newText, VersionStamp newVersion)
259private static bool TopLevelChanged(SyntaxTree oldTree, SourceText oldText, SyntaxTree newTree, SourceText newText)
444public new DocumentState UpdateText(SourceText newText, PreservationMode mode)
507else if (TryGetText(out var priorText))
672SourceText newText,
674SourceText? oldText = null)
Workspace\Solution\FileTextLoader.cs (7)
68GetType(), _ => new StrongBox<bool>(new Func<Stream, Workspace, SourceText>(CreateText).Method.DeclaringType != typeof(FileTextLoader))).Value;
72/// Creates <see cref="SourceText"/> from <see cref="Stream"/>.
76protected virtual SourceText CreateText(Stream stream, Workspace? workspace)
80/// Creates <see cref="SourceText"/> from <see cref="Stream"/>.
83private protected virtual SourceText CreateText(Stream stream, LoadTextOptions options, CancellationToken cancellationToken)
183var text = t.self.CreateText(readStream, t.options, t.cancellationToken);
207var text = t.self.CreateText(stream, t.options, t.cancellationToken);
Workspace\Solution\Solution.cs (18)
986var sourceText = SourceText.From(text, encoding: null, checksumAlgorithm: project.ChecksumAlgorithm);
995public Solution AddDocument(DocumentId documentId, string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null, bool isGenerated = false)
1028var sourceText = SourceText.From(string.Empty, encoding: null, project.ChecksumAlgorithm);
1034private Solution AddDocumentImpl(ProjectState project, DocumentId documentId, string name, SourceText text, IReadOnlyList<string>? folders, string? filePath, bool isGenerated)
1089=> this.AddAdditionalDocument(documentId, name, SourceText.From(text), folders, filePath);
1095public Solution AddAdditionalDocument(DocumentId documentId, string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null)
1126public Solution AddAnalyzerConfigDocument(DocumentId documentId, string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null)
1150private DocumentInfo CreateDocumentInfo(DocumentId documentId, string name, SourceText text, IEnumerable<string>? folders, string? filePath)
1288public Solution WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
1291internal Solution WithDocumentTexts(ImmutableArray<(DocumentId documentId, SourceText text)> texts, PreservationMode mode = PreservationMode.PreserveValue)
1311public Solution WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
1332public Solution WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
1645public Solution WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode = PreservationMode.PreserveValue)
1671SourceGeneratedDocumentIdentity documentIdentity, DateTime generationDateTime, SourceText text)
1684internal Solution WithFrozenSourceGeneratedDocuments(ImmutableArray<(SourceGeneratedDocumentIdentity documentIdentity, DateTime generationDateTime, SourceText text)> documents)
1685=> WithCompilationState(CompilationState.WithFrozenSourceGeneratedDocuments(documents.SelectAsArray(d => (d.documentIdentity, d.generationDateTime, (SourceText?)d.text, (SyntaxNode?)null))));
Workspace\Solution\SolutionCompilationState.cs (18)
806internal SolutionCompilationState WithDocumentTexts(ImmutableArray<(DocumentId documentId, SourceText text)> texts, PreservationMode mode)
810return UpdateDocumentsInMultipleProjects<DocumentState, SourceText, PreservationMode>(
817(ImmutableArray<(DocumentId, SourceText)>,
818ImmutableArray<(SourceGeneratedDocumentIdentity, DateTime, SourceText?, SyntaxNode?)>) GetOrdinaryAndSourceGeneratedDocuments()
823using var _1 = ArrayBuilder<(DocumentId, SourceText)>.GetInstance(capacity: texts.Length, out var ordinaryDocuments);
824using var _2 = ArrayBuilder<(SourceGeneratedDocumentIdentity, DateTime, SourceText?, SyntaxNode?)>.GetInstance(out var sourceGeneratedDocuments);
841private static bool SourceTextIsUnchanged(DocumentState oldDocument, SourceText text)
842=> oldDocument.TryGetText(out var oldText) && text == oldText;
850ImmutableArray<(SourceGeneratedDocumentIdentity documentIdentity, DateTime generationDateTime, SourceText? sourceText, SyntaxNode? syntaxNode)> sourceGeneratedDocuments,
962/// <inheritdoc cref="SolutionState.WithAdditionalDocumentText(DocumentId, SourceText, PreservationMode)"/>
964DocumentId documentId, SourceText text, PreservationMode mode)
970/// <inheritdoc cref="SolutionState.WithAnalyzerConfigDocumentText(DocumentId, SourceText, PreservationMode)"/>
972DocumentId documentId, SourceText text, PreservationMode mode)
1023ImmutableArray<(SourceGeneratedDocumentIdentity, DateTime, SourceText?, SyntaxNode?)>) GetOrdinaryAndSourceGeneratedDocuments()
1029using var _2 = ArrayBuilder<(SourceGeneratedDocumentIdentity, DateTime, SourceText?, SyntaxNode?)>.GetInstance(out var sourceGeneratedDocuments);
1405ImmutableArray<(SourceGeneratedDocumentIdentity documentIdentity, DateTime generationDateTime, SourceText? sourceText, SyntaxNode? syntaxNode)> documents)
1873public SolutionCompilationState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode)
1875using var _ = ArrayBuilder<(DocumentId, SourceText)>.GetInstance(out var changedDocuments);
Workspace\Workspace.cs (18)
1138protected internal void OnDocumentTextChanged(DocumentId documentId, SourceText newText, PreservationMode mode)
1141private protected void OnDocumentTextChanged(DocumentId documentId, SourceText newText, PreservationMode mode, bool requireDocumentPresent)
1156protected internal void OnAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText, PreservationMode mode)
1171protected internal void OnAnalyzerConfigDocumentTextChanged(DocumentId documentId, SourceText newText, PreservationMode mode)
1936var text = document.GetTextSynchronously(CancellationToken.None);
1945var text = document.GetTextSynchronously(CancellationToken.None);
1954var text = document.GetTextSynchronously(CancellationToken.None);
1971var currentText = newDoc.GetTextSynchronously(CancellationToken.None); // needs wait
1981var currentText = newDoc.GetTextSynchronously(CancellationToken.None); // needs wait
1998if (!oldDoc.TryGetText(out var oldText))
2003var currentText = newDoc.GetTextSynchronously(CancellationToken.None); // needs wait
2006else if (!newDoc.TryGetText(out var newText))
2202protected virtual void ApplyDocumentAdded(DocumentInfo info, SourceText text)
2224protected virtual void ApplyDocumentTextChanged(DocumentId id, SourceText text)
2246protected virtual void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text)
2268protected virtual void ApplyAdditionalDocumentTextChanged(DocumentId id, SourceText text)
2279protected virtual void ApplyAnalyzerConfigDocumentAdded(DocumentInfo info, SourceText text)
2301protected virtual void ApplyAnalyzerConfigDocumentTextChanged(DocumentId id, SourceText text)
Workspace\Workspace_Editor.cs (11)
396var newText = textContainer.CurrentText;
397if (oldDocument.TryGetText(out var oldText) &&
486private static TextAndVersion GetProperTextAndVersion(SourceText oldText, SourceText newText, VersionStamp version, string? filePath)
495private void SignupForTextChanges(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext, Action<Workspace, DocumentId, SourceText, PreservationMode> onChangedHandler)
556Func<Solution, DocumentId, SourceText, PreservationMode, Solution> withDocumentText,
558Action<Workspace, DocumentId, SourceText, PreservationMode> onDocumentTextChanged)
588var oldText = oldDocument.GetTextSynchronously(CancellationToken.None);
591var newText = data.textContainer.CurrentText;
850private SourceText GetOpenDocumentText(Solution solution, DocumentId documentId)
855Contract.ThrowIfFalse(doc.TryGetText(out var text));
Microsoft.CodeAnalysis.Workspaces.MSBuild (9)
MSBuild\MSBuildWorkspace.cs (9)
394protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText text)
412protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText text)
430private static Encoding? DetermineEncoding(SourceText text, TextDocument document)
445var onDiskText = EncodedStringText.Create(stream);
458protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text)
496private void SaveDocumentText(DocumentId id, string fullPath, SourceText newText, Encoding encoding)
726internal void OnDocumentTextChangedInternal(DocumentId documentId, SourceText newText)
731internal void OnAdditionalDocumentTextChangedInternal(DocumentId documentId, SourceText newText)
736internal void OnAnalyzerConfigDocumentTextChangedInternal(DocumentId documentId, SourceText newText)
Microsoft.CodeAnalysis.Workspaces.MSBuild.UnitTests (46)
Microsoft.CodeAnalysis.Workspaces.Test.Utilities (24)
Formatting\FormattingTestBase.cs (6)
49var document = project.AddDocument("Document", SourceText.From(code));
83private static async Task AssertFormatAsync(SolutionServices services, string expected, SyntaxNode root, ImmutableArray<TextSpan> spans, SyntaxFormattingOptions options, SourceText sourceText)
90var resultText = sourceText.WithChanges(result);
99private static bool TryAdjustSpans(SourceText inputText, IList<TextChange> changes, SourceText outputText, ImmutableArray<TextSpan> inputSpans, out ImmutableArray<TextSpan> outputSpans)
127protected static void AssertResult(string expected, SourceText sourceText, IList<TextChange> result)
Microsoft.CodeAnalysis.Workspaces.UnitTests (353)
FindReferencesTests.cs (5)
40return solution.AddProject(pi).AddDocument(did, $"{projectName}.{suffix}", SourceText.From(code));
56return solution.AddProject(pi).AddDocument(did, $"{projectName}.{suffix}", SourceText.From(code));
66.AddDocument(did, "goo.cs", SourceText.From(sourceText));
82solution = solution.AddDocument(did, $"goo{docCounter++}.cs", SourceText.From(sourceText));
130.AddDocument(did, "goo.cs", SourceText.From(text));
Formatter\FormatterTests.cs (7)
42=> document.WithText(SourceText.From($"Formatted with options: {lineFormattingOptions.ToString().Replace("\r", "\\r").Replace("\n", "\\n")}"));
52var document = workspace.AddDocument(project.Id, "File.dummy", SourceText.From("dummy"));
58var formattedText = await formattedDocument.GetTextAsync();
71var document = workspace.AddDocument(project.Id, "File.dummy", SourceText.From("dummy"));
96var formattedText = await formattedDocument.GetTextAsync();
116var csDocument = workspace.AddDocument(csProject.Id, "File.cs", SourceText.From("class C { }"));
117var vbDocument = workspace.AddDocument(vbProject.Id, "File.vb", SourceText.From("Class C : End Class"));
SolutionTests\SolutionTests.cs (165)
58.AddDocument(DocumentId.CreateNewId(projectId), "goo.cs", SourceText.From("public class Goo { }", Encoding.UTF8, SourceHashAlgorithms.Default), filePath: Path.Combine(s_projectDir, "goo.cs"))
59.AddAdditionalDocument(DocumentId.CreateNewId(projectId), "add.txt", SourceText.From("text", Encoding.UTF8, SourceHashAlgorithms.Default))
60.AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From(editorConfig ?? "#empty", Encoding.UTF8, SourceHashAlgorithms.Default), filePath: Path.Combine(s_projectDir, "editorcfg"))));
80.AddDocument(DocumentId.CreateNewId(projectId1), "goo.cs", SourceText.From(docContents, Encoding.UTF8, SourceHashAlgorithms.Default), filePath: "goo.cs")
81.AddAdditionalDocument(DocumentId.CreateNewId(projectId1), "add.txt", SourceText.From("text", Encoding.UTF8, SourceHashAlgorithms.Default), filePath: "add.txt")
82.AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId1), "editorcfg", SourceText.From("config", Encoding.UTF8, SourceHashAlgorithms.Default), filePath: "/a/b")
84.AddDocument(DocumentId.CreateNewId(projectId2), "goo.cs", SourceText.From(docContents, Encoding.UTF8, SourceHashAlgorithms.Default), filePath: "goo.cs")
85.AddAdditionalDocument(DocumentId.CreateNewId(projectId2), "add.txt", SourceText.From("text", Encoding.UTF8, SourceHashAlgorithms.Default), filePath: "add.txt")
86.AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId2), "editorcfg", SourceText.From("config", Encoding.UTF8, SourceHashAlgorithms.Default), filePath: "/a/b")));
346.AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From("config"));
362var text = SourceText.From("new text", encoding: null, SourceHashAlgorithm.Sha1);
367Assert.True(newDocument1.TryGetText(out var actualText));
373Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
386var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default);
389Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText));
397Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
410var text = SourceText.From("new text");
413Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText));
449var text1 = await document1.GetTextAsync();
450var text2 = await document2.GetTextAsync();
463var text = SourceText.From("new text", encoding: null, SourceHashAlgorithm.Sha1);
508private static Solution UpdateSolution(PreservationMode mode, TextUpdateType updateType, Solution solution, DocumentId documentId1, SourceText text, TextAndVersion textAndVersion)
537var text1 = await document1.GetTextAsync();
538var text2 = await document2.GetTextAsync();
551var text = SourceText.From("new text", encoding: null, SourceHashAlgorithm.Sha1);
616var text1 = await document1.GetTextAsync();
617var text2 = await document2.GetTextAsync();
634var text = SourceText.From("new text without pp directives", encoding: null, SourceHashAlgorithm.Sha1);
702var text1 = await document1.GetTextAsync();
703var text2 = await document2.GetTextAsync();
717var text = SourceText.From("#if true", encoding: null, SourceHashAlgorithm.Sha1);
779var text1 = await document1.GetTextAsync();
780var text2 = await document2.GetTextAsync();
793var text = SourceText.From("new text", encoding: null, SourceHashAlgorithm.Sha1);
855.AddDocument(DocumentId.CreateNewId(projectId1), "goo.cs", SourceText.From(docContents, Encoding.UTF8, SourceHashAlgorithms.Default), filePath: "goo.cs")
857.AddDocument(DocumentId.CreateNewId(projectId2), "goo.cs", SourceText.From(docContents, Encoding.UTF8, SourceHashAlgorithms.Default), filePath: "goo.cs")));
867var text1 = await document1.GetTextAsync();
868var text2 = await document2.GetTextAsync();
880var text = SourceText.From(" ", encoding: null, SourceHashAlgorithm.Sha1);
932var text = SourceText.From("new text");
935Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText));
941Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
954var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default);
957Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText));
965Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
978var text = SourceText.From("new text");
981Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText));
987Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
1000var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default);
1003Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText));
1011Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity));
1105.AddDocument(d1, "d1.cs", SourceText.From("class D1;", Encoding.UTF8, SourceHashAlgorithms.Default), filePath: Path.Combine(s_projectDir, "d1.cs"))
1106.AddDocument(d2, "d2.cs", SourceText.From("class D2;", Encoding.UTF8, SourceHashAlgorithms.Default), filePath: Path.Combine(s_projectDir, "d2.cs"))
1107.AddAdditionalDocument(a1, "a1.txt", SourceText.From("text1", Encoding.UTF8, SourceHashAlgorithms.Default))
1108.AddAdditionalDocument(a2, "a2.txt", SourceText.From("text2", Encoding.UTF8, SourceHashAlgorithms.Default))
1109.AddAnalyzerConfigDocument(c1, "c1", SourceText.From("#empty1", Encoding.UTF8, SourceHashAlgorithms.Default), filePath: Path.Combine(s_projectDir, "editorcfg"))
1110.AddAnalyzerConfigDocument(c2, "c2", SourceText.From("#empty2", Encoding.UTF8, SourceHashAlgorithms.Default), filePath: Path.Combine(s_projectDir, "editorcfg"));
1120loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class NewD1;", Encoding.UTF32, SourceHashAlgorithm.Sha256), VersionStamp.Create(), filePath: Path.Combine(s_projectDir, "newD1.cs"))),
1129loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class NewD3;", Encoding.UTF8, SourceHashAlgorithms.Default), VersionStamp.Create(), filePath: Path.Combine(s_projectDir, "newD3.cs"))),
1139loader: TextLoader.From(TextAndVersion.Create(SourceText.From("new text1", Encoding.UTF32, SourceHashAlgorithm.Sha256), VersionStamp.Create(), filePath: Path.Combine(s_projectDir, "newD1.cs"))),
1148loader: TextLoader.From(TextAndVersion.Create(SourceText.From("new text3", Encoding.UTF8, SourceHashAlgorithms.Default), VersionStamp.Create(), filePath: Path.Combine(s_projectDir, "newD3.cs"))),
1158loader: TextLoader.From(TextAndVersion.Create(SourceText.From("#new empty1", Encoding.UTF32, SourceHashAlgorithm.Sha256), VersionStamp.Create(), filePath: Path.Combine(s_projectDir, "newD1.cs"))),
1167loader: TextLoader.From(TextAndVersion.Create(SourceText.From("#new empty3", Encoding.UTF8, SourceHashAlgorithms.Default), VersionStamp.Create(), filePath: Path.Combine(s_projectDir, "newD3.cs"))),
1246var newText1 = newDocument1.GetTextSynchronously(CancellationToken.None);
1255var newText3 = newDocument3.GetTextSynchronously(CancellationToken.None);
1267var newAddText1 = newAddDocument1.GetTextSynchronously(CancellationToken.None);
1276var newAddText3 = newAddDocument3.GetTextSynchronously(CancellationToken.None);
1288var newConfigText1 = newConfigDocument1.GetTextSynchronously(CancellationToken.None);
1297var newConfigText3 = newConfigDocument3.GetTextSynchronously(CancellationToken.None);
1321var text = SourceText.From("class D;", Encoding.UTF8, SourceHashAlgorithms.Default);
1678var textC = SourceText.From("class C {}", encoding: null, checksumAlgorithm: SourceHashAlgorithm.Sha1);
2373var solution4 = solution3.AddAnalyzerConfigDocument(editorConfigId, ".editorconfig", SourceText.From(editorConfigContent), filePath: Path.Combine(s_projectDir, "subfolder", ".editorconfig"));
2459var sourceText = document.GetTextSynchronously(default);
2484var sourceText = SourceText.From("text", checksumAlgorithm: SourceHashAlgorithms.Default);
2498Assert.Throws<ArgumentNullException>("text", () => solution.AddDocument(documentId, "name", text: (SourceText)null!));
2514var sourceText = await document.GetTextAsync();
2542.AddAdditionalDocument(DocumentId.CreateNewId(additionalFileProjectId), "Linked.cs", SourceText.From("class C {}"), filePath: LinkedFileName)
2544.AddDocument(DocumentId.CreateNewId(sourceFileProjectId), "Linked.cs", SourceText.From("class C {}"), filePath: LinkedFileName);
2572.AddAnalyzerConfigDocument(DocumentId.CreateNewId(analyzerConfigProjectId), "Linked.cs", SourceText.From("class C {}"), filePath: LinkedFileName)
2574.AddDocument(DocumentId.CreateNewId(sourceFileProjectId), "Linked.cs", SourceText.From("class C {}"), filePath: LinkedFileName);
2601.AddAdditionalDocument(DocumentId.CreateNewId(additionalFileProjectId), "Linked.cs", SourceText.From("class C {}"), filePath: LinkedFileName)
2603.AddDocument(DocumentId.CreateNewId(sourceFileProjectId), "Linked.cs", SourceText.From("class C {}"), filePath: LinkedFileName);
2622.AddAnalyzerConfigDocument(DocumentId.CreateNewId(analyzerConfigProjectId), "Linked.cs", SourceText.From("class C {}"), filePath: LinkedFileName)
2624.AddDocument(DocumentId.CreateNewId(sourceFileProjectId), "Linked.cs", SourceText.From("class C {}"), filePath: LinkedFileName);
2674var root = CSharp.SyntaxFactory.ParseSyntaxTree(SourceText.From("class C {}", encoding: Encoding.ASCII, SourceHashAlgorithm.Sha1)).GetRoot();
2679var sourceText = document2.GetTextSynchronously(default);
2711var sourceText = document2.GetTextSynchronously(default);
3357.AddDocument(documentId, "DocumentName", SourceText.From("class Class{}"));
3397var text2 = tree2.GetText();
3510var observedText2 = sol.GetDocument(did).GetTextAsync().Result;
3528var docText = doc.GetTextAsync().Result;
3550var docText = doc.GetTextAsync().Result;
3575var docText = doc.GetTextAsync().Result;
3721private static ObjectReference<SourceText> GetObservedText(Solution solution, DocumentId documentId, string expectedText = null)
3723var observedText = solution.GetDocument(documentId).GetTextAsync().Result;
3730return new ObjectReference<SourceText>(observedText);
3752private static ObjectReference<SourceText> GetObservedTextAsync(Solution solution, DocumentId documentId, string expectedText = null)
3754var observedText = solution.GetDocument(documentId).GetTextAsync().Result;
3761return new ObjectReference<SourceText>(observedText);
3973.AddDocument(did, "test", SourceText.From(language == LanguageNames.CSharp ? "class C {}" : "Class C : End Class", Encoding.UTF8, SourceHashAlgorithm.Sha256), filePath: "old path");
4116var text = await doc.GetTextAsync().ConfigureAwait(false);
4186var solution2 = solution.WithDocumentText(did3, SourceText.From(text4));
4199var doc = ws.AddDocument(proj.Id, "a.cs", SourceText.From("public class c { }", Encoding.UTF32));
4264workspace.AddDocument(project1.Id, "Broken.cs", SourceText.From("class "));
4286project = project.AddDocument("Extra.cs", SourceText.From("class Extra { }")).Project;
4288var documentToFreeze = project.AddDocument("DocumentToFreeze.cs", SourceText.From(""));
4311project = project.AddDocument("Extra.cs", SourceText.From("class Extra { }")).Project;
4313var documentToFreeze = project.AddDocument("DocumentToFreeze.cs", SourceText.From(""));
4339project = project.AddDocument("Extra.cs", SourceText.From("class Extra { }")).Project;
4341var documentToFreezeOriginal = project.AddDocument("DocumentToFreeze.cs", SourceText.From("class DocumentToFreeze { void M() { } }"));
4345var solution = project.Solution.WithDocumentText(documentToFreezeOriginal.Id, SourceText.From("class DocumentToFreeze { void M() { /*no top level change*/ } }"));
4384project = project.AddDocument("Extra.cs", SourceText.From("class Extra { }")).Project;
4386var documentToFreezeOriginal = project.AddDocument("DocumentToFreeze.cs", SourceText.From("class DocumentToFreeze { void M() { } }"));
4390var solution = project.Solution.WithDocumentText(documentToFreezeOriginal.Id, SourceText.From("class DocumentToFreeze { void M() { } public void NewMethod() { } }"));
4452var document = workspace.AddDocument(project2.Id, "Test.cs", SourceText.From(""));
4556document = document.WithText(SourceText.From("// Source File with Changes"));
4582.WithDocumentText(documentId1, SourceText.From("// Document 1 Changed"))
4583.WithDocumentText(documentId2, SourceText.From("// Document 2 Changed"))
4584.WithDocumentText(documentId3, SourceText.From("// Document 3 Changed"));
4769var text = SourceText.From("// empty", encoding: null, SourceHashAlgorithms.Default);
4772var sourceText = strongTree.GetText();
4884loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default)))));
4917loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default)))));
4958loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default)))));
4970TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA6789.severity = error"), VersionStamp.Default)),
5006loader: TextLoader.From(TextAndVersion.Create(SourceText.From("is_global = true\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default)))));
5052loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ngenerated_code = true"), VersionStamp.Default)))));
5634var text = SourceText.From("public class C { }");
5655var newDocText = await newDoc.GetTextAsync();
5656var sameText = await newDoc.GetTextAsync();
5660var treeText = newDocTree.GetText();
5682var sourceTextToRelease = ObjectReference.CreateFromFactory(static () => SourceText.From(Guid.NewGuid().ToString()));
5730.AddDocument(documentId, "test.cs", SourceText.From("public class C { }"), filePath: sourcePath)
5731.AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), ".editorconfig", SourceText.From($"[{pattern}]\nindent_style = tab"), filePath: configPath);
5791project = project.AddDocument("Extra.cs", SourceText.From("class Extra { }")).Project;
5808project = project.AddDocument("Extra.cs", SourceText.From("class Extra { }")).Project;
5829project1 = project2.Solution.GetProject(project1.Id).AddDocument("Doc1", SourceText.From("class Doc1 { }")).Project;
5830project2 = project1.Solution.GetProject(project2.Id).AddDocument("Doc2", SourceText.From("class Doc2 { }")).Project;
5857project1 = project2.Solution.GetProject(project1.Id).AddDocument("Doc1", SourceText.From("class Doc1 { }")).Project;
5858project2 = project1.Solution.GetProject(project2.Id).AddDocument("Doc2", SourceText.From("class Doc2 { }")).Project;
5887project1 = project2.Solution.GetProject(project1.Id).AddDocument("Doc1", SourceText.From("class Doc1 { }")).Project;
5888project2 = project1.Solution.GetProject(project2.Id).AddDocument("Doc2", SourceText.From("class Doc2 { }")).Project;
5919project1 = project1.AddDocument("Doc1", SourceText.From("class Doc1 { }")).Project;
5928var forkedProject1 = frozenSolution.WithDocumentText(project1.Documents.Single().Id, SourceText.From("class Doc2 { }")).GetProject(project1.Id);
5947project1 = project1.AddDocument("Doc1", SourceText.From("class Doc1 { }")).Project;
5967var forkedProject1 = frozenSolution.WithDocumentText(project1.Documents.Single().Id, SourceText.From("class Doc2 { }")).GetProject(project1.Id);
5996project = project.AddDocument("Extra.ts", SourceText.From("class Extra { }")).Project;
6019.AddDocument($"Document", SourceText.From("class C { }"), filePath: @"c:\test\Document.cs").Project;
6029.AddDocument($"Document", SourceText.From("class C { }"), filePath: @"c:\test\Document.cs").Project;
6040old => old.WithDocumentText(documentId1, SourceText.From(lastContents)),
SolutionTests\SolutionWithSourceGeneratorTests.cs (44)
205project = project.AdditionalDocuments.First().WithAdditionalDocumentText(SourceText.From("Changed text!")).Project;
229project = project.AddDocument("Source.cs", SourceText.From("")).Project;
262project = project.Solution.WithDocumentText(documentId, SourceText.From("// Changed Source File")).Projects.Single();
305project = project.Solution.WithAdditionalDocumentText(additionalDocumentId, SourceText.From("Hello, everyone!")).Projects.Single();
310project = project.Solution.WithAdditionalDocumentText(additionalDocumentId, SourceText.From("Good evening, everyone!")).Projects.Single();
374SourceText.From("Hello, world!!!!")).Projects.Single();
488project = project.Documents.Single().WithText(SourceText.From("// Change")).Project;
564var existingText = await project.Documents.Single().GetTextAsync();
565var newText = existingText.WithChanges(new TextChange(new TextSpan(existingText.Length, length: 0), " With Change"));
594var differentOpenTextContainer = SourceText.From("// Open Text").Container;
618var differentOpenTextContainer = SourceText.From("// StaticContent", Encoding.UTF8).Container;
633.AddAdditionalDocument("Test.txt", SourceText.From(""));
638var differentOpenTextContainer = SourceText.From("// Open Text").Container;
669var differentOpenTextContainer = SourceText.From("// Open Text").Container;
696var differentOpenTextContainer = SourceText.From("// Open Text").Container;
733documentToFreeze = documentToFreeze.WithText(SourceText.From("// Changed Source File"));
763document = document.WithText(SourceText.From("// Something else"));
792document = document.WithText(SourceText.From("// Something else"));
826document = document.WithText(SourceText.From("// Something else"));
887identity, DateTime.Now, SourceText.From("// Frozen Document"));
914[(sourceGeneratedDocument1.Identity, DateTime.Now, SourceText.From("// Frozen 1")), (sourceGeneratedDocument2.Identity, DateTime.Now, SourceText.From("// Frozen 2"))]);
934sourceGeneratedDocumentIdentity, sourceGeneratedDocument.GenerationDateTime, SourceText.From("// Hello, World"));
998[(ordinaryDocument.Id, SourceText.From("// Regular modified")),
999(sourceGeneratedDocument.Id, SourceText.From("// Source gen modified"))]);
1003var sourceText = await updatedDocument.GetTextAsync();
1031var sourceText = await sourceGeneratedDocument.GetTextAsync();
1065var sourceText = await sourceGeneratedDocument.GetTextAsync();
1100var sourceText = await sourceGeneratedDocument.GetTextAsync();
1153sourceGeneratedDocument = sourceGeneratedDocument.WithText(SourceText.From("// Something else"));
1154var sourceText = await sourceGeneratedDocument.GetTextAsync();
1181sourceGeneratedDocument = sourceGeneratedDocument.WithText(SourceText.From("// Something else"));
1182var sourceText = await sourceGeneratedDocument.GetTextAsync();
1185sourceGeneratedDocument = sourceGeneratedDocument.WithText(SourceText.From("// Thrice is nice"));
1217var solution = sourceGeneratedDocument1.WithText(SourceText.From("// Change doc 1")).Project.Solution;
1219var sourceText = await sourceGeneratedDocument1!.GetTextAsync();
1224solution = sourceGeneratedDocument2!.WithText(SourceText.From("// Change doc 2")).Project.Solution;
1266newDocument = newDocument.WithText(SourceText.From("// Changed frozen document"));
1275identity, DateTime.Now, SourceText.From("// Frozen Document"));
1312identity, DateTime.Now, SourceText.From("// Frozen Document"));
1343identity, DateTime.Now, SourceText.From("// Frozen Document"));
1378identity, DateTime.Now, SourceText.From("// Frozen Document"));
1485var contents = await helloWorldDoc.GetTextAsync();
1522var contents = await helloWorldDoc.GetTextAsync();
SyntaxPathTests.cs (14)
90var text = SourceText.From(string.Empty);
95var newText = text.WithChanges(new TextChange(new TextSpan(0, 0), "class C {}"));
104var text = SourceText.From("class C {}");
109var newText = text.WithChanges(new TextChange(new TextSpan(0, text.Length), ""));
411var text = SourceText.From("using X; class C {}");
416var newText = WithReplaceFirst(text, "using X;", "");
423internal static SourceText WithReplaceFirst(SourceText text, string oldText, string newText)
430return SourceText.From(newFullText);
443var oldFullText = syntaxTree.GetText();
444var newFullText = oldFullText.WithChanges(new TextChange(new TextSpan(offset, length), newText));
WorkspaceTests\AdhocWorkspaceTests.cs (22)
73var doc = ws.AddDocument(project.Id, name, SourceText.From(source));
155loader: TextLoader.From(TextAndVersion.Create(SourceText.From(""), VersionStamp.Create())));
213var text = SourceText.From("public class C { }");
227Assert.False(doc.TryGetText(out var currentText));
247var text = SourceText.From("public class C { }");
261Assert.False(doc.TryGetText(out var currentText));
281var text = SourceText.From("public class C { }");
300Assert.False(doc.TryGetText(out var currentText));
320var text = SourceText.From("public class C { }");
334Assert.False(doc.TryGetText(out var currentText));
366var actualText = await newDoc.GetTextAsync();
378var docid1 = ws.AddDocument(projid, "A.cs", SourceText.From("public class A { }")).Id;
379var docid2 = ws.AddDocument(projid, "B.cs", SourceText.From("public class B { }")).Id;
415var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
446var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
482var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
514var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
545var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
WorkspaceTests\WorkspaceTests.cs (7)
25var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
27var changedDoc = originalDoc.WithText(SourceText.From("new"));
38var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
54var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
73var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
90var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
147public Document AddDocument(ProjectId projectId, string name, SourceText text)
Microsoft.DotNet.CodeAnalysis (2)
Microsoft.Extensions.Logging.Generators (1)
Microsoft.Extensions.Options.SourceGeneration (1)
Microsoft.Extensions.Validation.GeneratorTests (3)
Microsoft.Extensions.Validation.ValidationsGenerator (1)
Microsoft.Gen.BuildMetadata (1)
Microsoft.Gen.BuildMetadata.Unit.Tests (5)
Microsoft.Gen.ComplianceReports.Unit.Tests (5)
Microsoft.Gen.ContextualOptions.Unit.Tests (5)
Microsoft.Gen.Logging (1)
Microsoft.Gen.Logging.Unit.Tests (5)
Microsoft.Gen.MetadataExtractor.Unit.Tests (5)
Microsoft.Gen.Metrics (2)
Microsoft.Gen.Metrics.Unit.Tests (5)
Microsoft.Gen.MetricsReports.Unit.Tests (5)
Microsoft.Maui.Controls.SourceGen (4)
Microsoft.ML.AutoML.SourceGenerator (3)
Microsoft.NET.Sdk.Razor.SourceGenerators.UnitTests (21)
RazorSourceGeneratorTests.cs (13)
398var updatedText = new TestAdditionalText("Pages/Counter.razor", SourceText.From("<h2>Counter</h2>", Encoding.UTF8));
530project = project.AddDocument("Person.cs", SourceText.From("""
646project = project.Documents.First().WithText(SourceText.From(@"
745var updatedText = new TestAdditionalText("Pages/Counter.razor", SourceText.From(@"
914var updatedText = new TestAdditionalText("Pages/Counter.razor", SourceText.From(@"
1165.AddSyntaxTrees(CSharpSyntaxTree.ParseText(Microsoft.CodeAnalysis.Text.SourceText.From(@"
1611var updatedText = new TestAdditionalText("Views/Shared/_Layout.cshtml", SourceText.From("<h2>Updated Layout</h2>", Encoding.UTF8));
1834project = project.Documents.First().WithText(SourceText.From(@"
1986project = project.AddDocument("HeaderTagHelper.cs", SourceText.From(@"
2147var updatedText = new TestAdditionalText("Pages/Index.cshtml", SourceText.From("<h1>Fixed header</h1>", Encoding.UTF8));
2331var updatedText = new TestAdditionalText("Pages/Index.cshtml", SourceText.From(@"
2826.AddAdditionalDocument("Counter.razor", SourceText.From("<h1>Counter</h1>", Encoding.UTF8))
3174var updatedIndex = new TestAdditionalText("Pages/Index.razor", SourceText.From("<RenamedComponent />", Encoding.UTF8));
Microsoft.VisualStudio.LanguageServices (110)
ProjectSystem\VisualStudioWorkspaceImpl.AddAdditionalDocumentUndoUnit.cs (1)
18SourceText text)
ProjectSystem\VisualStudioWorkspaceImpl.AddAnalyzerConfigDocumentUndoUnit.cs (1)
17SourceText text)
ProjectSystem\VisualStudioWorkspaceImpl.cs (13)
736protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text)
739protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text)
742protected override void ApplyAnalyzerConfigDocumentAdded(DocumentInfo info, SourceText text)
748private void AddDocumentCore(DocumentInfo info, SourceText initialText, TextDocumentKind documentKind)
854SourceText? initialText = null,
873SourceText? initialText = null,
890SourceText text)
955SourceText? initialText,
996var text = document.GetTextSynchronously(CancellationToken.None);
1157protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText)
1160protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText)
1163protected override void ApplyAnalyzerConfigDocumentTextChanged(DocumentId documentId, SourceText newText)
1166private void ApplyTextDocumentChange(DocumentId documentId, SourceText newText)
Venus\ContainedDocument.cs (13)
208public void UpdateText(SourceText newText)
210var originalText = SubjectBuffer.CurrentSnapshot.AsText();
233private ITextSnapshot ApplyChanges(SourceText originalText, IEnumerable<TextChange> changes)
261private IEnumerable<TextChange> FilterTextChanges(SourceText originalText, List<TextSpan> editorVisibleSpansInOriginal, IEnumerable<TextChange> changes)
348private IEnumerable<TextChange> GetSubTextChanges(SourceText originalText, TextChange changeInOriginalText, TextSpan visibleSpanInOriginalText)
365SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText, List<TextChange> changes)
399SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText)
503SourceText originalText, TextSpan visibleSpanInOriginalText,
824public BaseIndentationFormattingRule GetBaseIndentationRule(SyntaxNode root, SourceText text, List<TextSpan> spans, int spanIndex)
872private static void GetVisibleAndTextSpan(SourceText text, List<TextSpan> spans, int spanIndex, out TextSpan visibleSpan, out TextSpan visibleTextSpan)
884private int GetBaseIndentation(SyntaxNode root, SourceText text, TextSpan span)
911private static TextSpan GetVisibleTextSpan(SourceText text, TextSpan visibleSpan, bool uptoFirstAndLastLine = false)
949private int GetAdditionalIndentation(SyntaxNode root, SourceText text, TextSpan span, int hostIndentationSize)
Workspace\VisualStudioDocumentNavigationService.cs (11)
60var text = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
77var text = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
128var text = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
137static VsTextSpan GetVsTextSpanFromPosition(SourceText text, int position, int virtualSpace)
159Func<SourceText, VsTextSpan> getVsTextSpan,
160Func<SourceText, TextSpan, VsTextSpan> getVsTextSpanForMapping,
183Func<SourceText, VsTextSpan> getVsTextSpan,
184Func<SourceText, TextSpan, VsTextSpan> getVsTextSpanForMapping,
243Func<SourceText, VsTextSpan> getVsTextSpan)
264var text = await document.GetValueTextAsync(cancellationToken).ConfigureAwait(false);
349private static VsTextSpan GetVsTextSpan(SourceText text, TextSpan textSpan, bool allowInvalidSpan)
Microsoft.VisualStudio.LanguageServices.CSharp (43)
CodeModel\CSharpCodeModelService.NodeLocator.cs (31)
33protected override VirtualTreePoint? GetStartPoint(SourceText text, LineFormattingOptions options, SyntaxNode node, EnvDTE.vsCMPart part)
84protected override VirtualTreePoint? GetEndPoint(SourceText text, LineFormattingOptions options, SyntaxNode node, EnvDTE.vsCMPart part)
135private static VirtualTreePoint GetBodyStartPoint(SourceText text, SyntaxToken openBrace)
147private static VirtualTreePoint GetBodyStartPoint(SourceText text, LineFormattingOptions options, SyntaxToken openBrace, SyntaxToken closeBrace, int memberStartColumn)
211private static VirtualTreePoint GetBodyEndPoint(SourceText text, SyntaxToken closeBrace)
221private static VirtualTreePoint GetStartPoint(SourceText text, ArrowExpressionClauseSyntax node, EnvDTE.vsCMPart part)
242private static VirtualTreePoint GetStartPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part)
275private static VirtualTreePoint GetStartPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part)
305private static VirtualTreePoint GetStartPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part)
353private static VirtualTreePoint GetStartPoint(SourceText text, LineFormattingOptions options, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part)
442private static VirtualTreePoint GetStartPoint(SourceText text, LineFormattingOptions options, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part)
507private static VirtualTreePoint GetStartPoint(SourceText text, LineFormattingOptions options, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part)
556private static VirtualTreePoint GetStartPoint(SourceText text, BaseNamespaceDeclarationSyntax node, EnvDTE.vsCMPart part)
605private static VirtualTreePoint GetStartPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part)
645private static VirtualTreePoint GetStartPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part)
678private static VirtualTreePoint GetStartPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part)
719private static VirtualTreePoint GetStartPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part)
759private static VirtualTreePoint GetStartPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part)
799private static VirtualTreePoint GetEndPoint(SourceText text, ArrowExpressionClauseSyntax node, EnvDTE.vsCMPart part)
817private static VirtualTreePoint GetEndPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part)
850private static VirtualTreePoint GetEndPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part)
880private static VirtualTreePoint GetEndPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part)
921private static VirtualTreePoint GetEndPoint(SourceText text, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part)
995private static VirtualTreePoint GetEndPoint(SourceText text, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part)
1055private static VirtualTreePoint GetEndPoint(SourceText text, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part)
1094private static VirtualTreePoint GetEndPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part)
1135private static VirtualTreePoint GetEndPoint(SourceText text, BaseNamespaceDeclarationSyntax node, EnvDTE.vsCMPart part)
1184private static VirtualTreePoint GetEndPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part)
1217private static VirtualTreePoint GetEndPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part)
1258private static VirtualTreePoint GetEndPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part)
1300private static VirtualTreePoint GetEndPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part)
Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests (6)
Microsoft.VisualStudio.LanguageServices.Implementation (8)
Microsoft.VisualStudio.LanguageServices.LiveShare (7)
Microsoft.VisualStudio.LanguageServices.Razor (10)
Microsoft.VisualStudio.LanguageServices.Razor.UnitTests (213)
Cohost\CohostDocumentPullDiagnosticsTest.cs (25)
99Range = SourceText.From(input.Text).GetRange(input.NamedSpans["HTM1337"].First()),
108Range = SourceText.From(input.Text).GetRange(input.NamedSpans["TS2304"].First()),
117Range = SourceText.From(input.Text).GetRange(input.NamedSpans["CSS002"].First()),
146Range = SourceText.From(input.Text).GetRange(input.NamedSpans.First().Value.First())
182Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf("@@") + 1, 1))
187Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf("f"), 1))
220Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf("@{"), 1))
225Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf("~~"), 1))
254Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf("@*"), 1))
259Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf("~~"), 1))
288Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf("Ra"), 1))
293Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf("~~"), 1))
331Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf(".@") + 1, 1))
336Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf(".{") + 1, 1))
374Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf(". @") + 1, 1))
379Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf(". {") + 1, 1))
417Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf(": @") + 1, 1))
422Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf(": /") + 1, 1))
452Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf("/"), "/****/".Length))
457Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf("@"), CSharpExpression.Length))
486Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf(firstLine), firstLine.Length))
509Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf(firstLine), firstLine.Length))
543Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf("@("), "@(!EnableMyButton)".Length))
548Range = SourceText.From(input.Text).GetRange(new TextSpan(input.Text.IndexOf("T"), "ThisIsNotValid".Length))
587var inputText = await document.GetTextAsync(DisposalToken);
Microsoft.VisualStudio.LanguageServices.Xaml (3)
Microsoft.VisualStudioCode.RazorExtension (5)
Microsoft.VisualStudioCode.RazorExtension.UnitTests (147)
Roslyn.Diagnostics.Analyzers (92)
src\Compilers\Core\Portable\EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\SourceTextExtensions_SharedWithCodeStyle.cs (5)
16public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
32this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
44this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
82public static bool AreOnSameLine(this SourceText text, SyntaxToken token1, SyntaxToken token2)
87public static bool AreOnSameLine(this SourceText text, int pos1, int pos2)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Services\RefactoringHelpers\AbstractRefactoringHelpers.cs (6)
25public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
42private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span)
60SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray<TSyntaxNode> result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
179SourceText sourceText, SyntaxNode root, int location)
251SourceText sourceText, SyntaxToken tokenOnLocation, int location)
533SourceText sourceText,
Roslyn.Diagnostics.CSharp.Analyzers (17)
Roslyn.VisualStudio.DiagnosticsWindow (3)
Roslyn.VisualStudio.Next.UnitTests (94)
Remote\SnapshotSerializationTests.cs (11)
50var document1 = project1.AddDocument("Document1", SourceText.From(csCode));
54var document2 = project2.AddDocument("Document2", SourceText.From(vbCode));
60.AddAdditionalDocument("Additional", SourceText.From("hello"), ["test"], @".\Add").Project.Solution;
67loader: TextLoader.From(TextAndVersion.Create(SourceText.From("root = true"), VersionStamp.Create())))]);
153var document = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp).AddDocument("Document", SourceText.From(code));
173var document = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp).AddDocument("Document", SourceText.From(code));
532var document = CreateWorkspace().CurrentSolution.AddProject("empty", "empty", LanguageNames.CSharp).AddDocument("empty", SourceText.From(""));
535var text = await document.GetTextAsync().ConfigureAwait(false);
609var sourceText = SourceText.From("Hello", Encoding.UTF8);
627sourceText = SourceText.From("Hello", new NotSerializableEncoding());
Services\ServiceHubServicesTests.cs (62)
105var oldText = await oldDocument.GetTextAsync();
108var newText = oldText.WithChanges(new TextChange(TextSpan.FromBounds(0, 0), "/* test */"));
417params ImmutableArray<(string hintName, SourceText text)>[] values)
425ImmutableArray<ImmutableArray<(string hintName, SourceText text)>> values)
428ImmutableArray<(string hintName, SourceText text)> sourceTexts = default;
454var tempDoc = project.AddDocument("X.cs", SourceText.From("// "));
469Assert.True(localWorkspace.SetCurrentSolution(s => s.WithDocumentText(tempDocId, SourceText.From("// " + i)), WorkspaceChangeKind.SolutionChanged));
505var localText = await localDoc.GetTextAsync();
506var remoteText = await localDoc.GetTextAsync();
514private static SourceText CreateText(string content, Encoding encoding = null, SourceHashAlgorithm checksumAlgorithm = SourceHashAlgorithm.Sha1)
515=> SourceText.From(content, encoding ?? Encoding.UTF8, checksumAlgorithm);
517private static SourceText CreateStreamText(string content, bool useBOM, bool useMemoryStream)
524return SourceText.From(stream, encoding, SourceHashAlgorithm.Sha1, throwIfBinaryDetected: true);
528return SourceText.From(bytes, bytes.Length, encoding, SourceHashAlgorithm.Sha1, throwIfBinaryDetected: true);
540var sourceText = CreateText(Guid.NewGuid().ToString());
570var sourceText = CreateText(Guid.NewGuid().ToString());
664var contents = CreateText(Guid.NewGuid().ToString());
672var contents = CreateText(Guid.NewGuid().ToString());
722return ImmutableArray.Create(("hint", SourceText.From($"// generated document {callCount}", Encoding.UTF8)));
744solution = solution.WithTextDocumentText(tempDocId, SourceText.From("// new contents"));
777var tempDoc = project.AddDocument("X.cs", SourceText.From("// "));
806return ImmutableArray.Create(("hint", SourceText.From($"// generated document {callCount}", Encoding.UTF8)));
861return ImmutableArray.Create(("hint", SourceText.From($"// generated document {callCount}", Encoding.UTF8)));
915var tempDoc = project1.AddDocument("X.cs", SourceText.From("// "));
924var tempDoc = project2.AddDocument("X.cs", SourceText.From("// "));
966var tempDoc = project1.AddDocument("X.cs", SourceText.From("// "));
975var tempDoc = project2.AddDocument("X.cs", SourceText.From("// "));
1007var tempDoc = project1.AddDocument("X.cs", SourceText.From("// "));
1016var tempDoc = project2.AddDocument("X.cs", SourceText.From("// "));
1050var tempDoc = project1.AddDocument("X.cs", SourceText.From("// "));
1059var tempDoc = project2.AddDocument("X.cs", SourceText.From("// "));
1102var tempDoc = project1.AddDocument("X.cs", SourceText.From("// "));
1112var tempDoc = project2.AddDocument("X.cs", SourceText.From("// "));
1155var tempDoc = project1.AddDocument("X.cs", SourceText.From("// "));
1165var tempDoc = project2.AddDocument("X.cs", SourceText.From("// "));
1208var tempDoc = project1.AddDocument("X.cs", SourceText.From("// "));
1218var tempDoc = project2.AddDocument("X.cs", SourceText.From("// "));
1253var tempDoc = project1.AddDocument("X.cs", SourceText.From("// "));
1263var tempDoc = project2.AddDocument("X.cs", SourceText.From("// "));
1298var tempDoc = project1.AddDocument("X.cs", SourceText.From("// "));
1307var tempDoc = project2.AddDocument("X.cs", SourceText.From("// "));
1341var tempDoc = project1.AddDocument("X.cs", SourceText.From("// "));
1350var tempDoc = project2.AddDocument("X.cs", SourceText.From("// "));
1455Contract.ThrowIfFalse(workspace.TryApplyChanges(workspace.CurrentSolution.WithDocumentText(normalDocId, SourceText.From("// new text"))));
1515var tempDoc = project.AddDocument("X.cs", SourceText.From("// "));
1527Contract.ThrowIfFalse(workspace.TryApplyChanges(workspace.CurrentSolution.WithDocumentText(tempDoc.Id, SourceText.From("// new text"))));
1541Contract.ThrowIfFalse(workspace.TryApplyChanges(workspace.CurrentSolution.WithDocumentText(tempDoc.Id, SourceText.From("// more new text"))));
1563var text = await docs
1599var tempDoc = project.AddDocument("X.cs", SourceText.From("// "));
1611Contract.ThrowIfFalse(workspace.TryApplyChanges(workspace.CurrentSolution.WithDocumentText(tempDoc.Id, SourceText.From("// new text"))));
1633Contract.ThrowIfFalse(workspace.TryApplyChanges(workspace.CurrentSolution.WithDocumentText(tempDoc.Id, SourceText.From("// more new text"))));
1678var tempDoc = project.AddDocument("X.cs", SourceText.From("// "));
1690Contract.ThrowIfFalse(workspace.TryApplyChanges(workspace.CurrentSolution.WithDocumentText(tempDoc.Id, SourceText.From("// new text"))));
1717Contract.ThrowIfFalse(workspace.TryApplyChanges(workspace.CurrentSolution.WithDocumentText(tempDoc.Id, SourceText.From("// more new text"))));
1762var tempDoc = project.AddDocument("X.cs", SourceText.From("// "));
1882var tempDoc = project1.AddDocument("X.cs", SourceText.From("// "));
1931var text = await document.GetTextAsync();
2053private static SourceText GetNewText(Document document, string csAddition, string vbAddition)
2057return SourceText.From(document.State.GetTextSynchronously(CancellationToken.None).ToString() + csAddition);
2060return SourceText.From(document.State.GetTextSynchronously(CancellationToken.None).ToString() + vbAddition);
2172solution = current.AddDocument($"Document{i}", SourceText.From(documents[i])).Project.Solution;
2178solution = current.AddAdditionalDocument($"AdditionalDocument{i}", SourceText.From(additionalDocuments[i])).Project.Solution;
Services\SolutionServiceTests.cs (18)
159await VerifySolutionUpdate(code, s => s.WithDocumentText(s.Projects.First().DocumentIds.First(), SourceText.From(code + " ")));
307project = project.AddDocument("newDocument", SourceText.From("// new text")).Project;
326loader: TextLoader.From(TextAndVersion.Create(SourceText.From("test"), VersionStamp.Create())));
337return s.WithAdditionalDocumentText(additionalDocumentId, SourceText.From("changed"));
358loader: TextLoader.From(TextAndVersion.Create(SourceText.From("root = true"), VersionStamp.Create(), filePath: configPath)),
370return s.WithAnalyzerConfigDocumentText(analyzerConfigDocumentId, SourceText.From("root = false"));
390loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class A { }"), VersionStamp.Create())));
401return s.WithDocumentText(documentId, SourceText.From("class Changed { }"));
428var currentSolution = remoteSolution1.WithDocumentText(remoteSolution1.Projects.First().Documents.First().Id, SourceText.From(code + " class Test2 { }"));
437currentSolution = oopSolution2.WithDocumentText(oopSolution2.Projects.First().Documents.First().Id, SourceText.From(code + " class Test3 { }"));
513var frozenText1 = SourceText.From("// Hello, World!");
522var frozenText2 = SourceText.From("// Hello, World! A second time!");
868solution = solution.GetProject(project1.Id).AddDocument("X.cs", SourceText.From("// X")).Project.Solution;
869solution = solution.GetProject(project2.Id).AddDocument("Y.vb", SourceText.From("' Y")).Project.Solution;
923solution = solution.GetProject(project1.Id).AddDocument("X.cs", SourceText.From("// X")).Project.Solution;
924solution = solution.GetProject(project2.Id).AddDocument("Y.cs", SourceText.From("// Y")).Project.Solution;
StackDepthTest (1)
System.Private.CoreLib.Generators (1)
System.Text.Json.SourceGeneration (17)
JsonSourceGenerator.Emitter.cs (14)
109private partial void AddSource(string hintName, SourceText sourceText);
124SourceText? sourceText = GenerateTypeInfo(contextGenerationSpec, typeGenerationSpec);
195private static SourceText CompleteSourceFileAndReturnText(SourceWriter writer)
206private SourceText? GenerateTypeInfo(ContextGenerationSpec contextSpec, TypeGenerationSpec typeGenerationSpec)
241private static SourceText GenerateForTypeWithBuiltInConverter(ContextGenerationSpec contextSpec, TypeGenerationSpec typeMetadata)
258private static SourceText GenerateForTypeWithCustomConverter(ContextGenerationSpec contextSpec, TypeGenerationSpec typeMetadata)
279private static SourceText GenerateForNullable(ContextGenerationSpec contextSpec, TypeGenerationSpec typeMetadata)
300private static SourceText GenerateForUnsupportedType(ContextGenerationSpec contextSpec, TypeGenerationSpec typeMetadata)
316private static SourceText GenerateForEnum(ContextGenerationSpec contextSpec, TypeGenerationSpec typeMetadata)
332private SourceText GenerateForCollection(ContextGenerationSpec contextSpec, TypeGenerationSpec typeGenerationSpec)
506private SourceText GenerateForObject(ContextGenerationSpec contextSpec, TypeGenerationSpec typeMetadata)
1714private static SourceText GetRootJsonContextImplementation(ContextGenerationSpec contextSpec, bool emitGetConverterForNullablePropertyMethod, bool emitValueTypeSetterDelegate)
1992private static SourceText GetGetTypeInfoImplementation(ContextGenerationSpec contextSpec)
2034private SourceText GetPropertyNameInitialization(ContextGenerationSpec contextSpec)
System.Windows.Forms.Analyzers (1)
System.Windows.Forms.Analyzers.CSharp.Tests (7)
System.Windows.Forms.Analyzers.Tests (12)
Test.Utilities (69)
src\Compilers\Core\Portable\EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\SourceTextExtensions_SharedWithCodeStyle.cs (5)
16public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
32this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
44this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
82public static bool AreOnSameLine(this SourceText text, SyntaxToken token1, SyntaxToken token2)
87public static bool AreOnSameLine(this SourceText text, int pos1, int pos2)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Services\RefactoringHelpers\AbstractRefactoringHelpers.cs (6)
25public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
42private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span)
60SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray<TSyntaxNode> result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
179SourceText sourceText, SyntaxNode root, int location)
251SourceText sourceText, SyntaxToken tokenOnLocation, int location)
533SourceText sourceText,
Text.Analyzers (95)
src\Compilers\Core\Portable\EncodedStringText.cs (11)
72/// Initializes an instance of <see cref="SourceText"/> from the provided stream. This version differs
73/// from <see cref="SourceText.From(Stream, Encoding, SourceHashAlgorithm, bool)"/> in two ways:
91internal static SourceText Create(Stream stream,
103internal static SourceText Create(Stream stream,
136/// Try to create a <see cref="SourceText"/> from the given stream using the given encoding.
143/// <returns>The <see cref="SourceText"/> decoded from the stream.</returns>
146private static SourceText Decode(
165return SourceText.From(bytes.Array,
175return SourceText.From(data, encoding, checksumAlgorithm, throwIfBinaryDetected, canBeEmbedded);
249internal static SourceText Create(Stream stream, Lazy<Encoding> getEncoding, Encoding defaultEncoding, SourceHashAlgorithm checksumAlgorithm, bool canBeEmbedded)
252internal static SourceText Decode(Stream data, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\SourceTextExtensions_SharedWithCodeStyle.cs (5)
16public static string GetLeadingWhitespaceOfLineAtPosition(this SourceText text, int position)
32this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden, CancellationToken cancellationToken)
44this SourceText text, TextSpan span, Func<int, CancellationToken, bool> isPositionHidden,
82public static bool AreOnSameLine(this SourceText text, SyntaxToken token1, SyntaxToken token2)
87public static bool AreOnSameLine(this SourceText text, int pos1, int pos2)
src\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Services\RefactoringHelpers\AbstractRefactoringHelpers.cs (6)
25public abstract bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
42private static TextSpan GetTrimmedTextSpan(SourceText sourceText, TextSpan span)
60SourceText sourceText, SyntaxNode root, TextSpan selectionRaw, bool allowEmptyNodes, int maxCount, ref TemporaryArray<TSyntaxNode> result, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode
179SourceText sourceText, SyntaxNode root, int location)
251SourceText sourceText, SyntaxToken tokenOnLocation, int location)
533SourceText sourceText,
Text.Analyzers.UnitTests (1)