zclsyntax: Implement the ContextString interface on our Nav
This allows tooling to get a string describing the context of a particular offset into the file. This is used, for example, to provide context above the source code snippets in console-printed diagnostic messages.
This commit is contained in:
parent
6f1cf4465d
commit
c9c2a2bd16
41
zcl/zclsyntax/navigation.go
Normal file
41
zcl/zclsyntax/navigation.go
Normal file
@ -0,0 +1,41 @@
|
||||
package zclsyntax
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type navigation struct {
|
||||
root *Body
|
||||
}
|
||||
|
||||
// Implementation of zcled.ContextString
|
||||
func (n navigation) ContextString(offset int) string {
|
||||
// We will walk our top-level blocks until we find one that contains
|
||||
// the given offset, and then construct a representation of the header
|
||||
// of the block.
|
||||
|
||||
var block *Block
|
||||
for _, candidate := range n.root.Blocks {
|
||||
if candidate.Range().ContainsOffset(offset) {
|
||||
block = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if block == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
if len(block.Labels) == 0 {
|
||||
// Easy case!
|
||||
return block.Type
|
||||
}
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
buf.WriteString(block.Type)
|
||||
for _, label := range block.Labels {
|
||||
fmt.Fprintf(buf, " %q", label)
|
||||
}
|
||||
return buf.String()
|
||||
}
|
@ -23,6 +23,10 @@ func ParseConfig(src []byte, filename string, start zcl.Pos) (*zcl.File, zcl.Dia
|
||||
return &zcl.File{
|
||||
Body: body,
|
||||
Bytes: src,
|
||||
|
||||
Nav: navigation{
|
||||
root: body,
|
||||
},
|
||||
}, diags
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user