readPageDefinitions function

({List<({int line, String message})> problems, Set<String> signatures, Map<String, List<NotationDefinition>> words}) readPageDefinitions(
  1. String text, {
  2. Map<String, List<NotationDefinition>> others = const {},
})

The words a text (a page, or an answer of several screens) defines with define Word … (or declares with primitive Word …, for what no line can express) at the margin, wherever they are written: a definition holds for the whole text, before or after its uses. A // line directly above a define is its purpose. A word defined twice is the later definition, unless both name their meaning (define Timeline#route), when the word has both. A word that uses itself, through these or others (the design system's), is left out. What is wrong is in problems, each with the 1-based line of text it is on; signatures are every define line read, as written without define (what DefinedWords.preread skips).

Implementation

({Map<String, List<NotationDefinition>> words, List<({int line, String message})> problems, Set<String> signatures}) readPageDefinitions(String text,
    {Map<String, List<NotationDefinition>> others = const {}}) {
  final words = <String, List<NotationDefinition>>{};
  final problems = <({int line, String message})>[];
  final signatures = <String>{};
  final lines = text.split(RegExp(r'\r?\n'));
  for (var i = 0; i < lines.length; i++) {
    final raw = lines[i];
    if (!isDeclaration(raw)) continue;
    // Its purpose: the `//` lines at the margin directly above it.
    final doc = <String>[];
    for (var k = i - 1; k >= 0 && lines[k].startsWith('//'); k--) {
      doc.insert(0, lines[k].substring(2).trim());
    }
    final head = i;
    signatures.add(declared(raw));
    final body = <({int indent, String text, int line})>[];
    while (i + 1 < lines.length) {
      final next = lines[i + 1];
      final nt = next.trim();
      if (nt.isNotEmpty && next.length - next.trimLeft().length == 0) break;
      i++;
      if (nt.isEmpty || nt.startsWith('//')) continue;
      body.add((indent: next.length - next.trimLeft().length, text: nt, line: i + 1));
    }
    final said = <String>[];
    final d = definitionOf('page', head + 1, raw.trim(), body, doc.join(' '), said);
    for (final p in said) {
      problems.add((line: int.tryParse(RegExp(r'^page:(\d+):').firstMatch(p)?[1] ?? '') ?? head + 1, message: p));
    }
    if (d == null) continue;
    final had = words[d.word];
    if (had != null && d.name != null && had.every((h) => h.name != null && h.name != d.name)) {
      had.add(d);
    } else {
      words[d.word] = [d];
    }
  }
  for (final w in words.keys.toList()) {
    final path = _cycle(w, {...others, ...words}, [w]);
    if (path != null) {
      final d = words.remove(w)!.first;
      problems.add((line: d.line, message: '${d.at(d.line)}: $w uses itself (${path.join(' > ')}): it is not read.'));
    }
  }
  return (words: words, problems: problems, signatures: signatures);
}