Hex.pm Docs CI License

PCN (Portable Chess Notation) implementation for Elixir.

Overview

This library implements the PCN Specification v1.0.0.

PCN records a complete Match of an abstract strategy board game built on the Sashité Game Protocol: metadata, links, Players, time control, the initial Position in FEEN, the Plies in PMN with their annotations and variations, and the result. A document is serialized in JSON or in TOML.

The library validates PCN documents and keeps them as they are decoded: maps with string keys, custom properties included. It reads and writes the JSON serialization with Elixir's built-in JSON module. For TOML, decode the document with a TOML library of your choice and pass the map to Sashite.Pcn.validate/1.

Implementation Constraints

ConstraintValueRationale
Max JSON document size1 MiBBounds decoding time and memory
Max integer literal20 charactersEvery 64-bit integer; longer literals cost more than linear time to convert
Max variation depth64Bounds recursion on analysis trees

The specification asks implementations to bound document size, string lengths and the nesting of variations (§17). Positions and moves are validated by sashite_feen and sashite_pmn, with their own limits.

Installation

# In your mix.exs
def deps do
  [
    {:sashite_pcn, "~> 1.0"}
  ]
end

The library requires Elixir 1.18 or later, for its built-in JSON module.

Dependencies

{:sashite_feen, "~> 2.1"}  # Field Expression Encoding Notation
{:sashite_pmn, "~> 1.3"}   # Portable Move Notation

Usage

Parsing JSON

{:ok, match} =
  Sashite.Pcn.parse("""
  {
    "meta": {"event": "Example", "started_at": "2025-06-17T14:00:00Z"},
    "sides": {
      "first": {"variant": "Chess", "style": "Western", "name": "Alice", "rating": 1500},
      "second": {"variant": "Chess", "name": "Bob", "rating": 1450}
    },
    "setup": {"feen": "-rnbqk^bn-r/pppppppp/8/8/8/8/PPPPPPPP/-RNBQK^BN-R / W/w"},
    "plies": [
      {"pmn": "e2-e4", "elapsed_ms": 4200},
      {"pmn": "e7-e5"},
      {"pmn": "f1-c4"},
      {"pmn": "b8-c6"},
      {"pmn": "d1-h5"},
      {"pmn": "g8-f6", "assessment": "blunder", "comment": "Overlooks the mate threat"},
      {"pmn": "h5+f7", "check": true, "mate": true}
    ],
    "outcome": {"result": "1-0"}
  }
  """)

match["sides"]["first"]["name"]  # => "Alice"
length(match["plies"])           # => 7
match["outcome"]["result"]       # => "1-0"

# Invalid input returns an error tuple
{:error, :invalid_pmn} =
  Sashite.Pcn.parse(~s({"setup": {"feen": "1 / W/w"}, "plies": [{"pmn": "e7-e8/Q"}]}))

# Bang version (raises ArgumentError on invalid input)
match = Sashite.Pcn.parse!(json)

Validating a TOML document

# With any TOML decoder that returns maps with string keys, e.g. {:toml, "~> 0.7"}
{:ok, decoded} = Toml.decode(toml)
{:ok, match} = Sashite.Pcn.validate(decoded)

A TOML native datetime for meta.started_at may be decoded as a DateTime or a NaiveDateTime; both are accepted.

Writing JSON

Sashite.Pcn.dump(%{
  "setup" => %{"feen" => "1 / W/w"},
  "meta" => %{"started_at" => ~U[2025-06-17 14:00:00Z]}
})
# => ~s({"meta":{"started_at":"2025-06-17T14:00:00Z"},"setup":{"feen":"1 / W/w"}})

The encoded document is read back with parse/1 before it is returned, so the output is always a document that parse/1 accepts: valid PCN, within the 1 MiB limit. The output is compact JSON; the order of the properties of an object carries no meaning and is not specified.

Validation

Sashite.Pcn.valid?(json)     # => true or false, never raises
Sashite.Pcn.valid?(decoded)  # decoded documents too

Working with Positions and Moves

The document keeps FEEN and PMN strings as they are. Decode them with their libraries when needed:

position = Sashite.Feen.parse!(match["setup"]["feen"])
moves = Enum.map(match["plies"], &Sashite.Pmn.parse!(&1["pmn"]))

API Reference

@spec Sashite.Pcn.parse(String.t()) :: {:ok, map()} | {:error, atom()}
@spec Sashite.Pcn.parse!(String.t()) :: map()
@spec Sashite.Pcn.validate(term()) :: {:ok, map()} | {:error, atom()}
@spec Sashite.Pcn.valid?(term()) :: boolean()
@spec Sashite.Pcn.dump(map()) :: String.t()
@spec Sashite.Pcn.max_string_length() :: pos_integer()    # 1_048_576
@spec Sashite.Pcn.max_variation_depth() :: pos_integer()  # 64

Errors

Reasons are atoms naming the first check that failed. The sections are checked in this order: setup, meta, links, periods, sides, plies, outcome.

JSON text (parse/1 only):

AtomCause
:not_a_stringThe input is not a binary
:input_too_longThe input exceeds 1 MiB
:invalid_jsonThe input is not a JSON text (RFC 8259), or holds a number beyond the range of a float
:duplicate_keyAn object has two members with the same name
:integer_too_largeAn integer literal has more than 20 characters

Document:

AtomCause
:not_an_objectThe document is not a map
:missing_setupsetup is absent
:invalid_setupsetup is not an object of at least one property, all strings
:invalid_feensetup.feen or a Ply's feen is not a valid FEEN string
:invalid_metameta is not an object, or one of its string properties is not a string
:invalid_started_atmeta.started_at is not an ISO 8601 datetime
:invalid_linkslinks is not an array of objects with non-empty rel and url strings
:invalid_periodsperiods is not an array of Periods (duration_ms ≥ 0, increment_ms ≥ 0, plies ≥ 1, all integers)
:invalid_sidessides or a Side is not an object, or a name is not a string
:invalid_variantA variant does not match ^[A-Z][A-Za-z]*[0-9]*$
:invalid_styleA style does not match ^[A-Z][A-Za-z]*$
:invalid_ratingA rating is not an integer ≥ 0
:invalid_pliesplies or variations is not an array, a Ply or a variation is not an object, a variation has no plies array, or a comment, name, check, mate or draw_offer has the wrong type
:invalid_pmnA pmn is not a valid PMN string
:invalid_elapsed_msAn elapsed_ms is not an integer ≥ 0
:invalid_assessmentAn assessment is not one of the six values
:variations_too_deepVariations are nested more than 64 levels
:invalid_outcomeoutcome is not an object with a result
:invalid_resultoutcome.result is not one of the five values

Semantics

  • Integers must be written as JSON integers: 1000, not 1000.0 or 1e3.
  • started_at is an ISO 8601 datetime, with T between the date and the time, with or without offset; a date alone is rejected.
  • style is checked for its syntax only. Whether it is consistent with the SIN letters of the FEEN Style–Turn field depends on the mapping between Style names and SIN letters, which is a convention of the Rule System (§9.2): an application that knows the mapping checks it itself, and the FEEN string prevails.
  • Keys are strings, as JSON and TOML decoders return them. In a decoded document passed to validate/1, a property under any other key, such as an atom, is not recognized.
  • Custom properties (§14.1) are kept and not inspected. Properties that PCN defines are checked wherever they appear, so a custom property cannot reuse a semantic name.
  • Rule System checks (§15.3: legality, accuracy of check and mate, consistency of style with the FEEN Style–Turn field, Turn alternation against the Position) need a Rule System and are left to the application.

Security

This library is designed for documents that come from untrusted clients.

  • Size first: JSON inputs over 1 MiB are rejected in O(1), before decoding.
  • Linear decoding: integer literals are limited to 20 characters, so no number costs more than linear time to convert.
  • No ambiguity: duplicate member names are rejected rather than resolved, so that every consumer reads a document the same way.
  • Bounded recursion: variations deeper than 64 levels are rejected.
  • No atoms from input: error reasons are compile-time atoms, and decoded keys stay strings.

License

Available as open source under the Apache License 2.0.