Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-config

Source of release 0.5.1

0.5.1 / src / toml.luc

## A scalar TOML reader for application configuration: tables, bare keys, quoted
## UTF-8 strings, decimal numbers and booleans. Unsupported structures are errors,
## not ignored input. A section may be declared dynamic so it accepts arbitrary
## keys (for example a keymap), while every other key must be a known setting.
## Parsing and schema validation finish before configuration is applied.
from luce_std import math

## Configuration that is malformed or does not match the declared schema.
pub let invalid: ErrorCode = ErrorCode.package(300)

pub class Value:
    pub let text: str
    pub let quoted: bool
    pub let line: int

    pub func init(self, text: str, quoted: bool, line: int):
        self.text = text
        self.quoted = quoted
        self.line = line

    pub func string(self) -> str!:
        if not self.quoted:
            error(invalid, f"Line {self.line}: expected a quoted string")
        return self.text

    pub func boolean(self) -> bool!:
        if self.quoted or (self.text != "true" and self.text != "false"):
            error(invalid, f"Line {self.line}: expected true or false")
        return self.text == "true"

    pub func number(self, minimum: float, maximum: float) -> float!:
        if self.quoted:
            error(invalid, f"Line {self.line}: expected a number")
        let parsed = float(decimal(self.text, self.line)) catch failure:
            error(invalid, f"Line {self.line}: expected a decimal number")
        if not math.is_finite(parsed) or parsed < minimum or parsed > maximum:
            error(invalid, f"Line {self.line}: value must be in {minimum}..{maximum}")
        return parsed

pub class Table:
    pub let values: map[str, Value]
    let sections: list[str]

    pub func init(self, source: str) -> unit!:
        var values: map[str, Value] = {}
        var tables: list[str] = []
        var section = ""
        var number = 0
        for original in source.lines():
            number += 1
            let line = uncomment(original, number).trim()
            if line == "":
                continue
            if line.starts_with("["):
                if not line.ends_with("]"):
                    error(invalid, f"Line {number}: expected a table header")
                section = line[1..<line.length - 1].trim()
                check_key(section, number)
                if section in tables:
                    error(invalid, f"Line {number}: duplicate table {section}")
                tables.append(section)
                continue
            let equal = line.index_of("=") else error(invalid, f"Line {number}: expected key = value")
            let key = line[..<equal].trim()
            check_key(key, number)
            let name = section + "." + key if section != "" else key
            if name in values:
                error(invalid, f"Line {number}: duplicate key {name}")
            let raw = line[equal + 1..].trim()
            if raw == "":
                error(invalid, f"Line {number}: missing value")
            let quoted = raw.starts_with("\"") or raw.starts_with("'")
            values[name] = Value(decode(raw, number) if quoted else raw, quoted, number)
        self.values = values
        self.sections = tables

    ## Reject unknown tables and settings against a fixed schema.
    pub func check_keys(self, supported: list[str]) -> unit!:
        var open: list[str] = []
        self.check_within(supported, open)

    ## Like check_keys, but sections named in `dynamic` accept any bare key, so a
    ## keymap or other open-ended table needs no fixed schema.
    pub func check_within(self, supported: list[str], dynamic: list[str]) -> unit!:
        for section in self.sections:
            var found = section in dynamic
            for key in supported:
                if key.starts_with(section + "."): found = true
            if not found:
                error(invalid, "Unknown configuration table " + section)
        for (key, value) in self.values:
            if key in supported:
                continue
            var allowed = false
            for section in dynamic:
                if key.starts_with(section + "."): allowed = true
            if not allowed:
                error(invalid, f"Line {value.line}: unknown setting {key}")

    ## The bare keys present under `section`, for a dynamic table read at runtime.
    pub func keys(self, section: str) -> list[str]:
        var result: list[str] = []
        let prefix = section + "."
        for (name, value) in self.values:
            if name.starts_with(prefix):
                result.append(name[prefix.length..])
        return result

    pub func string(self, key: str, fallback: str) -> str!:
        let value = self.values[key] else return fallback
        return value.string()

    pub func boolean(self, key: str, fallback: bool) -> bool!:
        let value = self.values[key] else return fallback
        return value.boolean()

    pub func number(self, key: str, fallback: float, minimum: float, maximum: float) -> float!:
        let value = self.values[key] else return fallback
        return value.number(minimum, maximum)

func check_key(key: str, line: int) -> unit!:
    if key == "":
        error(invalid, f"Line {line}: empty key or table")
    for character in key:
        if not ((character >= "a" and character <= "z") or (character >= "A" and character <= "Z") or (character >= "0" and character <= "9") or character == "_" or character == "-"):
            error(invalid, f"Line {line}: use a bare key or table name")

func uncomment(source: str, line: int) -> str!:
    var quote = ""
    var escaped = false
    var offset = 0
    for character in source:
        if character < " " and character != "\t":
            error(invalid, f"Line {line}: unexpected control character")
        if escaped:
            escaped = false
        elif quote == "\"" and character == "\\":
            escaped = true
        elif quote != "":
            if character == quote:
                quote = ""
        elif character == "#":
            return source[..<offset]
        elif character == "\"" or character == "'":
            quote = character
        offset += 1
    if quote != "":
        error(invalid, f"Line {line}: unterminated string; use a single-line value")
    return source

func decode(raw: str, line: int) -> str!:
    let quote = raw[..<1]
    if raw.length < 2 or not raw.ends_with(quote):
        error(invalid, f"Line {line}: trailing text after a string")
    var result = ""
    var escaped = false
    for character in raw[1..<raw.length - 1]:
        if escaped:
            if character == "n":
                result += "\n"
            elif character == "r":
                result += "\r"
            elif character == "t":
                result += "\t"
            elif character == "\\" or character == "\"":
                result += character
            else:
                error(invalid, f"Line {line}: unsupported escape; write Unicode directly")
            escaped = false
        elif character == "\\" and quote == "\"":
            escaped = true
        elif character == quote:
            error(invalid, f"Line {line}: unexpected quote in a single-line string")
        else:
            result += character
    if escaped:
        error(invalid, f"Line {line}: unfinished string escape")
    return result

## Validate TOML decimal syntax before the language's general number conversion.
## Underscores separate digits; a decimal integer part cannot have leading zeroes.
func decimal(source: str, line: int) -> str!:
    var previous = ""
    var underscore = false
    for character in source:
        if character == "_":
            if previous < "0" or previous > "9":
                error(invalid, f"Line {line}: underscores must separate digits")
            underscore = true
        else:
            if underscore and (character < "0" or character > "9"):
                error(invalid, f"Line {line}: underscores must separate digits")
            underscore = false
        previous = character
    if underscore:
        error(invalid, f"Line {line}: trailing numeric underscore")
    let normalized = source.replace("_", "").lower()
    let exponent = normalized.split("e")
    if exponent.length > 2:
        error(invalid, f"Line {line}: invalid numeric exponent")
    let parts = unsigned(exponent[0]).split(".")
    if parts.length > 2 or parts[0].length > 1 and parts[0].starts_with("0"):
        error(invalid, f"Line {line}: invalid decimal number")
    for part in parts: digits(part, line)
    if exponent.length == 2: digits(unsigned(exponent[1]), line)
    return normalized

func unsigned(text: str) -> str:
    return text[1..] if text.starts_with("+") or text.starts_with("-") else text

func digits(text: str, line: int) -> unit!:
    if text == "":
        error(invalid, f"Line {line}: expected decimal digits")
    for character in text:
        if character < "0" or character > "9":
            error(invalid, f"Line {line}: expected decimal digits")

test "reads strings, numbers and booleans with fallbacks":
    let table = Table("[editor]\nfont = \"Mono\"\nsize = 14\nwrap = true\n")
    assert(table.string("editor.font", "") == "Mono")
    assert(table.number("editor.size", 0.0, 8.0, 40.0) == 14.0)
    assert(table.boolean("editor.wrap", false) == true)
    assert(table.boolean("editor.missing", true) == true)
    assert(table.string("editor.absent", "fallback") == "fallback")

test "rejects unknown tables and settings":
    var refused = false
    Table("[nope]\nx = 1\n").check_keys(["editor.font"]) catch failure:
        refused = true
    assert(refused)
    refused = false
    Table("[editor]\nzoom = 2\n").check_keys(["editor.font"]) catch failure:
        refused = true
    assert(refused)

test "accepts arbitrary keys inside a dynamic section":
    let table = Table("[shortcuts]\nsave = \"cmd+s\"\nquit = \"cmd+q\"\n")
    table.check_within([], ["shortcuts"])
    let bound = table.keys("shortcuts")
    assert(bound.length == 2)
    assert(table.string("shortcuts.save", "") == "cmd+s")