# `SefazNfe.Layout.Generator`
[🔗](https://github.com/devaction-labs/sefaz_nfe/blob/v0.5.0/lib/sefaz_nfe/layout/generator.ex#L1)

Compiles the official XSD package (a PL) into the layout tree that
`SefazNfe.Layout` loads (AD-024). Driven by `mix sefaz.gen_layout`.

## Why a subset compiler

`:xmerl_xsd` cannot compile PL_010, and the builder needs the *shape* of the
schema, not a validator: element order, occurrence, choices, attributes and
the facets of every leaf. This module reads exactly the XSD idioms the NF-e
package uses and **raises** on any other, so a Nota Tecnica that introduces
a new construct fails generation instead of producing a layout that silently
drops it.

## XSD idioms and how they are handled

  * `xs:include` / `xs:import` are followed (the file name must be a plain
    sibling file). Every file reached is hashed. Definitions are indexed only
    for files in the entry file's target namespace; an imported foreign
    namespace (`ds`) is hashed but not compiled.
  * Global `xs:element` + named `xs:complexType` / `xs:simpleType`, anonymous
    inline `complexType` / `simpleType`, and named types referenced by
    `type=` are all expanded in place. A named complex type is recorded as
    `type_name` on the element; a named simple type as `name` on the leaf.
  * `xs:sequence` and `xs:choice`, nested in any combination
    (choice-in-sequence, sequence-in-choice), keep their own `minOccurs` /
    `maxOccurs` and their children order.
  * `minOccurs` defaults to 1, `maxOccurs` to 1; `"unbounded"` becomes
    `:unbounded`.
  * `xs:attribute` (inline or by `type=`), with `use` and `fixed`.
  * `xs:restriction` chains over `xs:string`, `xs:ID`, `xs:base64Binary`,
    `xs:gYearMonth` and the other built-ins in `@builtins`, resolved down to
    a single flat facet set: `pattern`, `enumeration`, `length`,
    `minLength`, `maxLength`, `totalDigits`, `fractionDigits`, `whiteSpace`,
    `minInclusive`, `maxInclusive`, `minExclusive`, `maxExclusive`.
    Several `xs:pattern` in one restriction are OR-ed into one
    `(a)|(b)` string. A derived type that adds a pattern to a base that
    already has one is an AND: `pattern` holds the most derived step and
    `inherited_patterns` the earlier ones, all of which must match.
  * `xs:element ref=` to a foreign namespace (`ds:Signature`) becomes an
    opaque `%{kind: :foreign, ...}` node.
  * Ignored on purpose (they constrain documents, not the shape the builder
    walks): `xs:annotation` and the identity constraints `xs:unique`,
    `xs:key`, `xs:keyref`. The only ones in PL_010 are uniqueness checks on
    `gPgto/@nPag`, `gPgto/@idTransacao` and `@dia`.
  * An `xs:element` with neither `type=` nor an inline type is `xs:anyType`
    (CT-e `gCompraGov/refDFeAnt`, which only carries documentation). It is
    compiled to a leaf with `base: :any_type` and no facets: free text.
  * `xs:any` (the CT-e / MDF-e `infModal`, whose content is the modal XML)
    becomes `%{kind: :any, namespace: "##any", process_contents: :skip,
    min: n, max: n}` inside its sequence or choice. It has no key and no
    children: the host supplies the foreign content and the modal's own
    layout validates it. `namespace` defaults to `"##any"` and
    `process_contents` to `:strict`, as in XSD; the value is read, not
    interpreted. An `any` is not an element: `SefazNfe.Layout.elements/1`
    skips it and it takes part in no key collision.
  * Not supported, raised: `xs:group`, `xs:attributeGroup`,
    `xs:extension`, `xs:simpleContent`, `xs:complexContent`, `xs:list`,
    `xs:union`, `mixed`, and recursive types.

## Keys

`snake_case/1` turns an XSD name into the key hosts write in their input
map. The algorithm:

  1. `NFe`, `DFe` and `CTe` are treated as one acronym (`NFE`, `DFE`, `CTE`).
  2. The name is cut into runs of capitals, of lowercase letters and of
     digits; digits stay attached to the run before them.
  3. A run of capitals is always split on the known acronyms (`@acronyms`)
     when it decomposes completely into them; otherwise it stays one token.
     Digits stay attached to the token before them. When lowercase follows
     the run, its last capital belongs to the next word (`ICMSUFDest` is
     `ICMSUF` + `Dest`) unless the whole run is itself made of acronyms
     (`ISSQNtot` is `ISSQN` + `tot`).
  4. `@token_overrides` (whole tokens a dictionary split gets wrong, such as
     `ISUF`, the Inscricao SUFRAMA) are applied before everything else.
  5. Words are lowercased and joined with `_`.

| XSD name        | key               |
|-----------------|-------------------|
| `vICMSUFDest`   | `v_icms_uf_dest`  |
| `CNPJ`          | `cnpj`            |
| `ICMS00`        | `icms00`          |
| `ICMSSN102`     | `icms_sn102`      |
| `ICMSST`        | `icms_st`         |
| `infNFeSupl`    | `inf_nfe_supl`    |
| `xPed`          | `x_ped`           |
| `nItemPed`      | `n_item_ped`      |
| `IBSCBS`        | `ibs_cbs`         |
| `gIBSCBS`       | `g_ibs_cbs`       |
| `IBSCBSTot`     | `ibs_cbs_tot`     |
| `vIBSUF`        | `v_ibs_uf`        |
| `vBCSTDest`     | `v_bc_st_dest`    |
| `ISSQNtot`      | `issqn_tot`       |
| `CNPJBasePSP`   | `cnpj_base_psp`   |
| `ISUF`          | `isuf`            |
| `ISUFEmit`      | `isuf_emit`       |

Two sibling elements/attributes of the same element (looking through
`sequence` and `choice`) whose *different* XSD names map to one key abort
generation. Keys are atoms created at generation time from a trusted local XSD, never
from network data; the layout stores them as atoms.

# `collisions`

```elixir
@spec collisions([String.t()]) :: :ok | {:error, [{String.t(), [String.t()]}]}
```

Detects sibling key collisions in `names` (XSD names under one element;
attributes are written `"@name"`). Returns `:ok` or
`{:error, [{key_string, [names]}]}`.

# `encode`

```elixir
@spec encode(map()) :: binary()
```

Serializes a layout deterministically, so regeneration is byte-stable.

# `generate`

```elixir
@spec generate(Path.t(), keyword()) :: map()
```

Compiles the package in `dir`.

Options: `:entry` (the XSD that includes the rest, default
`nfe_v4.00.xsd`), `:root` (the complex type to compile, default
`TNFe`; the one global element of that type is the layout root)
and `:element` (the name of a global element to compile instead, for a
modal whose root has an anonymous type; the layout then records
`root_element` and a `nil` `root_type`). Raises on any unsupported idiom.

# `snake_case`

```elixir
@spec snake_case(String.t()) :: String.t()
```

Deterministic snake_case key of an XSD name (see the moduledoc).

# `version`

```elixir
@spec version() :: pos_integer()
```

The generator version recorded in every layout.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
