hashicorp / hcl-lang

Schema and decoder to be used as building blocks for an HCL2-based language server.
https://pkg.go.dev/github.com/hashicorp/hcl-lang
Mozilla Public License 2.0
84 stars 24 forks source link

Extend symbols with concrete `*hcl.(Attribute/Block/Expression)` #409

Open magodo opened 3 months ago

magodo commented 3 months ago

I have a use case of this module: I'd like to firstly call the Decoder.Symbols to get the target symbols of a query. Then iterate each symbols (recursively visiting its nested symbols). Then check whether those symbols are reference origins/targets, by using ReferenceOriginsTargetingPos()/ReferenceTargetsForOriginAtPos(), with passing in the position of the symbols.

The problem is that the symbol's position is larger than what those two functions expected. E.g. Given following HCL:

provider "azurerm" {
  features {
    resource_group {
      prevent_deletion_if_contains_resources = false
    }
  }
}

resource "azurerm_resource_group" "src" {
  name     = "my-rg"
  location = "westeurope"
}

resource "azurerm_resource_group" "dst" {
  name     = azurerm_resource_group.src.name
  location = azurerm_resource_group.src.location
  tags = {
    source = azurerm_resource_group.src.id
  }
}

The symbol of azurerm_resource_group.dst's attribute name, its range spans from column 3 to column 45, which is effectively name = azurerm_resource_group.src.name, which is not recognised by ReferenceTargetsForOriginAtPos(). Instead, it wants the pos is within range column 14 to column 45.

Furthermore, we also want to get the exact position of, e.g. for AttributeSymbol, the key and value positions. These are missing in the current symbol types.

This PR adds: