Skip to content

Commit

Permalink
Fix a couple of exceptions encountered when formatting documents with…
Browse files Browse the repository at this point in the history
… preprocessor directives
  • Loading branch information
davidwengier committed Jan 9, 2025
1 parent a91b26f commit cdc677a
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,12 @@ public static bool TryGetLinePositionSpanWithoutWhitespace(this SyntaxNode node,
var startPositionSpan = GetLinePositionSpan(firstToken, source, node.SpanStart);
var endPositionSpan = GetLinePositionSpan(lastToken, source, node.SpanStart);

if (endPositionSpan.End < startPositionSpan.Start)
{
linePositionSpan = default;
return false;
}

linePositionSpan = new LinePositionSpan(startPositionSpan.Start, endPositionSpan.End);
return true;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,15 @@ static void ExtractTriviaAnnotations(
var formattedTriviaList = formattedRoot.GetAnnotatedTrivia(MarkerId);
foreach (var trivia in formattedTriviaList)
{
// We only expect one annotation because we built the entire trivia with a single annotation.
var annotation = trivia.GetAnnotations(MarkerId).Single();
if (!int.TryParse(annotation.Data, out var projectedIndex))
// We only expect one annotation because we built the entire trivia with a single annotation, but
// we need to be defensive here. Annotations are a little hard to work with though, so apologies for
// the slightly odd method of validation.
using var enumerator = trivia.GetAnnotations(MarkerId).GetEnumerator();
enumerator.MoveNext();
var annotation = enumerator.Current;
// We shouldn't be able to enumerate any more, and we should be able to parse our data out of the annotation.
if (enumerator.MoveNext() ||
!int.TryParse(annotation.Data, out var projectedIndex))
{
// This shouldn't happen realistically unless someone messed with the annotations we added.
// Let's ignore this annotation.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,46 @@ @typeparam TValue
}
}

[FormattingTestFact]
public async Task PreprocessorDirectives()
{
await RunFormattingTestAsync(
input: """
<div Model="SomeModel">
<div />
@{
#if DEBUG
}
<div />
@{
#endif
}
</div>
@code {
private object SomeModel {get;set;}
}
""",
expected: """
<div Model="SomeModel">
<div />
@{
#if DEBUG
}
<div />
@{
#endif
}
</div>
@code {
private object SomeModel { get; set; }
}
""",
allowDiagnostics: true);
}

private ImmutableArray<TagHelperDescriptor> GetComponents()
{
AdditionalSyntaxTrees.Add(Parse("""
Expand Down

0 comments on commit cdc677a

Please sign in to comment.