Skip to content

Meta information for objects and not just for blocks? #130

Open

Description

@ioah86

I love the feature where you include line numbers to blocks. Why was this not extended to objecs?

def object(self, args: List) -> Dict:
args = self.strip_new_line_tokens(args)
result: Dict[str, Any] = {}
for arg in args:
result.update(arg)
return result

I tried out a small alteration, and it seems to work fine for me:

class CustomDictTransformer(hcl2.transformer.DictTransformer):
    """
    Custom alteration of the DictTransformer.
    """

    @v_args(meta=True)
    def object(self, meta: Meta, args: List) -> Dict:
        args = self.strip_new_line_tokens(args)
        result: Dict[str, Any] = {}
        for arg in args:
            result.update(arg)
        if self.with_meta:
            result.update(
                {
                    hcl2.transformer.START_LINE: meta.line,
                    hcl2.transformer.END_LINE: meta.end_line,
                }
            )
        return result

def load_hcl2(file: TextIO, with_meta=False) -> dict:
    """Load a HCL2 file.
    :param file: File with hcl2 to be loaded as a dict.
    :param with_meta: If set to true then adds `__start_line__` and `__end_line__`
    parameters to the output dict. Default to false.
    """
    return loads_hcl2(file.read(), with_meta=with_meta)


def loads_hcl2(text: str, with_meta=False) -> dict:
    """Load HCL2 from a string.
    :param text: Text with hcl2 to be loaded as a dict.
    :param with_meta: If set to true then adds `__start_line__` and `__end_line__`
    parameters to the output dict. Default to false.
    """
    # append new line as a workaround for https://github.com/lark-parser/lark/issues/237
    # Lark doesn't support a EOF token so our grammar can't look for "new line or end of file"
    # This means that all blocks must end in a new line even if the file ends
    # Append a new line as a temporary fix
    tree = hcl2.parser.hcl2.parse(text + "\n")
    return CustomDictTransformer(with_meta=with_meta).transform(tree)

I would suggest to add that. It does not hurt and is useful for the people using meta information.

Activity

  1. added
    enhancement
    serialization
    on Apr 9, 2026
  2. livingstaccato commented on Sep 1, 2026

    @livingstaccato
    Contributor

    Two things worth knowing before anyone picks this up.

    The snippet here subclasses hcl2.transformer.DictTransformer, which the v8
    rewrite removed — serialization moved onto the rule classes, so object meta
    would now go in ObjectRule.serialize in hcl2/rules/containers.py rather than
    a transformer method. The idea carries over; the patch does not.

    More to the point, the feature this asks to extend is currently inert.
    with_meta has emitted nothing at all since v8 — see #291 — so block meta is
    not a working baseline to generalise from. That wants fixing first.

    When it is, I would suggest a different shape for objects than for blocks.
    __start_line__ in a block is an established v7 convention, and a block's
    dict is structural. An object's dict is user data: tags = {Name = "x"} would
    come back as {"Name": "x", "__start_line__": 3, "__end_line__": 3}, and since
    HCL puts no namespace around these, a configuration is free to contain an
    attribute genuinely named __start_line__ — I hit exactly that case downstream,
    where filtering the key silently deleted the user's own attribute.

    The query API avoids the collision entirely, because it reports positions
    without putting them in the value:

    block = hcl2.query(text).blocks("resource")[0]
    block.start_line, block.end_line

    I have a branch adding those two properties to BlockView alongside the #291
    fix; the same pair on ObjectView (and AttributeView, which #291 does not
    cover either) would serve this issue without touching anyone's data. Happy to
    put that up as a follow-up once #291 is resolved, if that direction appeals.



    Researched with AI assistance; the measurements above were executed rather than inferred, and reviewed and approved by me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

enhancementserialization

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions