"""Read the AIM diary example: its Records, its fixed Rows and its Entries files, with every link checked and every line keeping who put it there.""" from __future__ import annotations import argparse from dataclasses import dataclass, field from datetime import date from decimal import Decimal import json from pathlib import Path import re import sys from urllib.parse import unquote ROOT = Path(__file__).resolve().parent / "aim" / "diary" ID = r"[A-Za-z0-9][A-Za-z0-9_-]*" NAME = r"[A-Za-z][A-Za-z0-9_]*" INTENT = r"[a-z][a-z0-9.]*" RECORD = rf"{INTENT}#Record:{NAME}" HEADING = re.compile(r" {0,3}(#{1,6})[ \t]+(.+?)\s*") FENCE = re.compile(r" {0,3}(`{3,}|~{3,})(.*)") FIELD = re.compile(rf"- ({NAME}):[ \t]*(.*?)\s*") NESTED_ITEM = re.compile(r"([ \t]+)-[ \t]+(.*?)\s*") REF = re.compile(rf"ref\(({INTENT})#({NAME})\.({NAME})\)") REF_LIST = re.compile(rf"list\(({INTENT})#({NAME})\)") LINK = re.compile(rf"\[(.*)\]\(aim:({RECORD})\[([^\]\s]+)\]\)") LINK_HEAD = re.compile(r"\[[^\]]*\]\(aim:[^()\s]*\)") ROW_ADDRESS = re.compile(rf"({RECORD})\[([^\]\s]+)\]") ENTRY_HEADING = re.compile(rf"({NAME}|{RECORD}): ({ID})") TRAILER_START = re.compile(r"(?:^|[ \t])— from(?=:|[ \t]*\[)") TRAILER = re.compile(r"— from(?:: (\S(?:.*\S)?)|[ \t]*\[(.+)\])") PROPOSED = re.compile(r"proposed(?: by (\S(?:.*\S)?), (\d{4}-\d{2}-\d{2}))?") NUMBER = re.compile(r"-?(?:0|[1-9][0-9]*)") class DiaryError(Exception): pass @dataclass(frozen=True) class Origin: """Who put a line there: words (`from: ...`) or an address (`from [...]`).""" text: str = "" address: str = "" proposed: bool = False def __str__(self) -> str: return f" — from [{self.address}]" if self.address else f" — from: {self.text}" @dataclass class Source: path: Path lines: list[str] @classmethod def open(cls, path: Path) -> Source: return cls(path, path.read_text(encoding="utf-8").splitlines()) def location(self, line: int) -> str: return f"{self.path}:{line + 1}" def fail(self, line: int, message: str) -> DiaryError: return DiaryError(f"{self.location(line)}: {message}") def frontmatter(self) -> tuple[dict[str, str], int]: if not self.lines or self.lines[0] != "---": raise self.fail(0, "Expected AIM frontmatter.") header = {} for index, line in enumerate(self.lines[1:], 1): if line == "---": return header, index + 1 if not line.strip() or line.lstrip().startswith("#"): continue match = re.fullmatch(r"([a-z][a-z_]*)[ \t]*:[ \t]*(.+?)\s*", line) if not match or match[1] in header: raise self.fail(index, "Expected one value per frontmatter key.") value = match[2] if value.startswith(('"', "'")): value = text_literal(self, index, value, allow_single_quotes=True) header[match[1]] = value raise self.fail(0, "Unclosed AIM frontmatter.") def sections(self, start: int, stop: int, level: int): found = [] fence = "" for index in range(start, stop): line = self.lines[index] marker = FENCE.fullmatch(line) if fence: if marker and marker[1].startswith(fence) and not marker[2].strip(): fence = "" continue if marker: fence = marker[1] continue heading = HEADING.fullmatch(line) if heading and len(heading[1]) == level: found.append((re.sub(r"[ \t]+#+$", "", heading[2]), index)) for (title, index), (_, end) in zip(found, found[1:] + [("", stop)]): yield title, index, end def nonblank(self, start: int, stop: int) -> list[int]: return [index for index in range(start, stop) if self.lines[index].strip()] @dataclass(frozen=True) class SchemaField: kind: str # string, date, integer, link, links required: bool unique: bool key: bool minimum: int | None target: tuple[str, str | None] | None = None # (Record address, field or None for the key) @dataclass(frozen=True) class Link: record: str key: str label: str line: int origin: Origin | None @dataclass(frozen=True) class Value: content: str | Decimal | Link | list[Link] line: int origin: Origin | None = None @dataclass class Row: address: str key: str source: Source line: int values: dict[str, Value] origin: Origin | None = None @dataclass class Record: address: str name: str schema: dict[str, SchemaField] line: int stated: bool = False # the rows are fixed in the model's `### Rows` listed: Source | None = None # the Record's one list file rows: dict[str, Row] = field(default_factory=dict) @property def key(self) -> str | None: keys = [name for name, schema in self.schema.items() if schema.key] return keys[0] if len(keys) == 1 else None def add(self, row: Row) -> None: if row.key in self.rows: first = self.rows[row.key] raise row.source.fail(row.line, f"Duplicate entry {row.address}. First written at {first.source.location(first.line)}.") if self.key in row.values: raise row.source.fail(row.values[self.key].line, f"The heading supplies '{self.key}'.") row.values[self.key] = Value(row.key, row.line, row.origin) for name, schema in self.schema.items(): if schema.required and name not in row.values: raise row.source.fail(row.line, f"{row.address} is missing required field '{name}'.") self.rows[row.key] = row @dataclass class Diary: intent: str records: dict[str, Record] # by Record address nodes: set[str] # addresses of the model's own headings waiting: int = 0 def record(self, name: str) -> Record: return self.records[f"{self.intent}#Record:{name}"] def rows(self): return (row for record in self.records.values() for row in record.rows.values()) def text_literal(source: Source, line: int, literal: str, *, allow_single_quotes: bool = False) -> str: if literal.startswith('"'): try: value = json.loads(literal) except json.JSONDecodeError: raise source.fail(line, "Invalid quoted text.") from None if isinstance(value, str): return value if allow_single_quotes and len(literal) >= 2 and literal[0] == literal[-1] == "'": return literal[1:-1].replace("''", "'") if literal and literal != "null" and not literal.startswith(("[", '"', "'")): return literal raise source.fail(line, "Use a bare value or put the text in double quotes.") def split_origin(source: Source, line: int, text: str) -> tuple[str, Origin | None]: """Take the one origin trailer off the end of a line. A quoted value and a link are read to their own end first, so their words are never taken for a trailer.""" head = "" if text.startswith('"'): end = 1 while end < len(text) and text[end] != '"': end += 2 if text[end] == "\\" else 1 head = text[: end + 1] elif (link := LINK_HEAD.match(text)) and LINK.fullmatch(text[: link.end()]): head = text[: link.end()] else: start = TRAILER_START.search(text) head = text[: start.start()] if start else text rest = text[len(head):].strip() if not rest: return head.rstrip(), None trailer = TRAILER.fullmatch(rest) words = trailer[1] if trailer else None if not trailer or (words and TRAILER_START.search(words)): raise source.fail(line, "Expected one origin trailer, ' — from: ' or ' — from [
]', at the end of the line.") if words is None: return head.rstrip(), Origin(address=trailer[2]) if words.startswith("proposed"): if not PROPOSED.fullmatch(words): raise source.fail(line, 'A suggestion is marked "proposed" or "proposed by , ".') return head.rstrip(), Origin(text=words, proposed=True) return head.rstrip(), Origin(text=words) def read_schema(source: Source, intent: str, heading: int, end: int) -> dict[str, SchemaField]: lines = source.nonblank(heading + 1, end) if len(lines) < 3 or source.lines[lines[0]].strip() != "```schema" or source.lines[lines[-1]].strip() != "```": raise source.fail(heading, "Expected a schema fence.") schema = {} for index in lines[1:-1]: match = re.fullmatch(rf"({NAME}):\s+(\S+)(?:\s+(.*))?", source.lines[index]) if not match or match[1] in schema: raise source.fail(index, "Malformed or repeated schema field.") name, kind, modifiers = match.groups() target = None if reference := REF.fullmatch(kind): kind, target = "link", (f"{reference[1]}#Record:{reference[2]}", reference[3]) elif reference := REF_LIST.fullmatch(kind): kind, target = "links", (f"{reference[1]}#Record:{reference[2]}", None) elif kind.startswith("list(ref("): raise source.fail(index, "A list of references is written list(#).") if kind not in {"string", "date", "integer", "link", "links"}: raise source.fail(index, f"Unsupported field type '{kind}' in the diary example.") flags = (modifiers or "").split() minimum = None for flag in flags: if flag in {"required", "optional", "unique", "key"}: continue bound = re.fullmatch(r"min\(([0-9]+)\)", flag) if not bound or kind not in {"string", "integer"} or minimum is not None: raise source.fail(index, f"Unsupported schema modifier '{flag}'.") minimum = int(bound[1]) if "key" in flags and not ("required" in flags and "unique" in flags and kind in {"string", "integer"}): raise source.fail(index, "A key is a required unique string or integer field.") schema[name] = SchemaField(kind, "required" in flags, "unique" in flags, "key" in flags, minimum, target) return schema def read_link(source: Source, line: int, literal: str, origin: Origin | None) -> Link: match = LINK.fullmatch(literal) if not match: raise source.fail(line, "Use [label](aim:#Record:[]) for a typed link.") return Link(match[2], unquote(match[3]), match[1], line, origin) def read_value(source: Source, line: int, schema: SchemaField, inline: str, nested: list[tuple[int, str]], inherited: Origin | None) -> Value: inline, own = split_origin(source, line, inline) origin = own or inherited if schema.kind == "links": if inline == "[]" and not nested: return Value([], line, origin) if inline or not nested: raise source.fail(line, "Use indented link bullets or [] for a list of references.") links = [] for index, item in nested: item, mark = split_origin(source, index, item) links.append(read_link(source, index, item, mark or origin)) return Value(links, line, origin) if nested: raise source.fail(nested[0][0], "Only a list field accepts nested bullets.") if schema.kind == "link": if schema.target[1] is not None and LINK.fullmatch(inline) is None and not inline.startswith("["): raise source.fail(line, "In an Entries file a reference to a key is written as a link.") return Value(read_link(source, line, inline, origin), line, origin) if schema.kind == "integer": if NUMBER.fullmatch(inline): return Value(Decimal(inline), line, origin) raise source.fail(line, "Expected an integer.") value = text_literal(source, line, inline) if schema.kind == "date": try: if re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", value): return Value(date.fromisoformat(value).isoformat(), line, origin) except ValueError: pass raise source.fail(line, "Expected a valid date in YYYY-MM-DD form.") return Value(value, line, origin) def read_fields(source: Source, record: Record, start: int, end: int, indent: str = "", inherited: Origin | None = None) -> dict[str, Value]: values = {} index = start while index < end: raw = source.lines[index] if not raw.strip(): index += 1 continue match = FIELD.fullmatch(raw[len(indent):]) if raw.startswith(indent) else None if not match: raise source.fail(index, "Expected a field bullet such as '- date: 2026-11-28'.") name, inline = match.groups() if name not in record.schema or name in values: raise source.fail(index, f"Unknown or repeated field '{name}' on {record.name}.") field_line = index index += 1 nested = [] while index < end: item = source.lines[index] if item.strip(): match = NESTED_ITEM.fullmatch(item[len(indent):]) if item.startswith(indent) else None if not match or len((indent + match[1]).expandtabs(4)) < len(indent) + 2: break nested.append((index, match[2])) index += 1 values[name] = read_value(source, field_line, record.schema[name], inline, nested, inherited) return values def read_stated_rows(source: Source, record: Record, heading: int, end: int) -> None: lines = source.nonblank(heading + 1, end) if lines and re.match(r"- key:", source.lines[lines[0]]): raise source.fail(lines[0], "The key is declared in the Schema with the 'key' modifier. Remove the 'key' bullet from Rows.") if record.key is None: raise source.fail(heading, f"{record.address} needs exactly one Schema field with the 'key' modifier.") starts = [index for index in lines if source.lines[index].startswith("- ")] if lines and (not starts or starts[0] != lines[0]): raise source.fail(lines[0], "Expected a stated row key.") record.stated = True for index, stop in zip(starts, starts[1:] + [end]): match = re.fullmatch(r"- \*\*(.+?)\*\*(?: — .+)?", source.lines[index]) if not match or (record.schema[record.key].kind == "integer" and not NUMBER.fullmatch(match[1])): raise source.fail(index, "Expected '- ****' for a stated row.") values = read_fields(source, record, index + 1, stop, indent=" ") record.add(Row(f"{record.address}[{match[1]}]", match[1], source, index, values)) def read_model(source: Source) -> Diary: header, start = source.frontmatter() intent = header.get("aim", "") if not re.fullmatch(INTENT, intent) or header.get("kind") != "intent": raise source.fail(0, "Expected an intent file.") diary = Diary(intent, {}, set()) for title, heading, end in source.sections(start, len(source.lines), 2): node = re.fullmatch(rf"({NAME}): ({NAME})", title) if node: diary.nodes.add(f"{intent}#{node[1]}:{node[2]}") if not node or node[1] != "Record": continue address = f"{intent}#Record:{node[2]}" blocks = list(source.sections(heading + 1, end, 3)) sections = {title: (first, last) for title, first, last in blocks} if address in diary.records or "Schema" not in sections or len(blocks) != len(sections): raise source.fail(heading, "A Record needs a unique name, one Schema, and distinct section headings.") record = Record(address, node[2], read_schema(source, intent, *sections["Schema"]), heading) if sum(schema.key for schema in record.schema.values()) > 1: raise source.fail(heading, f"{address} names more than one key.") if "Rows" in sections: read_stated_rows(source, record, *sections["Rows"]) diary.records[address] = record return diary def read_entries(source: Source, diary: Diary) -> None: header, start = source.frontmatter() if header.get("aim") != diary.intent or header.get("kind") != "entries": raise source.fail(0, f"Expected an Entries file of the intent '{diary.intent}'.") if "key" in header: raise source.fail(0, "The key is declared in the Record's Schema with the 'key' modifier. Remove 'key' from the frontmatter.") listed = diary.records.get(header.get("record", "")) subject = ROW_ADDRESS.fullmatch(header.get("subject", "")) if ("record" in header) == ("subject" in header) or not (listed or (subject and subject[1] in diary.records)): raise source.fail(0, "Expected either 'record', the address of a Record, or 'subject', the row address of one entry.") name = source.path.name if listed: if name != f"{diary.intent}.{listed.name}.entries.aim": raise source.fail(0, f"Expected the list of {listed.address} in {diary.intent}.{listed.name}.entries.aim.") if listed.listed: raise source.fail(0, f"{listed.address} already has a list.") listed.listed = source elif not re.fullmatch(rf"{re.escape(diary.intent)}\.{ID}\.entries\.aim", name): raise source.fail(0, f"Expected a document named {diary.intent}.