-2

I am trying to get all the regions I have in a class and fetch all the statements inside it. When I try to access the location of SyntaxTrivia object, application throws NullReferenceException

I have created a dictionary to store the start and end location of the regions. I am looping through each region and trying to fetch the location.

private static void Analyze(SyntaxNodeAnalysisContext context)
        {
            ClassDeclarationSyntax classDeclaration = (ClassDeclarationSyntax)context.Node;

            SyntaxTriviaList regions = classDeclaration.DescendantTrivia().ToImmutableList()
                .FindAll(x => x.Kind().Equals(SyntaxKind.RegionDirectiveTrivia) || x.Kind().Equals(SyntaxKind.EndRegionDirectiveTrivia))
                .ToSyntaxTriviaList();

            Dictionary<Location, Location> regionLocations = new Dictionary<Location, Location>();

            Location regionStart = classDeclaration.GetLocation();

            foreach (SyntaxTrivia region in regions)
            {
                if (regions.IndexOf(region) / 2 == 0)
                {
                    Location ll = region.GetLocation();
                    regionLocations.Add(region.GetLocation(), region.GetLocation());
                    regionStart = region.GetLocation();
                }
                else
                {
                    regionLocations.Add(regionStart, region.GetLocation());
                }
            }

        }
Gaurav Gandhi
  • 161
  • 2
  • 2
  • 9

1 Answers1

0

The problem is with ToSyntaxTriviaList. The produced trivia are detached from the syntax tree, which in turn means that GetLocation throws an exception, since it needs a syntax tree to work.

You have two main options:

  1. Use span instead of location
  2. Don't use ToSyntaxTriviaList
Luaan
  • 62,244
  • 7
  • 97
  • 116