Skip to content

Index

pyvider.hcl.parser

HCL parsing module.

This module provides HCL parsing functionality with CTY type integration.

Functions

auto_infer_cty_type

auto_infer_cty_type(raw_data: Any) -> CtyValue[Any]

Automatically infer CTY type from raw Python data.

This function takes Python data structures (typically from HCL parsing) and automatically infers appropriate CTY types using pyvider-cty's canonical inference implementation.

Parameters:

Name Type Description Default
raw_data Any

Python data structure to infer types for

required

Returns:

Type Description
CtyValue[Any]

CTY value with inferred types

Example

data = {"name": "test", "count": 5} result = auto_infer_cty_type(data) isinstance(result.type, CtyObject) True

Note

This delegates to pyvider.cty.conversion.infer_cty_type_from_raw() which provides sophisticated type inference including: - List element type analysis (e.g., [1,2,3] → list(number)) - Object attribute inference - Type unification for mixed collections - Caching and cycle detection

Source code in pyvider/hcl/parser/inference.py
def auto_infer_cty_type(raw_data: Any) -> CtyValue[Any]:
    """Automatically infer CTY type from raw Python data.

    This function takes Python data structures (typically from HCL parsing)
    and automatically infers appropriate CTY types using pyvider-cty's
    canonical inference implementation.

    Args:
        raw_data: Python data structure to infer types for

    Returns:
        CTY value with inferred types

    Example:
        >>> data = {"name": "test", "count": 5}
        >>> result = auto_infer_cty_type(data)
        >>> isinstance(result.type, CtyObject)
        True

    Note:
        This delegates to pyvider.cty.conversion.infer_cty_type_from_raw()
        which provides sophisticated type inference including:
        - List element type analysis (e.g., [1,2,3] → list(number))
        - Object attribute inference
        - Type unification for mixed collections
        - Caching and cycle detection
    """
    # Use pyvider-cty's canonical inference implementation
    inferred_type = infer_cty_type_from_raw(raw_data)
    return inferred_type.validate(raw_data)  # type: ignore[no-any-return]

parse_hcl_to_cty

parse_hcl_to_cty(
    hcl_content: str, schema: CtyType[Any] | None = None
) -> CtyValue[Any]

Parse HCL directly into validated CtyValues using pyvider.cty types.

Parameters:

Name Type Description Default
hcl_content str

HCL string to parse

required
schema CtyType[Any] | None

Optional CTY type schema for validation

None

Returns:

Type Description
CtyValue[Any]

Parsed and validated CTY value

Raises:

Type Description
HclParsingError

If parsing or validation fails

Example

hcl = 'name = "example"' result = parse_hcl_to_cty(hcl) result.value["name"].value 'example'

Source code in pyvider/hcl/parser/base.py
def parse_hcl_to_cty(hcl_content: str, schema: CtyType[Any] | None = None) -> CtyValue[Any]:
    """Parse HCL directly into validated CtyValues using pyvider.cty types.

    Args:
        hcl_content: HCL string to parse
        schema: Optional CTY type schema for validation

    Returns:
        Parsed and validated CTY value

    Raises:
        HclParsingError: If parsing or validation fails

    Example:
        >>> hcl = 'name = "example"'
        >>> result = parse_hcl_to_cty(hcl)
        >>> result.value["name"].value
        'example'
    """

    try:
        raw_data = hcl2.loads(hcl_content)  # type: ignore[attr-defined]
    except Exception as e:
        raise HclParsingError(message=f"Failed to parse HCL: {e}") from e

    if schema:
        try:
            validated_value = schema.validate(raw_data)
            return validated_value
        except (CtySchemaError, CtyValidationError) as e:
            raise HclParsingError(message=f"Schema validation failed after HCL parsing: {e}") from e
    else:
        inferred_value = auto_infer_cty_type(raw_data)
        return inferred_value

parse_with_context

parse_with_context(
    content: str, source_file: Path | None = None
) -> Any

Parse HCL content with enhanced error context.

This function parses HCL content and provides rich error context if parsing fails. It returns the raw parsed data (dict/list), not CTY values.

Parameters:

Name Type Description Default
content str

HCL content string to parse

required
source_file Path | None

Optional source file path for error reporting

None

Returns:

Type Description
Any

Raw parsed data (typically dict or list)

Raises:

Type Description
HclParsingError

If parsing fails, with source location information

Example

content = 'name = "example"' data = parse_with_context(content) data['name'] 'example'

Source code in pyvider/hcl/parser/context.py
def parse_with_context(content: str, source_file: Path | None = None) -> Any:
    """Parse HCL content with enhanced error context.

    This function parses HCL content and provides rich error context if parsing fails.
    It returns the raw parsed data (dict/list), not CTY values.

    Args:
        content: HCL content string to parse
        source_file: Optional source file path for error reporting

    Returns:
        Raw parsed data (typically dict or list)

    Raises:
        HclParsingError: If parsing fails, with source location information

    Example:
        >>> content = 'name = "example"'
        >>> data = parse_with_context(content)
        >>> data['name']
        'example'
    """
    source_str = str(source_file) if source_file else "string input"

    try:
        return hcl2.loads(content)  # type: ignore[attr-defined]
    except Exception as e:
        logger.error(
            "HCL parsing failed",
            source=source_str,
            error=str(e),
            exc_info=True,
        )
        raise HclParsingError(
            message=str(e),
            source_file=str(source_file) if source_file else None,
        ) from e