Skip to content

Commit

Permalink
walker/schemacontext: Introduce nesting level
Browse files Browse the repository at this point in the history
  • Loading branch information
radeksimko committed Nov 6, 2023
1 parent 8715001 commit 0d22b9d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
7 changes: 7 additions & 0 deletions decoder/internal/walker/walker.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ type Walker interface {
func Walk(ctx context.Context, node hclsyntax.Node, nodeSchema schema.Schema, w Walker) hcl.Diagnostics {
var diags hcl.Diagnostics

blkNestingLvl, ok := schemacontext.BlockNestingLevel(ctx)
if !ok {
ctx = schemacontext.WithBlockNestingLevel(ctx, 0)
blkNestingLvl = 0
}

switch nodeType := node.(type) {
case *hclsyntax.Body:
bodyCtx := ctx
Expand Down Expand Up @@ -105,6 +111,7 @@ func Walk(ctx context.Context, node hclsyntax.Node, nodeSchema schema.Schema, w
blockBodySchema = mergedSchema
}

blockCtx = schemacontext.WithBlockNestingLevel(blockCtx, blkNestingLvl+1)
diags = diags.Extend(Walk(blockCtx, nodeType.Body, blockBodySchema, w))

// TODO: case hclsyntax.Expression
Expand Down
10 changes: 10 additions & 0 deletions schemacontext/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import "context"
type unknownSchemaCtxKey struct{}
type foundBlocksCtxKey struct{}
type dynamicBlocksCtxKey struct{}
type blockNestingLevelCtxKey struct{}

// WithUnknownSchema attaches a flag indicating that the schema being passed
// is not wholly known.
Expand Down Expand Up @@ -42,3 +43,12 @@ func WithDynamicBlocks(ctx context.Context, dynamicBlocks map[string]uint64) con
func DynamicBlocks(ctx context.Context) map[string]uint64 {
return ctx.Value(dynamicBlocksCtxKey{}).(map[string]uint64)
}

func WithBlockNestingLevel(ctx context.Context, nestingLvl uint64) context.Context {
return context.WithValue(ctx, blockNestingLevelCtxKey{}, nestingLvl)
}

func BlockNestingLevel(ctx context.Context) (uint64, bool) {
lvl, ok := ctx.Value(blockNestingLevelCtxKey{}).(uint64)
return lvl, ok
}

0 comments on commit 0d22b9d

Please sign in to comment.