#!/usr/bin/env python3 """Checks the AIM 7 example models in this directory. python3 examples/check.py [dir ...] check the examples (default: the five whole models) python3 examples/check.py --self-test break the examples in memory and expect each error It reads `aim/**/*.aim` of an example and checks what AIM 7 adds below the facets: the Schema of every Record (types, `key`, `rough`, `unit`), stated rows, `### Period`, `### Replaces`, `### Complete`, a requirement's strength, precedence and source, and every Entries file with its values, texts, typed links, origin trailers, files and fingerprints. It does not check the behavioral graph (edges and the facets other than Record). Python 3, standard library only. """ import hashlib import json import os import re import sys from datetime import date, datetime from decimal import Decimal, InvalidOperation from urllib.parse import unquote 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_]*(?:\.[a-z][a-z0-9_]*)*' MODEL = r'(?:[a-z][a-z0-9-]*/)?' RECORD = INTENT + r'#Record:' + NAME ROW_ADDRESS = re.compile(r'(' + MODEL + RECORD + r')\[(.+)\]') REQ_ADDRESS = re.compile(r'(' + INTENT + r')#Requirements\[(.+)\]') FACET_ADDRESS = re.compile(r'(' + INTENT + r')#(' + NAME + r'):(' + NAME + r')') LINK = re.compile(r'\[(.*)\]\(aim:([^)]+)\)') TRAILER = re.compile(r'(?:^|[ \t])— from(?=:|[ \t]*\[)') AT = re.compile(r'\s+at\s+(#' + ID + r'|"(?:[^"\\]|\\.)*"|page \d+|\d{1,2}:\d{2}(?::\d{2})?)') PROPOSED = re.compile(r'proposed(?: by (\S(?:.*\S)?), (\d{4}-\d{2}-\d{2}))?') BARE = re.compile(r'[A-Za-z0-9._-]+') NUMBER = re.compile(r'-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?') DATETIME = re.compile(r'\d{4}-\d\d-\d\dT\d\d:\d\d(?::\d\d(?:\.\d+)?)?(?:Z|[+-]\d\d:\d\d)') ROUGH = re.compile(r'(?:\d{4}-\d\d-\d\d|\d{4}-\d\d|\d{4}|\d{1,3}X{1,3})[~?]?') DURATION = re.compile(r'(\d+) (minutes|hours|days|business-days|weeks|months|years)') POSITION = re.compile(r'(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)') FINGERPRINT = re.compile(r'([a-z0-9]+):([0-9a-f]+)') SCALARS = {'string', 'number', 'integer', 'decimal', 'boolean', 'date', 'datetime', 'email', 'url', 'phone', 'file', 'duration', 'position'} FACETS = {'Record', 'Operation', 'Process', 'Persona', 'View', 'Event', 'Trigger', 'Capability', 'Style', 'State', 'Knowledge', 'Organisation', 'Project', 'Software', 'Service', 'Output'} EXAMPLES = ['diary', 'board', 'scheduling', 'claims', 'incidents'] class Field: def __init__(self, name, line): self.name, self.line = name, line self.kind = 'scalar' # scalar, enum, ref, reflist, modelref, fingerprint, other self.scalar = 'string' self.values = [] # enum values self.target = None # (Record address, field) of a ref or a reference list self.arg = None # modelref type, or the file field a fingerprint names self.mods = set() self.min = self.max = self.default = None self.units = [] class Record: def __init__(self, intent, name, path, line): self.intent, self.name, self.path, self.line = intent, name, path, line self.address = f'{intent}#Record:{name}' self.fields = {} self.key = None self.rows = {} # typed key -> Row, stated rows and entries alike self.stated = False # has a ### Rows block self.entries = False # has a list or appears in a document self.list_path = None self.period = None # (start, end, one at a time, per field) self.replaces = None self.immutable = set() class Row: def __init__(self, record, key, keytext, path, line, entry): self.record, self.key, self.keytext, self.path, self.line, self.entry = record, key, keytext, path, line, entry self.address = f'{record.address}[{keytext}]' self.values = {} # field -> (value, line, origin) self.links = [] # dicts: field, address, line, origin, at, model self.texts = {} # field -> [(language, text, line, origin)] self.origin = None self.words = '' def tokens(text): """Split a schema line's right side on spaces outside brackets and quotes.""" out, depth, quote, cur = [], 0, False, '' for ch in text: if ch == '"': quote = not quote if not quote: depth += ch == '(' depth -= ch == ')' if ch in ' \t' and not depth and not quote: if cur: out.append(cur) cur = '' else: cur += ch return out + ([cur] if cur else []) def call(token, word): return token[len(word) + 1:-1] if token.startswith(word + '(') and token.endswith(')') else None def frontmatter(text): lines = text.split('\n') meta = {} if not lines or lines[0].strip() != '---': return None, lines, 0 for i in range(1, len(lines)): if lines[i].strip() == '---': return meta, lines, i + 1 m = re.match(r'([A-Za-z_]+):\s*(.*)$', lines[i]) if m: value = m.group(2).strip() meta[m.group(1)] = (json.loads(value) if value.startswith('"') else value, i + 1) return None, lines, 0 def sections(lines, start): """-> [(h2 title, h2 line, {h3 title or None: [(line number, line, in fence)]})]""" out, fence = [], None cur = None h3 = None for i in range(start, len(lines)): line, no = lines[i], i + 1 stripped = line.strip() if fence: if stripped and set(stripped) == {fence[0]} and len(stripped) >= len(fence): fence = None elif cur: cur[2].setdefault(h3, []).append((no, line, True)) continue m = re.match(r'\s*(`{3,}|~{3,})', line) if m: fence = m.group(1) continue if line.startswith('## '): cur, h3 = (line[3:].strip(), no, {}), None out.append(cur) elif line.startswith('### ') and cur: h3 = line[4:].strip() cur[2].setdefault(h3, []) elif cur: cur[2].setdefault(h3, []).append((no, line, False)) return out def parse_date(text): return date.fromisoformat(text) class Checker: def __init__(self, base, files): self.base, self.files = base, files self.errors, self.notes = [], [] self.intents, self.facets, self.records, self.reqs = set(), set(), {}, {} self.documents = [] # (path, line, subject address, [rows]) self.pending = [] # origin addresses to resolve: (path, line, address) self.req_sources = [] self.proposed = 0 def err(self, path, line, message): self.errors.append((path, line, message)) def note(self, path, line, message): self.notes.append((path, line, message)) # ---- literals ------------------------------------------------------------------------- def text(self, raw, pattern=BARE): if raw.startswith('"'): try: value = json.loads(raw) except ValueError: raise ValueError(f'{raw} is not a quoted text.') if not isinstance(value, str): raise ValueError(f'{raw} is not a text.') return value if not pattern.fullmatch(raw): raise ValueError(f'{raw!r} is neither a quoted text nor a bare token.') return raw def literal(self, field, raw): """The typed value of a literal for this field. Raises ValueError with the reason.""" raw = raw.strip() if raw in ('', 'null'): raise ValueError('A blank value or a bare null states nothing.') if field.kind == 'ref': target = self.target_field(field) return self.literal(target, raw) if target else self.text(raw) if field.kind == 'enum': value = self.text(raw) if value not in field.values: raise ValueError(f"'{value}' is not one of {', '.join(field.values)}.") return value if field.kind == 'fingerprint': if not FINGERPRINT.fullmatch(raw): raise ValueError('A fingerprint is written :.') return raw kind = field.scalar if kind in ('integer', 'number', 'decimal'): number, unit = raw, None if len(field.units) > 1: number, _, unit = raw.partition(' ') if unit not in field.units: raise ValueError(f"The value names its unit, one of {', '.join(field.units)}.") if not NUMBER.fullmatch(number) or (kind == 'integer' and not re.fullmatch(r'-?\d+', number)): raise ValueError(f'{raw!r} is not {"an integer" if kind == "integer" else "a number"}' + (' with its unit.' if field.units else '.')) try: value = Decimal(number) except InvalidOperation: raise ValueError(f'{raw!r} is not a number.') if field.min is not None and value < field.min: raise ValueError(f'{raw} is below min({field.min}).') if field.max is not None and value > field.max: raise ValueError(f'{raw} is above max({field.max}).') return (value, unit) if unit else value if kind == 'boolean': if raw not in ('true', 'false'): raise ValueError('A boolean is true or false.') return raw == 'true' if kind == 'date': if 'rough' in field.mods: if not ROUGH.fullmatch(raw) or len(raw.rstrip('~?')) not in (4, 7, 10): raise ValueError(f'{raw!r} is not a date in the spelling of ISO 8601-2.') if len(raw.rstrip('~?')) < 10 or raw[-1] in '~?': return raw try: return parse_date(raw.rstrip('~?')) if 'rough' in field.mods else parse_date(raw) except ValueError: raise ValueError(f'{raw!r} is not a calendar date.') if kind == 'datetime': if not DATETIME.fullmatch(raw): raise ValueError(f'{raw!r} is not a moment with a time zone or offset.') try: return datetime.fromisoformat(raw.replace('Z', '+00:00')) except ValueError: raise ValueError(f'{raw!r} is not a moment.') if kind == 'duration': m = DURATION.fullmatch(raw) if not m: raise ValueError(f'{raw!r} is not a length of time: a whole number and a unit.') return (int(m.group(1)), m.group(2)) if kind == 'position': m = POSITION.fullmatch(raw) if not m or not -90 <= float(m.group(1)) <= 90 or not -180 <= float(m.group(2)) <= 180: raise ValueError(f'{raw!r} is not a position: latitude, then longitude.') return (m.group(1), m.group(2)) if kind == 'file': return self.text(raw, re.compile(r'[A-Za-z0-9._/-]+')) value = self.text(raw) if kind == 'url' and not re.match(r'https?://\S+$', value): raise ValueError(f'{value!r} is not an absolute web address.') if kind == 'email' and not re.fullmatch(r'[^@\s]+@[^@\s]+\.[^@\s]+', value): raise ValueError(f'{value!r} is not an e-mail address.') if kind == 'phone' and not re.fullmatch(r'\+[\d ().-]{7,}', value): raise ValueError(f'{value!r} is not a telephone number in international form.') if field.min is not None and len(value) < field.min: raise ValueError(f'The text is shorter than min({field.min}).') if field.max is not None and len(value) > field.max: raise ValueError(f'The text is longer than max({field.max}).') return value def target_field(self, field): record = self.records.get(field.target[0]) return record.fields.get(field.target[1]) if record else None def to_key(self, record, keytext): """The typed key a row address names. A text key stands without quotes.""" key = record.key if key.kind == 'scalar' and key.scalar in ('integer', 'number', 'decimal', 'boolean', 'date', 'datetime', 'duration', 'position'): try: return self.literal(key, keytext) except ValueError: return None return keytext def find_row(self, address): m = ROW_ADDRESS.fullmatch(address) record = self.records.get(m.group(1)) if m else None if not record or not record.key: return None return record.rows.get(self.to_key(record, unquote(m.group(2)))) def resolve(self, address): """-> 'row', 'requirement', 'positional', 'facet:', 'intent', 'unverifiable' or None""" if re.match(r'[a-z][a-z0-9-]*/', address): return 'unverifiable' if ROW_ADDRESS.fullmatch(address): return 'row' if self.find_row(address) else None m = REQ_ADDRESS.fullmatch(address) if m: if m.group(2).isdigit(): return 'positional' return 'requirement' if (m.group(1), m.group(2)) in self.reqs else None m = FACET_ADDRESS.fullmatch(address) if m: return f'facet:{m.group(2)}' if m.groups() in self.facets else None return 'intent' if address in self.intents else None # ---- the model: Records and Requirements ---------------------------------------------- def read_schema(self, record, lines): for no, line, fenced in lines: if not fenced or not line.strip(): continue m = re.match(r'\s*(' + NAME + r'):\s*(\S.*)$', line) if not m: self.err(record.path, no, 'Expected : *.') continue field = Field(m.group(1), no) if field.name in record.fields: self.err(record.path, no, f"Field '{field.name}' is declared twice.") record.fields[field.name] = field first, *rest = tokens(m.group(2)) self.read_type(record, field, first, no) for token in rest: if token in ('required', 'optional', 'unique', 'key', 'rough', 'owner', '!owner'): field.mods.add(token) elif call(token, 'min') is not None or call(token, 'max') is not None: try: setattr(field, token[:3], Decimal(token[4:-1])) except InvalidOperation: self.err(record.path, no, f'{token} needs a number.') elif call(token, 'default') is not None: field.default = call(token, 'default') elif call(token, 'label') is not None: pass elif call(token, 'unit') is not None: field.units = [unit.strip() for unit in call(token, 'unit').split(',') if unit.strip()] if not field.units or field.kind != 'scalar' or field.scalar not in ('number', 'integer', 'decimal'): self.err(record.path, no, 'unit(...) names what a number field measures.') elif call(token, 'ref') is not None or call(token, 'enum') is not None or call(token, 'list') is not None: self.read_type(record, field, token, no) else: self.err(record.path, no, f"Unknown modifier '{token}'.") if 'rough' in field.mods and not (field.kind == 'scalar' and field.scalar == 'date'): self.err(record.path, no, "'rough' stands on a date field.") if {'required', 'optional'} <= field.mods: self.err(record.path, no, "'required' together with 'optional'.") keys = [field for field in record.fields.values() if 'key' in field.mods] for field in keys[1:]: self.err(record.path, field.line, f'{record.address} has more than one key field.') if keys: key = keys[0] plain = key.kind == 'enum' or (key.kind == 'scalar' and key.scalar != 'file') if not plain or not {'required', 'unique'} <= key.mods: self.err(record.path, key.line, "The key is a 'required unique' enum or non-file scalar field.") else: record.key = key for field in record.fields.values(): if field.kind == 'fingerprint': named = record.fields.get(field.arg) if not named or named.kind != 'scalar' or named.scalar != 'file': self.err(record.path, field.line, f"fingerprint({field.arg}) names no file field of {record.address}.") def read_type(self, record, field, token, no): if token in SCALARS: field.kind, field.scalar = 'scalar', token elif call(token, 'enum') is not None: field.kind = 'enum' field.values = [re.sub(r'\s*".*"$', '', value.strip()) for value in re.split(r',(?=(?:[^"]*"[^"]*")*[^"]*$)', call(token, 'enum'))] elif call(token, 'ref') is not None: m = re.fullmatch(r'(' + INTENT + r')#(' + NAME + r')\.(' + NAME + r')', call(token, 'ref')) if not m: self.note(record.path, no, f'{token} is not a reference to a Record facet and is not checked.') field.kind = 'other' else: field.kind, field.target = 'ref', (f'{m.group(1)}#Record:{m.group(2)}', m.group(3)) elif call(token, 'list') is not None: inner = call(token, 'list') m = re.fullmatch(r'(' + INTENT + r')#(' + NAME + r')', inner) or re.fullmatch(r'ref\((' + INTENT + r')#(' + NAME + r')\.' + NAME + r'\)', inner) if m: field.kind, field.target = 'reflist', (f'{m.group(1)}#Record:{m.group(2)}', None) else: field.kind = 'other' elif call(token, 'part') is not None or call(token, 'map') is not None: field.kind = 'other' elif call(token, 'modelref') is not None: field.kind, field.arg = 'modelref', call(token, 'modelref') if field.arg != 'Requirement' and field.arg not in FACETS: self.err(record.path, no, f'modelref({field.arg}) names neither Requirement nor a facet type.') elif call(token, 'fingerprint') is not None: field.kind, field.arg = 'fingerprint', call(token, 'fingerprint') else: self.note(record.path, no, f"Unknown type '{token}', read as string.") def read_intent(self, path, meta, lines, start): intent = meta['aim'][0] todo = [] for title, line, blocks in sections(lines, start): m = re.fullmatch(r'(' + NAME + r'): (.+)', title) if title == 'Requirements': self.read_requirements(path, intent, blocks.get(None, [])) elif m and m.group(1) in FACETS: self.facets.add((intent, m.group(1), m.group(2))) if m.group(1) == 'Record': record = Record(intent, m.group(2), path, line) self.records[record.address] = record self.read_schema(record, blocks.get('Schema', [])) todo.append((record, blocks)) return todo def read_requirements(self, path, intent, lines): for no, line, fenced in lines: if fenced or not line.startswith('- '): continue body = line[2:].strip() m = re.match(r'\*\*(.+?)\*\*\s*', body) label = m.group(1) if m else None body = body[m.end():] if m else body should = body.startswith('(should)') if should and not label: self.err(path, no, 'The mark (should) needs a requirement with a label.') source = re.search(r'\s—\s+from(?::\s*(.+)|\s*\[(.+)\])$', body) if source: body = body[:source.start()] if source.group(2): for address in re.split(r',\s*', source.group(2)): self.req_sources.append((path, no, address.strip())) over = re.search(r'\s—\s+over\s*\[(.+)\]$', body) names = re.split(r',\s*', over.group(1)) if over else [] if label: if (intent, label) in self.reqs: self.err(path, no, f"Duplicate requirement label '{label}'.") self.reqs[(intent, label)] = {'should': should, 'over': names, 'path': path, 'line': no} elif over: self.err(path, no, "'over' stands on a requirement with a label.") def check_requirements(self): for (intent, label), req in self.reqs.items(): for address in req['over']: m = REQ_ADDRESS.fullmatch(address) other = self.reqs.get((m.group(1), m.group(2))) if m else None if not req['should']: self.err(req['path'], req['line'], f"'over' stands on a \"must\". Only \"should\" requirements are ranked.") elif not other: self.err(req['path'], req['line'], f"'over' names {address}, which is no labelled requirement.") elif not other['should']: self.err(req['path'], req['line'], f"'over' names {address}, which is a \"must\". A \"must\" never gives way.") seen, stack = set(), [(intent, label)] while stack: for address in self.reqs.get(stack.pop(), {}).get('over', []): m = REQ_ADDRESS.fullmatch(address) node = (m.group(1), m.group(2)) if m else None if node == (intent, label): self.err(req['path'], req['line'], f"'over' closes a circle at {label}.") stack = [] break if node and node not in seen: seen.add(node) stack.append(node) for path, no, address in self.req_sources: kind = self.resolve(address) if kind == 'unverifiable': self.note(path, no, f'The source {address} lies in another model and is not checked here.') elif kind not in ('row', 'requirement', 'facet:Knowledge', 'facet:Event'): self.err(path, no, f'The source {address} does not resolve to a Knowledge facet, a requirement, an Event or a row.') # ---- blocks of a Record ---------------------------------------------------------------- def read_blocks(self, record, blocks): path = record.path for no, line, fenced in blocks.get('Immutable', []): m = re.match(r'- `(' + NAME + r')`', line) if m: record.immutable.add(m.group(1)) bullets = lambda name: [(no, line[2:].strip()) for no, line, fenced in blocks.get(name, []) if line.startswith('- ')] if 'Period' in blocks: start = end = per = None one = False for no, text in bullets('Period'): m = re.fullmatch(r'from `(' + NAME + r')` until `(' + NAME + r')`', text) p = re.fullmatch(r'one at a time(?: per `(' + NAME + r')`)?', text) if m: start, end = record.fields.get(m.group(1)), record.fields.get(m.group(2)) kinds = {field.scalar if field and field.kind == 'scalar' else None for field in (start, end)} if kinds not in ({'date'}, {'datetime'}): self.err(path, no, 'A period names two date or two datetime fields of the Record.') start = end = None elif p: one, per = True, p.group(1) if per and per not in record.fields: self.err(path, no, f"'{per}' is no field of {record.address}.") else: self.err(path, no, "Expected - from `` until `` or - one at a time [per ``].") if start: record.period = (start.name, end.name, one, per) elif not self.errors or self.errors[-1][0] != path: self.err(path, record.line, 'The Period block names no start and end.') if 'Replaces' in blocks: items = bullets('Replaces') m = re.fullmatch(r'`(' + NAME + r')`', items[0][1]) if len(items) == 1 else None field = record.fields.get(m.group(1)) if m else None if not field or field.kind not in ('ref', 'reflist') or field.target[0] != record.address: self.err(path, items[0][0] if items else record.line, "The Replaces block names one field that references the Record's own key.") else: record.replaces = field.name for no, text in bullets('Complete'): m = re.fullmatch(r'`(' + NAME + r')`', text) field = record.fields.get(m.group(1)) if m else None if text != 'the collection' and not (field and (field.kind == 'reflist' or field.kind == 'other')): self.err(path, no, 'A Complete bullet is `the collection` or a list field of the Record.') if 'Rows' in blocks: record.stated = True if not record.key: self.err(path, record.line, f"{record.address} has Rows and needs exactly one Schema field with the 'key' modifier.") else: self.read_rows(record, blocks['Rows']) def read_rows(self, record, lines): path, row = record.path, None for no, line, fenced in lines: if not line.strip(): continue if line.startswith('- '): row = None body = line[2:] if body.startswith('**"'): try: _, end = json.JSONDecoder().raw_decode(body[2:]) except ValueError: end = -1 keytext, rest = body[2:2 + end], body[2 + end:] ok = end > 0 and rest.startswith('**') rest = rest[2:] else: m = re.match(r'\*\*(.+?)\*\*', body) ok = bool(m) keytext, rest = (m.group(1), body[m.end():]) if m else ('', '') words = re.fullmatch(r'(?:\s+—\s+(.*))?\s*', rest) if not ok or not words: self.err(path, no, 'Expected - **** or - **** — .') continue try: key = self.literal(record.key, keytext) except ValueError as e: self.err(path, no, f'Invalid key: {e}') continue shown = json.loads(keytext) if keytext.startswith('"') else keytext if key in record.rows: self.err(path, no, f'Duplicate stated key {record.address}[{shown}].') continue row = record.rows[key] = Row(record, key, shown, path, no, False) row.words = words.group(1) or '' row.values[record.key.name] = (key, no, None) continue m = re.match(r'\s+- (' + NAME + r'):\s*(.*)$', line) if not row or (not m and not line.startswith(' ')): self.err(path, no, 'Malformed row.') elif m: name, raw = m.group(1), m.group(2) field = record.fields.get(name) if not field: self.err(path, no, f"'{name}' is no Schema field of {record.address}.") elif name in row.values or any(link['field'] == name for link in row.links): self.err(path, no, f"'{name}' is stated twice in this row." if field is not record.key else 'A value bullet repeats the key.') elif field.kind not in ('scalar', 'enum', 'ref') or (field.kind == 'scalar' and field.scalar == 'file'): self.err(path, no, f"'{name}' has a type that Rows do not state.") elif field.kind == 'ref' and LINK.fullmatch(raw.strip()): row.links.append({'field': name, 'address': LINK.fullmatch(raw.strip()).group(2), 'line': no, 'origin': None, 'at': None}) else: try: row.values[name] = (self.literal(field, raw), no, None) except ValueError as e: self.err(path, no, f"'{name}': {e}") # ---- Entries files --------------------------------------------------------------------- def origin(self, rest, path, no): rest = rest.strip() if not rest: return None m = re.fullmatch(r'— from:\s*(\S.*)', rest) a = re.fullmatch(r'— from\s*\[(.+)\]', rest) if m and not TRAILER.search(' ' + m.group(1)): words = m.group(1).strip() if words.startswith('proposed'): p = PROPOSED.fullmatch(words) if not p: self.err(path, no, 'A suggestion is marked "proposed" or "proposed by , ".') return None return {'proposed': True, 'text': words, 'by': p.group(1), 'date': p.group(2)} return {'proposed': False, 'text': words} if a and not m: self.pending.append((path, no, a.group(1).strip())) return {'proposed': False, 'address': a.group(1).strip()} self.err(path, no, 'Expected one origin trailer, "— from: " or "— from [
]".') return None def split(self, text, path, no): """-> (value, where a link points inside, origin)""" s, at = text.strip(), None if s.startswith('"'): try: _, end = json.JSONDecoder().raw_decode(s) except ValueError: end = len(s) value, rest = s[:end], s[end:] elif s.startswith('[') and '](aim:' in s: end = s.find(')', s.index('](aim:')) end = len(s) - 1 if end < 0 else end value, rest = s[:end + 1], s[end + 1:] m = AT.match(rest) if m: at, rest = m.group(1), rest[m.end():] else: m = TRAILER.search(s) value, rest = (s[:m.start()], s[m.start():]) if m else (s, '') return value.strip(), at, self.origin(rest, path, no) def read_entries(self, path, meta, lines, start): intent = meta['aim'][0] name = os.path.basename(path) if intent not in self.intents: return self.err(path, meta['aim'][1], f"'aim' names {intent}, which is no intent of this model.") if 'key' in meta: return self.err(path, meta['key'][1], "The key is declared in the Record's Schema with the 'key' modifier. Remove 'key' from the frontmatter.") if ('record' in meta) == ('subject' in meta): return self.err(path, 1, "Expected either 'record', for a list, or 'subject', for a document.") listed = subject = None if 'record' in meta: listed = self.records.get(meta['record'][0]) if not listed: return self.err(path, meta['record'][1], f"'record' names {meta['record'][0]}, which is no Record of the model.") if listed.list_path: return self.err(path, meta['record'][1], f'{listed.address} already has a list.') listed.list_path, listed.entries = path, True if name != f'{intent}.{listed.name}.entries.aim': self.err(path, 1, f'Expected the list of {listed.address} in {intent}.{listed.name}.entries.aim.') else: subject = meta['subject'][0] m = ROW_ADDRESS.fullmatch(subject) if not m or m.group(1) not in self.records: return self.err(path, meta['subject'][1], f"'subject' names {subject}, which is no row address of the model.") if not re.fullmatch(re.escape(intent) + r'\.' + ID + r'\.entries\.aim', name): self.err(path, 1, f'Expected a document named {intent}.