K7PL

Lecture des textes par couches🔗

Deux lecteurs lisent un texte, et leurs codes, avec les messages de l'annexe A, leur sont communs.

// SPDX-FileCopyrightText: 2026 Cyprien PIERRE
// SPDX-License-Identifier: CECILL-2.1
//
// Codes and messages of the refusals emitted when a text is read. Both readers share them:
// refusals.k, which reads a text as a tree, and balance.k, which reads it as a stream of
// delimiters. The messages are those of annex A (tables tab:err-frontieres and
// tab:err-delimiteurs): they are rendered in the specification and stay in French, and
// tools/layer-check compares them word for word with the annex.
//
// - ERR-TOP-001 to ERR-TOP-003: the three inclusions refused by the grammar of the layers
//   (crossings.k), from the most specific container (layer 3) to the most generic one.
// - ERR-DLM-001 to ERR-DLM-003: delimiters that do not pair (author's choices of
//   2026-10-26, questionnaire Q-LEX-006 and Q-ERR-001: one code per kind of fault); their
//   messages are confirmed by the author (2026-10-27, Q-ERR-102).
// - ERR-DLM-004: a string never closed (author's choice of 2026-10-27, Q-ERR-101); its
//   message is a proposal.

module CODES
  syntax Code ::= "ERR-TOP-001" | "ERR-TOP-002" | "ERR-TOP-003"
                | "ERR-DLM-001" | "ERR-DLM-002" | "ERR-DLM-003" | "ERR-DLM-004"

  // A message is kept as written, in a token sort of its own.
  syntax Message ::= r"\\\"[^\\\"]*\\\"" [token]

  syntax Refusal ::= refusal(Code, Message) [symbol(refusal)]

  syntax Message ::= message(Code) [function, total]
  rule message(ERR-TOP-001) => "Structure de couche 2 `( )` instanciée dans un bloc de couche 3 `[ ]`. Déplacer le calcul dans un `let` de couche 2 en amont."
  rule message(ERR-TOP-002) => "Structure de couche 1 `{ }` instanciée dans un bloc de couche 3 `[ ]`. Déplacer le calcul dans un bloc `{ }` de couche 1 en amont."
  rule message(ERR-TOP-003) => "Structure de couche 1 `{ }` instanciée dans un bloc de couche 2 `( )`. Déplacer le calcul dans un bloc `{ }` de couche 1 en amont."
  rule message(ERR-DLM-001) => "Délimiteur ouvrant jamais refermé. Ajouter le délimiteur fermant de sa paire, ou retirer l'ouvrant."
  rule message(ERR-DLM-002) => "Délimiteur fermant sans délimiteur ouvrant. Retirer le fermant, ou ajouter l'ouvrant de sa paire."
  rule message(ERR-DLM-003) => "Délimiteur fermant d'une autre paire que les délimiteurs encore ouverts. Fermer le dernier délimiteur ouvert par le fermant de sa paire."
  rule message(ERR-DLM-004) => "Chaîne jamais refermée : elle court jusqu'à la fin du texte. Ajouter le guillemet fermant."

  syntax Refusal ::= refuse(Code) [function, total]
  rule refuse(C) => refusal(C, message(C))
endmodule

Le premier voit un texte comme une suite d'expressions, selon la grammaire des couches ; sa syntaxe lexicale est tenue à part du module des règles. Le module REFUSALS rend, pour chaque inclusion refusée, son code et son message.

// SPDX-FileCopyrightText: 2026 Cyprien PIERRE
// SPDX-License-Identifier: CECILL-2.1
//
// A text, as the reader sees it: a sequence of expressions, each of them either well
// layered (layers.k) or containing refused inclusions (crossings.k).

requires "crossings.k"

module READER
  imports CROSSINGS

  syntax Program ::= List{Expression, ""} [symbol(program)]

  // A train, a run made only of glyphs (tokens.k, Q-LEX-201), is read as an atom of a
  // sort of its own; the grammar of the layers counts it among the symbols.
  syntax Atom ::= Train
  syntax Train [token]
endmodule
// SPDX-FileCopyrightText: 2026 Cyprien PIERRE
// SPDX-License-Identifier: CECILL-2.1
//
// Lexical syntax used to read a text (kompile --syntax-module TOKENS). It is kept out of
// the module that holds the rules, whose own parser would otherwise read K variables
// as symbols. stream.k repeats these classes for the balance reader, and
// tools/layer-check reads every text with both readers.
//
// Each class follows the author's answers to the reading lot (wiki/questions.md,
// questionnaires of 2026-10-26 and 2026-10-27); what is still open is marked a proposal.
//
// - A symbol is any run of characters other than white space, the six delimiters and
//   the double quote. A semicolon belongs to it when a symbol character follows, and a
//   lone semicolon is a symbol of its own: `a;` reads `a` then `;`, `a;b` is one symbol
//   (Q-LEX-105). A sigil (`#`, `:`, `@`, `?`, `!`, Q-LEX-102) starts a symbol; Phase 0
//   turns it into an attribute (chapter 6).
// - A train is a run made only of glyphs of the table of chapter 1 (tab:glyphes) and of
//   the modifiers ´ and ¨, each character one glyph; any other run is read whole, as a
//   name or a number (Q-LEX-201). reader.k gives trains a sort of their own.
// - A number (Q-NUM-105) is a decimal with an optional fraction and exponent, whose
//   digits may be grouped by `_`; a rational `1/3`; a complex `3+4i`; `inf`, `-inf` or
//   `nan`. Radix prefixes are not numbers.
// - A string is enclosed in double quotes and may span lines (Q-STR-103). Proposal, until
//   the escapes are chosen (Q-STR-201): a backslash escapes the next character; an
//   unknown escape is to be refused (Q-STR-102).
// - Comments (Q-LEX-004): `;;` opens a comment that runs to the end of the line, `;;;` a
//   heading and `;;;;` a sub-heading. A semicolon just before an opening delimiter
//   disables the tree it opens; this reader reads `;(` as a lone semicolon followed by
//   `(`, and so checks the disabled tree like any other (Q-LEX-104). stream.k marks it.

requires "reader.k"

module TOKENS
  imports READER

  syntax Symbol ::= r"([^ \\t\\n\\r\\[\\](){}\\\";]|;[^ \\t\\n\\r\\[\\](){}\\\";])+|;" [token]
  syntax Train ::= r"(\\+|-|×|÷|⌊|⌈|≠|⊏|⊔|⍋|⍒|↕|∾|⊣|⊢|⥊|∧|∨|¬|=|<|>|≤|≥|⍟|⊘|↢|↣|´|¨)+" [token, prec(2)]
  syntax Number ::= r"[+\\-]?([0-9](_?[0-9])*(\\.[0-9](_?[0-9])*)?([eE][+\\-]?[0-9]+)?|[0-9](_?[0-9])*\\/[0-9](_?[0-9])*|[0-9](_?[0-9])*(\\.[0-9](_?[0-9])*)?([eE][+\\-]?[0-9]+)?[+\\-][0-9](_?[0-9])*(\\.[0-9](_?[0-9])*)?([eE][+\\-]?[0-9]+)?i|inf)|nan" [token, prec(1)]
  syntax String ::= r"\\\"([^\\\"\\\\]|\\\\.)*\\\"" [token]

  syntax #Layout ::= r"(;;[^\\n\\r]*)"
                   | r"([\\ \\n\\r\\t])"
endmodule
// SPDX-FileCopyrightText: 2026 Cyprien PIERRE
// SPDX-License-Identifier: CECILL-2.1
//
// Refusals of the layer grammar: each forbidden inclusion of crossings.k produces its
// code and its message (codes.k), in the order of the text. A text is well layered exactly
// when it produces no refusal. balance.k checks the same inclusions on a stream of
// delimiters; tools/layer-check requires the two readers to agree.

requires "reader.k"
requires "codes.k"
requires "tokens.k" // lexical syntax of the texts read by this definition

module REFUSALS
  imports READER
  imports CODES

  syntax Refusals ::= List{Refusal, ""} [symbol(refusals)]

  syntax Refusals ::= Refusals "+++" Refusals [function, total, right]
  rule .Refusals +++ R:Refusals => R
  rule (X:Refusal Xs:Refusals) +++ R:Refusals => X (Xs +++ R)

  syntax Refusals ::= crossings(Program)       [function, total]
                    | expression(Expression)   [function, total]
                    | inSquare(SquareContents) [function, total]
                    | inParen(ParenContents)   [function, total]
                    | inBrace(BraceContents)   [function, total]

  rule crossings(.Program) => .Refusals
  rule crossings(E:Expression P:Program) => expression(E) +++ crossings(P)

  rule expression(_:Atom) => .Refusals
  rule expression([ C:SquareContents ]) => inSquare(C)
  rule expression(( C:ParenContents )) => inParen(C)
  rule expression({ C:BraceContents }) => inBrace(C)

  // Inside [ ]: atoms and [ ] only. A refused inclusion is still read in its own layer,
  // so that the refusals nested in it are reported as well.
  rule inSquare(.SquareContents) => .Refusals
  rule inSquare(_:Atom C:SquareContents) => inSquare(C)
  rule inSquare([ D:SquareContents ] C:SquareContents) => inSquare(D) +++ inSquare(C)
  rule inSquare(( D:ParenContents ) C:SquareContents) => refuse(ERR-TOP-001) (inParen(D) +++ inSquare(C))
  rule inSquare({ D:BraceContents } C:SquareContents) => refuse(ERR-TOP-002) (inBrace(D) +++ inSquare(C))

  // Inside ( ): atoms, ( ) and [ ].
  rule inParen(.ParenContents) => .Refusals
  rule inParen(_:Atom C:ParenContents) => inParen(C)
  rule inParen([ D:SquareContents ] C:ParenContents) => inSquare(D) +++ inParen(C)
  rule inParen(( D:ParenContents ) C:ParenContents) => inParen(D) +++ inParen(C)
  rule inParen({ D:BraceContents } C:ParenContents) => refuse(ERR-TOP-003) (inBrace(D) +++ inParen(C))

  // Inside { }: everything.
  rule inBrace(.BraceContents) => .Refusals
  rule inBrace(_:Atom C:BraceContents) => inBrace(C)
  rule inBrace([ D:SquareContents ] C:BraceContents) => inSquare(D) +++ inBrace(C)
  rule inBrace(( D:ParenContents ) C:BraceContents) => inParen(D) +++ inBrace(C)
  rule inBrace({ D:BraceContents } C:BraceContents) => inBrace(D) +++ inBrace(C)

  configuration <k> crossings($PGM:Program) </k>
endmodule

Le second, le module BALANCE, voit un texte comme un flux de délimiteurs qu'il empile et dépile. Il lit aussi un texte dont les délimiteurs ne s'apparient pas, et en signale chaque défaut avec la ligne du délimiteur en cause. Les deux lecteurs doivent s'accorder sur chaque texte vérifié.

// SPDX-FileCopyrightText: 2026 Cyprien PIERRE
// SPDX-License-Identifier: CECILL-2.1
//
// A text as balance.k reads it: a stream of delimiters, atoms and line breaks. Unlike the
// tree of reader.k, a stream does not need its delimiters to pair, so a text whose
// delimiters do not pair is still read, and each fault is reported with its line.
//
// A semicolon written just before an opening delimiter disables the tree that delimiter
// opens (chapter 5); the disabled tree is read and checked like any other (author's
// choice of 2026-10-26, Q-LEX-104).

module STREAM
  syntax Item ::= "[" [symbol(openSquare)]  | "]" [symbol(closeSquare)]
                | "(" [symbol(openParen)]   | ")" [symbol(closeParen)]
                | "{" [symbol(openBrace)]   | "}" [symbol(closeBrace)]
                | ";[" [symbol(disabledSquare)]
                | ";(" [symbol(disabledParen)]
                | ";{" [symbol(disabledBrace)]
                | Word | Text | OpenText | Newline

  syntax Stream ::= List{Item, ""} [symbol(stream)]

  syntax Word [token]    // a symbol, a train or a number
  syntax Text [token]    // a string literal, which may span lines
  syntax OpenText [token] // a string never closed: it runs to the end of the text
  syntax Newline [token]
endmodule

// Lexical syntax of the stream (kompile --syntax-module SCANNER). A word is a symbol, a
// train or a number of tokens.k, and a text one of its strings; comments are those of
// chapter 5.
// tools/layer-check reads every text with both readers, so that a difference between the
// two lexical syntaxes shows as a disagreement.
module SCANNER
  imports STREAM

  syntax Word ::= r"([^ \\t\\n\\r\\[\\](){}\\\";]|;[^ \\t\\n\\r\\[\\](){}\\\";])+|;" [token]
  syntax Text ::= r"\\\"([^\\\"\\\\]|\\\\.)*\\\"" [token]
  syntax OpenText ::= r"\\\"([^\\\"\\\\]|\\\\.)*" [token]
  syntax Newline ::= r"\\r?\\n" [token]

  syntax #Layout ::= r"(;;[^\\n\\r]*)"
                   | r"([\\ \\r\\t])"
endmodule
// SPDX-FileCopyrightText: 2026 Cyprien PIERRE
// SPDX-License-Identifier: CECILL-2.1
//
// Reading a text as a visibly pushdown automaton (chapter 5): an opening delimiter is
// pushed, with its line; a closing delimiter pops the delimiter of its pair. Each fault is
// reported with the delimiter at fault and its line:
//
// - ERR-DLM-001: an opening delimiter never closed;
// - ERR-DLM-002: a closing delimiter while no delimiter is open;
// - ERR-DLM-003: a closing delimiter of another pair than every delimiter still open;
// - ERR-DLM-004: a string never closed, which runs to the end of the text (Q-ERR-101);
// - ERR-TOP-001 to ERR-TOP-003: an opening delimiter that the grammar of the layers does
//   not admit inside the delimiter it opens in (crossings.k).
//
// Recovery (author's choice of 2026-10-26, Q-LEX-006-d: delimiters work by two): a closing
// delimiter closes the nearest open delimiter of its pair, and the delimiters opened after
// that one are reported as never closed. A closing delimiter whose pair is not open closes
// nothing. A text is well read exactly when it produces no report.

requires "stream.k"
requires "codes.k"

// The line breaks inside a string literal, which may span lines. K's STRING module is not
// imported: its string literals and the message tokens of codes.k cannot share one grammar.
// Chars is K's string sort, reached through the native functions it needs.
module LINES
  imports STREAM
  imports INT

  syntax Chars [hook(STRING.String)]
  syntax Chars ::= chars(Text) [function, total, hook(STRING.token2string)]
                 | openChars(OpenText) [function, total, hook(STRING.token2string)]
                 | character(Int) [function, total, hook(STRING.chr)]
  syntax Int ::= occurrences(Chars, Chars) [function, total, hook(STRING.countAllOccurrences)]

  syntax Int ::= lineBreaks(Text) [function, total]
                | openLineBreaks(OpenText) [function, total]
  rule lineBreaks(T) => occurrences(chars(T), character(10))
  rule openLineBreaks(T) => occurrences(openChars(T), character(10))
endmodule

module BALANCE
  imports STREAM
  imports CODES
  imports LINES
  imports INT
  imports BOOL
  imports K-EQUAL

  syntax Pair ::= "square" [symbol(square)] | "paren" [symbol(paren)] | "brace" [symbol(brace)]
                | "quote" [symbol(quote)] // the double quotes of a string

  // The delimiters still open, the innermost first, each with the line where it opens.
  syntax Open ::= opened(Pair, Int) [symbol(opened)]
  syntax Opens ::= List{Open, ""} [symbol(opens)]

  // Where a fault is: the delimiter at fault and its line, or, for ERR-DLM-003, the
  // closing delimiter and the innermost open delimiter it meets.
  syntax Site ::= at(Pair, Int) [symbol(at)]
                | meets(Pair, Int, Pair, Int) [symbol(meets)]

  syntax Report ::= located(Refusal, Site) [symbol(located)]
  syntax Reports ::= List{Report, ""} [symbol(reports)]

  syntax Reports ::= Reports "+++" Reports [function, total, right]
  rule .Reports +++ R:Reports => R
  rule (X:Report Xs:Reports) +++ R:Reports => X (Xs +++ R)

  syntax Reports ::= read(Stream, Opens, Int) [function]
  rule read(.Stream, S, _) => unclosed(S)
  rule read(_:Newline I, S, L) => read(I, S, L +Int 1)
  rule read(T:Text I, S, L) => read(I, S, L +Int lineBreaks(T))
  rule read(T:OpenText I, S, L) => located(refuse(ERR-DLM-004), at(quote, L)) read(I, S, L +Int openLineBreaks(T))
  rule read(_:Word I, S, L) => read(I, S, L)
  rule read(`openSquare`(.KList) I, S, L) => push(I, S, L, square)
  rule read(`openParen`(.KList) I, S, L) => push(I, S, L, paren)
  rule read(`openBrace`(.KList) I, S, L) => push(I, S, L, brace)
  rule read(`disabledSquare`(.KList) I, S, L) => push(I, S, L, square)
  rule read(`disabledParen`(.KList) I, S, L) => push(I, S, L, paren)
  rule read(`disabledBrace`(.KList) I, S, L) => push(I, S, L, brace)
  rule read(`closeSquare`(.KList) I, S, L) => pop(I, S, L, square)
  rule read(`closeParen`(.KList) I, S, L) => pop(I, S, L, paren)
  rule read(`closeBrace`(.KList) I, S, L) => pop(I, S, L, brace)

  // Opening: the grammar of the layers decides whether P may open inside the innermost
  // open delimiter. A refused delimiter is still pushed, so that its contents are read.
  syntax Reports ::= push(Stream, Opens, Int, Pair) [function]
  rule push(I, S, L, P) => read(I, opened(P, L) S, L) requires admits(S, P)
  rule push(I, S, L, P) => located(refuse(crossing(S, P)), at(P, L)) read(I, opened(P, L) S, L)
    requires notBool admits(S, P)

  syntax Bool ::= admits(Opens, Pair) [function, total]
  rule admits(.Opens, _) => true
  rule admits(opened(brace, _) _, _) => true
  rule admits(opened(paren, _) _, P) => P =/=K brace
  rule admits(opened(square, _) _, P) => P ==K square

  syntax Code ::= crossing(Opens, Pair) [function]
  rule crossing(opened(square, _) _, paren) => ERR-TOP-001
  rule crossing(opened(square, _) _, brace) => ERR-TOP-002
  rule crossing(opened(paren, _) _, brace) => ERR-TOP-003

  // Closing.
  syntax Reports ::= pop(Stream, Opens, Int, Pair) [function]
  rule pop(I, opened(P, _) S, L, P) => read(I, S, L)
  rule pop(I, .Opens, L, P) => located(refuse(ERR-DLM-002), at(P, L)) read(I, .Opens, L)
  rule pop(I, opened(Q, M) S, L, P) => located(refuse(ERR-DLM-001), at(Q, M)) pop(I, S, L, P)
    requires Q =/=K P andBool stillOpen(S, P)
  rule pop(I, opened(Q, M) S, L, P) => located(refuse(ERR-DLM-003), meets(P, L, Q, M)) read(I, opened(Q, M) S, L)
    requires Q =/=K P andBool notBool stillOpen(S, P)

  syntax Bool ::= stillOpen(Opens, Pair) [function, total]
  rule stillOpen(.Opens, _) => false
  rule stillOpen(opened(Q, _) S, P) => Q ==K P orBool stillOpen(S, P)

  // At the end of the text, the delimiters still open are reported in the order they open.
  syntax Reports ::= unclosed(Opens) [function, total]
  rule unclosed(.Opens) => .Reports
  rule unclosed(opened(P, M) S) => unclosed(S) +++ located(refuse(ERR-DLM-001), at(P, M)) .Reports

  configuration <k> read($PGM:Stream, .Opens, 1) </k>
endmodule

Explorer les relations explicites de K7PL