File: source_pos.go

package info (click to toggle)
golang-github-hashicorp-terraform-config-inspect 0.0~git20230614.f32df32-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 472 kB
  • sloc: makefile: 2
file content (53 lines) | stat: -rw-r--r-- 1,619 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package tfconfig

import (
	legacyhcltoken "github.com/hashicorp/hcl/hcl/token"
	"github.com/hashicorp/hcl/v2"
)

// SourcePos is a pointer to a particular location in a source file.
//
// This type is embedded into other structs to allow callers to locate the
// definition of each described module element. The SourcePos of an element
// is usually the first line of its definition, although the definition can
// be a little "fuzzy" with JSON-based config files.
type SourcePos struct {
	Filename string `json:"filename"`
	Line     int    `json:"line"`
}

func sourcePos(filename string, line int) SourcePos {
	return SourcePos{
		Filename: filename,
		Line:     line,
	}
}

func sourcePosHCL(rng hcl.Range) SourcePos {
	// We intentionally throw away the column information here because
	// current and legacy HCL both disagree on the definition of a column
	// and so a line-only reference is the best granularity we can do
	// such that the result is consistent between both parsers.
	return SourcePos{
		Filename: rng.Filename,
		Line:     rng.Start.Line,
	}
}

func sourcePosLegacyHCL(pos legacyhcltoken.Pos, filename string) SourcePos {
	useFilename := pos.Filename
	// We'll try to use the filename given in legacy HCL position, but
	// in practice there's no way to actually get this populated via
	// the HCL API so it's usually empty except in some specialized
	// situations, such as positions in error objects.
	if useFilename == "" {
		useFilename = filename
	}
	return SourcePos{
		Filename: useFilename,
		Line:     pos.Line,
	}
}