API Reference¶
Everything documented here is importable directly from the top-level literalizer package (exceptions live in literalizer.exceptions).
Core functions¶
- literalizer.literalize(*, source: str, input_format: InputFormat, language: Language, pre_indent_level: int = 0, include_delimiters: bool = True, variable_form: NewVariable | ExistingVariable | BothVariableForms | None = None, wrap_in_file: bool = False, ref_case: IdentifierCase | None = None, ref_values: Mapping[str, ValueInput] | None = None, bound_refs: Mapping[str, ValueInput] | None = None, ref_key: str = '$ref', collection_layout: CollectionLayout = CollectionLayout.COMPACT) LiteralizeResult¶
Convert a JSON, JSON5, YAML, or TOML string to a native language literal.
YAML and TOML comments are preserved in the output using the target language’s comment syntax.
- Parameters:
source – The input string to convert.
input_format – The serialization format of source.
language – A
Languageinstance describing how to format literals. Use one of the built-in constants (e.g.PYTHON,GO) or provide your own. Languages whosewrap_in_fileintroduces a named scope (the wrapping class in Java, theprogramin Fortran, the-modulein Erlang) carry that name as a constructor argument (Java(module_name="Foo")); languages whose wrappers do not introduce a named scope take no such argument.pre_indent_level – Number of
indentsteps to prepend to every output line. For example,2with a 4-space indent produces an 8-space margin. Defaults to0.include_delimiters – If True, include the collection delimiters (
[…]for arrays,{…}for dicts).variable_form – Controls how the output is wrapped in a variable. Pass
NewVariableto useformat_variable_declaration(e.g.const x =in JavaScript),ExistingVariableto useformat_variable_assignment(e.g.x =), orBothVariableFormsto produce both a declaration and an assignment combined in one output (requires wrap_in_file).None(default) means no variable wrapping.wrap_in_file – If
True, assemblecodeas a complete, valid source file using the language’swrap_in_filemethod and prependpreamble. When set,preambleandbody_preambleon the result are empty tuples (their content has been folded intocode).ref_case – Optional
IdentifierCasecontrolling how ref identifiers are cased in the rendered output.{ref_key: "name"}markers anywhere in the data are rendered as bare identifiers using the language’sformat_call_ref_identifierhook. WhenNone(default), ref names are emitted verbatim. When set, the identifier name is converted to ref_case first.ref_values – Optional mapping from ref identifier to the value declared elsewhere for that ref. Some languages render a ref differently depending on the type behind it (V emits
namefor primitive scalars butname.clone()for arrays and maps); supplying ref_values lets those languages pick the right form. When omitted, a ref’s type is unknown and languages fall back to their type-agnostic default. Keys should match the identifiers used in source before any ref_case conversion.bound_refs – Optional mapping from ref identifier to the value that ref should be bound to. Unlike ref_values (which only feeds type knowledge to the ref site, leaving the ref as a free external identifier), each name in bound_refs additionally has a binding emitted for it, in bound_refs iteration order, so a single
literalizecall withwrap_in_file=Trueproduces a complete, valid file with per-language declaration sequencing (Nix nestedlet, Fortran two-phase declarations, and so on). Supply bound_refs ordered by each ref’s first use in source (and limited to refs that appear there) so every binding precedes its first use and no unused binding is emitted. Binding emission only happens when wrap_in_file isTrueand variable_form is aNewVariableorExistingVariable(a binding the refs can precede); otherwise bound_refs degrades to type information only, exactly like ref_values, and the refs stay free identifiers. Entries also act as ref_values for their names, so a name need not be repeated in both mappings. Keys should match the identifiers used in source before any ref_case conversion. Defaults toNone(no bindings emitted; behavior is byte-identical to omitting this argument).ref_key – The dict key used to identify variable-reference markers in the input data. A single-key dict whose key equals ref_key and whose value is a string is treated as a ref marker. Defaults to
"$ref".collection_layout – Controls layout for collections nested inside other collections.
CollectionLayout.COMPACTpreserves the existing one-line nested rendering, whileCollectionLayout.MULTILINEexpands non-empty nested collections with one element per line.
- Raises:
JSONParseError – If input_format is
JSONand source is not valid JSON.JSON5ParseError – If input_format is
JSON5and source is not valid JSON5.YAMLParseError – If input_format is
YAMLand source is not valid YAML.TOMLParseError – If input_format is
TOMLand source is not valid TOML.HeterogeneousCollectionError – If the data contains collections whose shape cannot be represented in the target language (e.g. heterogeneous scalar types in a language that requires homogeneous collections).
ValueError – If variable_form is
BothVariableFormsand wrap_in_file isFalse, or if the language’sdeclaration_styledoes not support redefinition.UnsupportedIdentifierCaseError – If ref_case is not in
supported_ref_casesfor the target language.VariableNameNotSupportedError – If variable_form is supplied but the target language sets
supports_variable_namestoFalse.WrapInFileWithoutVariableNotSupportedError – If wrap_in_file is
Trueand variable_form isNonebut the target language setssupports_no_variable_wrap_in_filetoFalse(i.e. it cannot represent a bare value at file-statement scope).
- literalizer.literalize_call(*, source: str, input_format: InputFormat, language: Language, target_function: str, parameter_names: Sequence[str], call_transform: Callable[[CallContext], str] | None = None, zip_source: str | None = None, zip_input_format: InputFormat | None = None, comment_source: Sequence[str] | None = None, per_element: bool = True, wrap_in_file: bool = False, ref_case: IdentifierCase | None = None, consumable_refs: frozenset[str] = frozenset({}), ref_values: Mapping[str, ValueInput] | None = None, bound_refs: Mapping[str, ValueInput] | None = None, ref_key: str = '$ref', collection_layout: CollectionLayout = CollectionLayout.COMPACT, variable_form: NewVariable | ExistingVariable | BothVariableForms | None = None) LiteralizeResult¶
Convert data to function call expressions in the target language.
Each top-level list element (when per_element is
True) becomes a separate function call with arguments formatted according to the language’scall_style_config.- Parameters:
source – The input string to convert.
input_format – The serialization format of source.
language – A
Languageinstance describing how to format literals.target_function – The function expression to call (e.g.
"throttler.should_send_notification").parameter_names – Parameter names, positionally mapped to each element in each row. For
PositionalCallStylelanguages these are unused in the output but still determine how many values to expect per row.call_transform – Optional callable transforming each generated call. Invoked once per call as
call_transform(context)with aCallContextand returns the transformed string (e.g.lambda ctx: f"print({ctx.call})"). The context also exposes the call’s zero-basedindex, its inputrow, and the pairedzippedliteral, so a transform can render data from a parallel sequence beside each call. Only supported for languages whose call form is an expression that can be wrapped (positional, keyword, or object call style); prefix/postfix/command-style languages reject it withUnsupportedCallShapeError.zip_source – Optional companion source whose parsed top-level elements pair positionally with the generated calls. It is parsed with the same parser as source (so YAML
!!omap, datetime/bytes coercion, JSON5, TOML, … behave identically by construction), each paired value is rendered to a language-native literal (via the same machinery asliteralize()) and exposed onCallContext.zippedfor the matching call, enabling patterns like printing an expected value beside each call’s actual return value. When per_element isTrueit must parse to a list whose top-level elements pair element-by-element with the calls (a non-list raisesPerElementNotListError); otherwise the whole parsed value pairs with the single call. A length mismatch raisesZipValuesLengthMismatchError. Requires zip_input_format (supplying zip_source without it raisesZipSourceWithoutInputFormatError) and call_transform (the values are only reachable through it; supplying zip_source without one raisesZipValuesWithoutCallTransformError).zip_input_format – The serialization format of zip_source. Required whenever zip_source is supplied and ignored otherwise.
comment_source – Optional sequence of trailing source-code comments, one per generated call, paired positionally. Each non-empty entry is emitted as a line comment after the statement terminator on the call’s last line, using the language’s
comment_configleader (#,//,--, …); languages with no line comment fall back to that language’s block-comment form (/* ... */), which is valid on a single line. Because the comment is applied to the fully terminated statement, a line-comment leader never swallows the terminator (a problem a call_transform cannot avoid, since it only sees the pre-terminator call expression). An empty entry emits no comment. Unlike zip_source this is a plain sequence (not a parsed source) and needs neither a call_transform nor an input format. The entry count must equal the number of generated calls – one per top-level element when per_element isTrue, otherwise one for the single call – orCommentSourceLengthMismatchErroris raised; an entry containing a newline raisesCommentSourceMultilineError. A trailing comment is only safe where each generated call is a self-contained line; languages that assemble the call sequence into a single clause/list/expression (so a separator, terminator or closer follows the call on the same line, which a line comment would swallow) reject a non-empty comment_source withUnsupportedCallShapeError. The supported set is exactly the languages whosesupports_standalone_comments_in_wrapped_callsisTrue.per_element – If
True(default), each top-level list element becomes a separate call (an element that is itself an empty list yields a zero-argument call). IfFalse, the whole literalized value is passed as a single argument. A variable_form binding requires exactly one call, so it is valid withper_element=False(always one call) or withper_element=Trueover a single-element source; the zero-argument constructorp2 = Playlist()is produced by the latter with a[[]]source.wrap_in_file – If
True, assemblecodeas a complete, self-contained source file using the language’swrap_in_filemethod and prependpreamble. A no-op stub for target_function is also injected so the generated file does not reference an undefined name; when a call_transform is supplied the wrapper name it introduces is not stubbed — callers that transform calls are responsible for providing that definition themselves. When set,preambleandbody_preambleon the result are empty tuples (their content has been folded intocode).ref_case – Optional
IdentifierCasecontrolling how ref identifiers are cased in the rendered output. WhenNone(default) ref names are emitted verbatim. When set, each ref identifier is normalized tosnake_caseand then converted to the requested case viapyhumps, so the same source can drive idiomatic identifiers across multiple languages. When language’ssupported_ref_casesdoes not expose the requested case,UnsupportedIdentifierCaseErroris raised.consumable_refs – Names of ref identifiers this call owns and may move from. Refs in this set may be rendered with a consuming form (e.g. C++
std::move) when they appear in exactly one call argument; refs used by more than one call – or omitted from this set – are emitted as the bare identifier so subsequent uses of the variable remain valid. Names should match the identifiers used in source before any ref_case conversion. Defaults to an empty set (no refs are consumed).ref_values – Optional mapping from ref identifier to the source value declared elsewhere. When supplied, values for refs used in source are included in data-driven preamble inference, so languages with generated body types (for example Haskell’s
data Val = ...) declare constructors for types reachable only through refs. Missing ref names keep the historical behavior: their markers are omitted from preamble inference. Keys should match the identifiers used in source before any ref_case conversion.bound_refs – Optional mapping from ref identifier to the source value that ref should be declared with. The recommended way to render a complete, self-contained file that declares each ref and then calls the target with it:
literalizeexposes the same argument for the declaration-only case, and this is its call-side counterpart. Each entry is emitted as aNewVariabledeclaration (cased via ref_case) in bound_refs iteration order ahead of the calls, the value is folded into preamble inference exactly like ref_values (so a name need not be repeated in both mappings; an explicit ref_values entry for the same name wins), and the declarations, calls, and a no-op stub for target_function are wrapped into one file viawrap_calls_with_declarations()with a single reconciled preamble. Declaration emission only happens when wrap_in_file isTrue; otherwise bound_refs degrades to type information only, exactly like ref_values, and the refs stay free identifiers. Every name should appear as a$refmarker in source (a ref that is declared but never referenced is folded into neither the call nor its preamble inference and so may leave the declaration’s data-dependent preamble entries uncovered, besides being an unused binding); this mirrorsliteralize’s bound_refs contract. Incompatible with variable_form (which binds the call result): the two are rejected together withUnsupportedCallShapeErrorbecause the declaration-composition path cannot apply a language’s call-result binding file scaffold. Keys should match the identifiers used in source before any ref_case conversion. Defaults toNone(no bindings emitted; behavior is byte-identical to omitting this argument).ref_key – The dict key used to identify variable-reference markers in the input data. A single-key dict whose key equals ref_key and whose value is a string is treated as a ref marker. Defaults to
"$ref".collection_layout – Controls layout for collections nested inside call arguments.
CollectionLayout.COMPACTpreserves the existing one-line nested rendering, whileCollectionLayout.MULTILINEexpands non-empty nested collections with one element per line.variable_form – When supplied, wrap the call expression in a variable binding using the language’s
format_variable_declaration/format_variable_assignmenthook (the same machinery used byliteralize()). PassNewVariablefor an idiomatic declaration (let p2 = Playlist::new();,const p2 = new Playlist();,p2 = Playlist()) orExistingVariablefor an assignment to an existing name.BothVariableFormsis rejected withUnsupportedCallShapeErrorbecause emitting both a declaration and an assignment would invoke the target function twice. Mutability and inference are controlled by the per-languagedeclaration_styleandModifiersenums on the suppliedLanguageinstance, not by extra arguments here. A single name can bind only one call result, so the input must produce exactly one call:per_element=Falsealways does, andper_element=Truedoes when the source has exactly one top-level element (a single-element[[]]source is how the zero-argument constructorp2 = Playlist()is reached). Zero calls (an emptyper_elementsource) or more than one call are rejected withUnsupportedCallShapeError, as are languages whose call form is not an expression (call_returns_expression=False).
Note
When composing the output of this function with
literalize()— for example, declaring a variable withliteralize()and then referencing it via a ref marker in the call — the two halves each computepreambleandbody_preambleindependently from the data they see. Concatenating the results into a single file can produce duplicate import lines or duplicate type declarations, which strict compilers (Haskell, D, …) reject and a linter (ruff,pylint, …) flags. Pass the ref values through bound_refs (withwrap_in_file=True) instead and this function renders the declarations and the calls into one coherent file with a single reconciled preamble. The “Composing declarations and calls” section of Rendering function calls shows a worked example.
Result type¶
- class literalizer.LiteralizeResult(declaration_code: str, preamble: tuple[str, ...], body_preamble: tuple[str, ...], pre_declaration_comments: tuple[str, ...] = (), types_present: frozenset[type] = frozenset({}), contains_standalone_comments: bool = False, source_data: Value = None, sections: tuple[FileSection, ...] = ())¶
Result of converting data to a native language literal.
- property bare_code: str¶
The literal text without
body_preambleprepended.Identical to
codewhenbody_preambleis empty.pre_declaration_commentsare preserved.
- body_preamble: tuple[str, ...]¶
Type-definition lines (e.g. F#’s
type Val = …, Haskell’sdata Val = …and typeclass instances) that are prepended tocode. Empty when none are needed.Use
bare_codeto obtain the literal text without these lines.
- property code: str¶
The formatted literal text.
When a language defines
scalar_body_preambleentries (e.g. Haskell typeclass instances), those lines are prepended to the code so they appear in the correct structural position.
- contains_standalone_comments: bool = False¶
Whether the rendered source carried standalone comments (lines whose only content is a comment, distinct from inline trailing comments). Set when
literalize_callparses YAML input that contains top-level before-element or trailing comments. Callers that wrap the result viaLanguage.wrap_calls_with_declarations()can consult this together withLanguage.supports_standalone_comments_in_wrapped_callsto decide whether wrapping is safe.
- declaration_code: str¶
The variable declaration or assignment text, without any
body_preambleorpre_declaration_commentslines.Use
codefor the full formatted text including all prefix lines.
- pre_declaration_comments: tuple[str, ...] = ()¶
Already-formatted comment lines that appear between
body_preambleand the variable declaration/assignment incode. These come from scalar before-comments when the language does not support them inline.Included in
bare_codebut excluded fromdeclaration_code.
- preamble: tuple[str, ...]¶
Lines (imports, package declarations, etc.) that must precede the generated code. Empty when none are needed.
- sections: tuple[FileSection, ...] = ()¶
For multi-section languages, the rendered output split into its file regions; empty for the single-section common case.
A few languages cannot express a value as one drop-in fragment: their output spans more than one region of a source file that a wrapping template must place separately. COBOL under
json_type=CJSONis the current example, emitting aWORKING-STORAGEregion of declarations and aPROCEDUREregion of statements.Only populated when
wrap_in_file=False(withwrap_in_file=Truethe language has already composed the regions into a complete file). When non-empty, compose theseFileSectionregions into your own template;code/declaration_codethen hold an opaque marker-bracketed payload (the form the language’s wrappers consume), not usable source. Empty for almost every language; usecodethen.
- source_data: Value = None¶
The parsed source value the literal was rendered from. Most callers do not need it. Callers that combine multiple
literalizeresults and re-invokeLanguage.compute_body_preambleto derive a single body preamble surface this so the second call can inspect the actual values (e.g. datetime microsecond precision) rather than a placeholder.
- types_present: frozenset[type] = frozenset({})¶
The set of Python types observed in the source data (e.g.
int,str,list,dict). Callers that combine multipleliteralizeresults (for example, a test harness that pairs$refdeclarations with a downstream call) can union these and re-invokeLanguage.compute_body_preambleto derive a single body preamble that covers every type referenced across the combined output.
- class literalizer.FileSection(*, name: str, content: str)¶
One named region of a multi-section language’s rendered output.
Most languages render a value as a single fragment that a caller can drop straight into a program template (the way the C, C++, Haskell and Zig round-trip helpers do). A few cannot: their output spans more than one region of a source file that a wrapping template must place separately. COBOL under
json_type=CJSONis the current example – it produces WORKING-STORAGE declarations and PROCEDURE DIVISION statements that live in different divisions.For such languages
sectionsexposes the regions as a tuple of these objects, so a caller can compose each one into the right place in its own template without parsing any language-internal marker. Single-section languages leave that attribute empty.- content: str¶
The region’s text, with no marker lines and no enclosing program boilerplate.
- name: str¶
A stable label identifying the region within its language (for COBOL
json_type=CJSON,"WORKING-STORAGE"or"PROCEDURE").
Variable forms¶
The bound_refs argument to literalize() and literalize_call() describes each referenced name as one of these forms.
- class literalizer.NewVariable(name: str, modifiers: frozenset[Enum] = frozenset({}))¶
Wrap output in a new variable declaration.
- modifiers: frozenset[Enum] = frozenset({})¶
Declaration modifiers to apply. Each language exposes its own modifier enum as
Language.Modifiers(e.g.Java.Modifiers.FINAL,CSharp.Modifiers.READONLY,Cpp.Modifiers.STATIC). Values that are not members of the target language’sModifiersenum are silently ignored.
- name: str¶
- class literalizer.ExistingVariable(name: str)¶
Wrap output in an assignment to an existing variable.
- name: str¶
- class literalizer.BothVariableForms(name: str, modifiers: frozenset[Enum] = frozenset({}))¶
Produce both a declaration and an assignment, combined.
Requires
wrap_in_file=Trueonliteralize().- modifiers: frozenset[Enum] = frozenset({})¶
Declaration modifiers applied to the declaration half. See
NewVariable.modifiers.
- name: str¶
- literalizer.VariableForm = literalizer._literalize.NewVariable | literalizer._literalize.ExistingVariable | literalizer._literalize.BothVariableForms¶
Represent a PEP 604 union type
E.g. for int | str
- class literalizer.ModifierCombination(name: str, modifiers: frozenset[Enum])¶
A named combination of declaration modifiers for a language.
Languages that support declaration modifiers (e.g. Java
public static final, C#public static readonly, C++static const) expose their canonical multi-modifier combinations viaLanguageCls.modifier_combinations.- modifiers: frozenset[Enum]¶
The set of modifier enum members that make up this combination.
- name: str¶
Identifier for this combination, used in generated code.
Identifier cases¶
- class literalizer.IdentifierCase(*values)¶
A naming convention for a single identifier.
Passed to
literalize_call()viaref_caseto convert{"$ref": "name"}markers to the target language’s idiomatic case at render time. EachLanguageexposes the subset it understands via its nestedIdentifierCasesenum.- CAMEL = 'camel'¶
camelCase— e.g.userObj.
- KEBAB = 'kebab'¶
kebab-case— e.g.user-obj.
- PASCAL = 'pascal'¶
PascalCase— e.g.UserObj.
- SNAKE = 'snake'¶
snake_case— e.g.user_obj.
- UPPER_SNAKE = 'upper_snake'¶
UPPER_SNAKE_CASE— e.g.USER_OBJ.
- convert(*, name: str) str¶
Return name converted to this case.
Normalizes any input convention to
snake_casefirst so the conversion is deterministic even when the source identifier does not follow the recommendedsnake_caseauthoring convention. Acronyms are lost in normalization (HTTPRequestbecomeshttp_requestand thenHttpRequest), so passingsnake_caseinput when exact-round-trip matters is recommended.
- literalizer.ALL_REF_CASES = frozenset({IdentifierCase.CAMEL, IdentifierCase.KEBAB, IdentifierCase.PASCAL, IdentifierCase.SNAKE, IdentifierCase.UPPER_SNAKE})¶
Build an immutable unordered collection of unique elements.
- literalizer.NON_KEBAB_REF_CASES = frozenset({IdentifierCase.CAMEL, IdentifierCase.PASCAL, IdentifierCase.SNAKE, IdentifierCase.UPPER_SNAKE})¶
Build an immutable unordered collection of unique elements.
Function calls¶
- class literalizer.CallContext(call: str, index: int, row: Sequence[Value], zipped: str | None)¶
Per-row context passed to a
literalize_call()call_transform.A
call_transformis invoked once per generated call ascall_transform(context)and returns the transformed call string. The context carries the call’s positional identity so a transform can pair it with data from a parallel source (seeliteralize_call()’szip_source).- call: str¶
The rendered language-native call expression (e.g.
catalog.lookup("Dune", 1965)).
- index: int¶
Zero-based position of this call among the generated calls.
- row: Sequence[Value]¶
The input values for this row, in source order. For
per_element=Truethis is the top-level element at positionindex, as its argument values; forper_element=Falseit is the whole parsed value wrapped in a single-element sequence.
- zipped: str | None¶
The
zip_sourceelement paired with this call, rendered as a language-native literal, orNonewhen nozip_sourcewas supplied.
A language renders a call using one of these call styles.
- literalizer.CallStyle = literalizer._language.PositionalCallStyle | literalizer._language.KeywordCallStyle | literalizer._language.ObjectCallStyle | literalizer._language.PostfixCallStyle | literalizer._language.PrefixCallStyle | literalizer._language.CommandCallStyle¶
Represent a PEP 604 union type
E.g. for int | str
- class literalizer.PositionalCallStyle(arg_separator: str, parenthesize_each_arg: bool)¶
Positional arguments only:
func(value1, value2).- arg_separator: str¶
- parenthesize_each_arg: bool¶
- class literalizer.KeywordCallStyle(separator: str)¶
Named arguments:
func(name=value).separator is the string placed between the parameter name and its value (e.g.
"="for Python,": "for Ruby).- separator: str¶
- class literalizer.ObjectCallStyle(separator: str)¶
Arguments wrapped in an object literal:
func({ name: value }).separator is the string placed between the parameter name and its value inside the object literal (e.g.
": "for JavaScript).- separator: str¶
- class literalizer.PrefixCallStyle(arg_separator: str, keyword_prefix: str)¶
S-expression-style calls:
(func value1 value2).Used by Lisp-family languages (Racket, Scheme, Common Lisp, Clojure) where the function and its arguments are wrapped together in one pair of parentheses. arg_separator is the string between arguments (typically a single space).
Arguments are emitted as
{keyword_prefix}{name}{arg_separator}{value}pairs (e.g. Racket’s#:user_id "u").- arg_separator: str¶
- keyword_prefix: str¶
- class literalizer.PostfixCallStyle(arg_separator: str)¶
Postfix (stack) calls:
value1 value2 func.Used by stack-based languages like Forth where arguments are pushed onto the stack before the word is invoked. arg_separator is the string placed between arguments.
- arg_separator: str¶
- class literalizer.CommandCallStyle(arg_separator: str)¶
Shell-command-style calls:
func value1 value2.Used by shell languages (Bash, POSIX sh) and Tcl where the function name is followed by space-separated positional arguments with no surrounding parentheses. arg_separator is the string between the target and each argument (typically a single space).
call_transformis not supported for this style (seeliteralize_call()).- arg_separator: str¶
- class literalizer.StubReturn(*values)¶
Whether a generated call stub returns a value or nothing.
Passed to
Language.format_call_stubandLanguage.format_call_preamble_stubto control the return type of the no-op target-function stub emitted when a call is wrapped in a self-contained file.- VALUE = 'value'¶
The call result is consumed (passed to a
call_transformor bound to a variable), so the stub returns a value.
- VOID = 'void'¶
The call result is discarded, so the stub returns nothing.
Input formats¶
Exceptions¶
Exceptions raised by literalizer.
- exception literalizer.exceptions.CallArgNotSupportedError(*, language_name: str, reason: str)¶
Raised when a call argument value cannot be expressed as a positional argument in the target language’s call syntax.
Used by languages whose call syntax does not accept compound literals as arguments, e.g. Bash, where
cmd (1 2 3)parses as a nested(...)child-process invocation rather than an inline array value.To resolve, bind the value to a name first, or target a language that accepts the argument inline.
- exception literalizer.exceptions.CallsNotSupportedByLanguageError(*, language_name: str)¶
Raised when the target language itself has no function call syntax (e.g. pure data/markup formats like YAML, TOML, JSON5, Norg).
To resolve, use
literalize()instead, or target a programming language.
- exception literalizer.exceptions.CallsNotSupportedByToolError(*, language_name: str)¶
Raised when literalizer has not yet implemented function call rendering for the target language, even though the language itself has function call syntax.
To resolve, target a language whose call rendering is implemented.
- exception literalizer.exceptions.CommentSourceLengthMismatchError(*, call_count: int, comment_count: int)¶
Raised when
literalize_callis given acomment_sourcewhose entry count differs from the number of generated calls.Each comment is paired positionally with one call, so the two sequences must be the same length.
To resolve, provide one comment per generated call.
- exception literalizer.exceptions.CommentSourceMultilineError(*, index: int)¶
Raised when a
comment_sourceentry contains a newline.A trailing comment is emitted on the statement’s last line; a newline would push the remainder onto a line with no comment leader and, in languages whose line comment runs to end of line, produce invalid source. Comments must be single-line.
To resolve, remove the newline, keeping each comment on one line.
- exception literalizer.exceptions.DottedCallTargetNotSupportedError(*, language_name: str, target_function: str)¶
Raised when
literalize_callis given a dottedtarget_functionbut the target language does not support dotted call expressions.To resolve, use a target name without dots, or target a language with dotted calls.
- exception literalizer.exceptions.HeterogeneousCollectionError¶
Base class for errors raised when data is incompatible with the target language’s collection-shape constraints.
To resolve, pick a non-default
heterogeneous_strategy(see Heterogeneous strategies) or render the value through ajson_type(see JSON value types); catch this base class to skip any heterogeneous input a strict-typed language cannot hold.
- exception literalizer.exceptions.HeterogeneousScalarCollectionError¶
Raised when a collection contains scalars of multiple types and the target language requires homogeneous scalar collections.
For example,
[1, "two", 3.0]for a language that needs a single element type. To resolve, setheterogeneous_strategytoTAGGED_ENUM(or the language’s equivalent) to wrap each scalar, or toTUPLEfor a fixed-length array.
- exception literalizer.exceptions.HeterogeneousSetError¶
Raised when a set contains scalars of multiple types and the target language requires homogeneous set elements.
To resolve, use one scalar type, or a richer
heterogeneous_strategy.
- exception literalizer.exceptions.HeterogeneousSiblingListsError¶
Raised when sibling sub-lists contain scalars that, combined, span multiple types and the target language requires homogeneous scalar collections.
To resolve, use a
TAGGED_ENUMstrategy, or render the value through ajson_type.
- exception literalizer.exceptions.IncompatibleFormatsError¶
Raised when a combination of format options produces invalid code.
For example, Rust
CONSTandSTATICdeclaration styles require constant-expression initializers, but theVECsequence format producesvec![…]which is not a constant expression.To resolve, change one of the conflicting options so they agree.
- exception literalizer.exceptions.InvalidDictKeyError¶
Raised when a dict key cannot be represented in the target language.
This includes empty-string keys and keys containing characters that the language’s label syntax does not support (e.g. control characters in Dhall backtick-quoted labels). To resolve, remove or rename the offending key.
- exception literalizer.exceptions.InvalidRecordNameError¶
Raised when
record_struct_name_prefixor a value inrecord_shape_namesis not a valid PascalCase identifier, collides with a reserved keyword of the target language, collides withheterogeneous_value_enum_name, or duplicates another mapped struct name.To resolve, use distinct, valid PascalCase names that avoid reserved keywords.
- exception literalizer.exceptions.JSON5ParseError¶
Raised when a JSON5 string cannot be parsed.
To resolve, fix the JSON5 syntax, or choose the matching
input_format.
- exception literalizer.exceptions.JSONParseError¶
Raised when a JSON string cannot be parsed.
To resolve, fix the JSON syntax, or pass the correct
input_formatif the data is really JSON5, YAML, or TOML.
- exception literalizer.exceptions.MixedDictKeysError¶
Raised when a dict has keys spanning multiple type families and the target language requires homogeneous dict keys.
To resolve, use a single key type, or render through a
json_type.
- exception literalizer.exceptions.MixedDictShapesError¶
Raised when a list contains dicts with different key sets and the target language requires uniform record shapes (e.g. Dhall).
To resolve, make every dict share the same keys, or use a
json_type.
- exception literalizer.exceptions.MixedDictValuesError¶
Raised when a dict has values spanning multiple type families and the target language requires homogeneous dict values.
To resolve, use the
RECORDstrategy if the dict is conceptually a record, or ajson_typefor arbitrary mappings.
- exception literalizer.exceptions.MixedListValuesError¶
Raised when a list has elements spanning multiple type families and the target language requires homogeneous list elements.
To resolve, use a richer
heterogeneous_strategyor ajson_type.
- exception literalizer.exceptions.NullInCollectionError¶
Raised when a collection contains null elements and the chosen format does not support them (e.g. Java’s
List.of()).To resolve, remove the nulls, or select a collection format that admits them.
- exception literalizer.exceptions.ParameterCountMismatchError(*, expected: int, got: int)¶
Raised when the number of
parameter_namesdoes not match the number of argument values in a function-call row.To resolve, make
parameter_namesthe same length as each row of values.
- exception literalizer.exceptions.ParseError¶
Raised when input cannot be parsed into a data structure.
Base class for every input-parsing failure; catch it to handle any malformed input uniformly. To resolve, validate the source against its declared
input_format.
- exception literalizer.exceptions.PerElementNotListError¶
Raised when
per_element=Truebut the parsed data is not a list.To resolve, pass a list, or drop
per_element.
- exception literalizer.exceptions.TOMLParseError¶
Raised when a TOML string cannot be parsed.
To resolve, fix the TOML syntax, or choose the matching
input_format.
- exception literalizer.exceptions.TupleArityNotRepresentableError(*, arity: int)¶
Raised when the
TUPLEheterogeneous strategy meets a tuple-eligible heterogeneous scalar array whose length the target language has no native fixed-size tuple for.Kotlin only has
Pair(two elements) andTriple(three elements); an array of any other length cannot be represented as a typed tuple without losing the per-position types, soliteralizeraises rather than falling back to a homogeneous list (which would re-trip the heterogeneity checks the strategy exists to satisfy). SubclassesHeterogeneousCollectionErrorso the same callers that already skip a heterogeneous input the language cannot represent also skip this one.To resolve, shorten the array to a length the language supports, choose a language without the tuple-length cap (Rust, Scala), or switch to a
TAGGED_ENUMstrategy.
- exception literalizer.exceptions.UnrepresentableEmptyDictError¶
Raised when an empty dict is passed to a target language whose runtime cannot distinguish an empty mapping from an empty sequence.
Lua, PHP, and R encode both empty arrays and empty objects with the same surface syntax (
{},[], andlist()respectively), so the JSON encoders in their ecosystems serialize an empty mapping as[]. The literalizer refuses to emit a literal that cannot round-trip rather than silently lose the mapping/sequence distinction.To resolve, drop the empty mapping, or target a language that distinguishes the two.
- exception literalizer.exceptions.UnrepresentableInputError¶
Raised when an input value cannot be represented in the target language.
Used as the centralized error for shape-level rejections at the formatting boundary, e.g. when a dict carries a non-string key for a language whose surface syntax only admits string-typed keys. To resolve, adjust the data to a representable shape, or pick a language that supports it.
- exception literalizer.exceptions.UnrepresentableIntegerError¶
Raised when an integer value exceeds the range the target language can represent natively.
Used by languages whose fixed-width integer types cannot hold values outside the signed 64-bit range (e.g. Fortran default
integer, CobolPIC S9(18), PureScriptInt) when no external arbitrary-precision integer library is assumed to be available.To resolve, keep integers within range, or target a language with wider or arbitrary-precision integers.
- exception literalizer.exceptions.UnrepresentableSpecialFloatError¶
Raised when a non-finite float (
inf,-inf, ornan) is passed to a target language whose runtime cannot produce IEEE 754 special float values.Used by Gleam on the Erlang target, which has no expression that evaluates to a non-finite float.
To resolve, replace the non-finite floats with finite values, or pick another language.
- exception literalizer.exceptions.UnsupportedCallShapeError(*, language_name: str, reason: str)¶
Raised when
literalize_callis given a call shape the target language cannot represent.Distinct from
CallArgNotSupportedError(which concerns individual argument values): this covers structural properties of the call itself, e.g. zero-parameter calls in languages whose syntax requires at least one operand.To resolve, adjust the call shape, or target a language that supports it.
- exception literalizer.exceptions.UnsupportedIdentifierCaseError(*, language_name: str, case_name: str)¶
Raised when
literalizeorliteralize_callis passed aref_casethat is not in the target language’ssupported_ref_cases– i.e. one that would not produce a syntactically legal identifier in the target language.To resolve, choose a
ref_casefrom the language’ssupported_ref_cases.
- exception literalizer.exceptions.VariableNameNotSupportedError(*, language_name: str, variable_name: str)¶
Raised when
literalizeis given avariable_formbut the target language does not support variable-name wrapping.To resolve, omit
variable_formfor that language, or target one that supports it.
- exception literalizer.exceptions.WrapCombinedInFileNotSupportedError¶
Raised when a language does not support
wrap_combined_in_file.Languages that raise this error do not support
BothVariableForms;literalize()rejects that form before reachingwrap_combined_in_file, but each language implementation still raises this typed exception as a safety net.To resolve, use a single variable form, or target a language that supports the combined form.
- exception literalizer.exceptions.WrapInFileWithoutVariableNotSupportedError(*, language_name: str)¶
Raised when
literalizeis called withwrap_in_file=Trueandvariable_form=Nonefor a target language that cannot represent a bare value at file-statement scope.Most strict-typed compiled languages (Rust, C, C++, Haskell, Swift, OCaml, Ada, D, Dart, C#, Elm, Mojo, Nim, Objective-C, Odin, SML, V, Zig, etc.) require every top-level item to be a declaration; a bare expression at file scope is a syntax error. Such languages opt out of the shape by setting
supports_no_variable_wrap_in_filetoFalse, andliteralizerejects the combination at the boundary instead of silently emitting invalid code.To resolve, supply a
variable_formso the value becomes a top-level declaration.
- exception literalizer.exceptions.YAMLParseError¶
Raised when a YAML string cannot be parsed.
To resolve, fix the YAML syntax, or choose the matching
input_format.
- exception literalizer.exceptions.ZipSourceWithoutInputFormatError¶
Raised when
literalize_callis given azip_sourcebut nozip_input_formatdescribing how to parse it.The companion source can only be parsed once its serialization format is known, so the two arguments must be supplied together.
To resolve, pass
zip_input_formatalongsidezip_source.
- exception literalizer.exceptions.ZipValuesLengthMismatchError(*, call_count: int, zip_count: int)¶
Raised when
literalize_callis given azip_sourcewhose parsed top-level elements differ in number from the generated calls.To resolve, make
zip_sourcehold one element per generated call.
- exception literalizer.exceptions.ZipValuesWithoutCallTransformError¶
Raised when
literalize_callis given azip_sourcebut nocall_transformto consume the paired values.The paired values are only reachable through
zipped, so supplying them without a transform would silently discard them.To resolve, supply a
call_transformthat readszipped, or dropzip_source.