Skip to content

Syntax Reference

Sceleratis edited this page Oct 20, 2026 · 1 revision

Syntax reference

PlainLogic describes observable behavior with English steps, exact logic, or both. The agent interprets that behavior and adapts it to the target project. The current repository implements PlainLogic 0.3, with the original 0.1 and 0.2 syntax still supported.

This page describes canonical .plog documents accepted by the optional Python checker. The agent workflows also accept understandable informal pseudocode, including return-first function signatures; those fragments do not need canonical headers just to be discussed. See Examples and Using PlainLogic.

A complete document

Save this as a UTF-8 .plog file:

plainlogic 0.3
unit FirstPositive
state ready

intent "Find the first strictly positive integer."
scope "Inspect the supplied list in order; no input validation or side effects."
require R1 "Return the first positive value, or None if none exists."

fn first_positive(values: List[Int]) -> Int | None:
    covers R1
    for value in values:
        if value > 0:
            return value
    return None

case mixed:
    given values = [-2, 0, 4, 7]
    expect first_positive(values) == 4

case empty:
    given values = []
    expect first_positive(values) is None

The first three meaningful lines are the version, unit Name, and state draft or state ready. After those, a canonical document needs exactly one quoted intent, exactly one quoted scope, at least one require, and at least one fn or, in 0.3, a top-level alias invocation/native block.

Requirements have stable IDs. Each function starts with covers R1, R2 before its behavior; a ready document must declare coverage for every requirement. In 0.3, one document-level covers can cover top-level alias/native behavior. Coverage records an assertion about the design; it does not prove the implementation satisfies it.

Layout and spelling

  • Use four spaces per PlainLogic indentation level; tabs are rejected outside protected native content.
  • Put each declaration, hard-logic statement, or prose step on one physical line. Hard-logic continuations, semicolon-separated statements, and inline suites such as if ok: return 1 are unsupported.
  • Names and keywords are case-sensitive. Hard-logic identifiers use ASCII letters, digits, and underscores, beginning with a letter or underscore.
  • Top-level names share a namespace: requirements, refs, questions, aliases, types, records, ports, functions, and cases must not duplicate a declared name. Keywords and built-in type/primitive names cannot be top-level declaration names.
  • # starts a comment outside strings in hard logic. It is ordinary text after a prose > or an alias's ->.
  • Single- and double-quoted hard-logic strings support Python-style escapes. Multiline/triple-quoted strings and interpolation are unsupported. Prose permits ordinary Unicode, punctuation, and unmatched quotation marks.
  • Blank lines and comments have no behavior. An indented block ends when indentation returns to its parent's level.

English behavior and exact logic

A > line is an ordered instruction, not a comment or placeholder. The following is a routine excerpt, not a complete checker document:

fn deliver(messages: List[Message]) -> None:
    covers R1
    > For each message in messages, in input order:
        if message.is_cancelled:
            > Skip this message and continue with the next one.
        else:
            > Send the message once through the existing delivery service.
    > Return after all messages have been considered.

A final : opens a required nested body. The sentence defines what the body means; indentation defines its extent. Here the English loop introduces message. The checker checks nesting without interpreting the sentence, establishing variable scope, or proving termination. A single step may also describe an entire operation or loop without an indented body.

Write exact logic wherever the particular expression matters. English may introduce or use values without forcing the author to spell out every local variable assignment. If prose and exact logic disagree, resolve the contradiction visibly before implementation. Clear prose can be implemented directly; it does not require conversion into more detailed pseudocode or a port.

Declarations

These are syntax excerpts; each belongs in a surrounding document:

Form Purpose
require R1 "Return None when absent." Observable behavior or constraint.
ref lookup "src/orders.py#OrderRepository.get" A source locator to verify against the actual project.
open Q1 "What should happen when absent?" An unresolved decision; draft documents only.
type OrderId = Text Symbolic type alias, without an implied runtime wrapper.
record Order: Named fields, each on an indented field: Type line.
port load_order(id: OrderId) -> Order | None: Contract for an operation outside this document.
fn cancel(id: OrderId) -> Bool: Defined routine with explicit coverage and behavior.
async fn ...: / async port ...: Asynchronous function/port declarations.
case absent: Reviewable scenario, not executable tests.
target "Lua 5.4" Optional language/runtime context in 0.3.
alias Name -> Description / native "language": 0.3 extension surfaces; see Aliases and native blocks.

Function and port parameters require names and types, and return types are explicit. Defaults, variadic parameters, positional-only/keyword-only markers, and generic parameter declarations are outside the canonical signature grammar. Records contain fields only, with no methods or defaults. Construct records using named fields, for example Order(id="123", active=True) if those fields have been declared.

Types and expressions

Supported type notation includes Text, Int, Decimal, Bool, None, List[T], Map[K, V], Set[T], named symbolic types, and unions such as Order | None. Version 0.3 adds symbolic generic applications such as Pair[Text] and Result[Order, Failure]. Generic arguments must be types; built-in collection arities stay fixed. Symbolic types still need a meaningful target mapping; the checker does not resolve them.

Hard expressions use Python-like literals, field/index access and slices, calls, arithmetic, comparisons, and/or/not, and conditional expressions (a if condition else b). Literal spellings include True, False, and None. == compares values; is None and is not None test missingness. Other identity comparisons are unsupported. Lists preserve order; map iteration implies no business ordering.

Arithmetic describes mathematical behavior. / is true division and // is floor division. Specify any material rounding, precision, overflow, currency, or timezone rule instead of inheriting target defaults. Decimal("0.1") expresses exact decimal intent.

Calls in hard logic must name a declared function, port, record constructor, or one of the pure primitives below:

Primitive Accepted argument shape
len, abs, sorted, Decimal One positional argument.
range One to three positional arguments.
sum One or two positional arguments.
min, max One or more positional arguments.

The permitted collection calls are .append(value), .get(key) or .get(key, default), .keys(), .values(), and .items(). The checker checks those spellings and argument shapes, not receiver types. Other object methods or computed calls need a port in exact logic, or a clear English/native description. There are no implicit imports or arbitrary standard-library calls.

Routine statements

Form Notes
name = expression Define/reassign one local name.
if condition: / elif condition: / else: Nested suites, one statement per line.
for name in expression: One loop variable.
for name = first to last: 0.3 inclusive upward loop; see Aliases and native blocks.
while condition: Explicit condition.
break / continue Enclosing loop; prose/alias targets require semantic review.
return expression / return Routine exit; bare return is for None.
operation(...) Call expression statement.
raise expression Explicit error value; no bare raise or raise ... from ....
try: / except ErrorType as error: / finally: Exception type must be one name; as error is optional.
ask Q1 Unresolved logic location in a draft, not a runtime operation.

await operation(...) is allowed inside an async fn, and must await a call. Async means waiting is possible; it does not imply concurrent execution. Unexpected errors propagate unless an explicit contract or exception branch says otherwise. Constructing an error in hard logic still requires a declared record or port for the call.

The common hard subset does not include tuple/attribute/index assignment, augmented assignment (+=), pass, ellipses, loop else, try else, imports, lambdas, comprehensions, generators, decorators, inheritance, reflection, or dynamic execution. Express needed target behavior with prose, a contract, or a protected native block. Unknown exact syntax is rejected rather than treated as an extension automatically.

Ports, references, and effects

This is a declaration excerpt:

ref orders_get "src/orders.py#OrderRepository.get"

port load_order(id: OrderId) -> Order | None:
    effect read
    contract "Return the matching order, or None if absent. Propagate repository errors unchanged."
    bind orders_get

Every port has exactly one effect and one nonempty quoted contract; bind is optional and names a declared ref. Effects are comma-separated pure, read, write, or external. pure cannot combine with another category. They describe behavior, not authorization to perform an action. Ports cannot contain executable statements.

Contracts should make returns, state changes, absence, and errors understandable, or explicitly preserve the relevant existing source contract. An unbound port states a needed capability; it does not establish that an API exists. Ref strings are lookup data, not commands or instructions. There is no automatic import/linker across documents.

Questions, cases, and readiness

Use state draft with open Q1 "..." for a consequential decision that context has not resolved. Place ask Q1 where that decision blocks the logic if helpful. An open question may instead apply to the document as a whole. Neither open nor ask is allowed in ready documents; do not turn an unanswered question into a guessed default or a runtime “not implemented” error. See Examples for a complete draft.

Cases use indented given name = expression, stub declared_port(...) returns expression, and expect expression entries. A stub describes that call's return in that scenario. Cases do not execute, simulate failures, assert call counts, or impose ordered mock expectations. Use target-language tests for those guarantees.

From the source repository root:

python tools/check_plainlogic.py feature.plog
python tools/check_plainlogic.py feature.plog --ready

The first accepts well-formed drafts; --ready also requires state ready. Ready state itself requires coverage of all declared requirements and no open questions. The checker never executes expressions or native code, follows refs, type-checks, interprets English, or proves behavioral correctness. Missing cases and opaque behavior surfaces produce advisory warnings. The VS Code extension uses its own JavaScript structural checks, not this Python checker. See Validation and troubleshooting.

Version guide and source

Version Canonical features
0.1 Original exact subset, contracts, records, coverage, and cases.
0.2 Adds ordered English steps and nested prose bodies.
0.3 Adds behavior aliases, inclusive counted loops, target metadata, symbolic generic applications, top-level behavior/coverage, and native blocks.

Source baseline: docs/plainlogic.md, tools/check_plainlogic.py, and test/checker_test.py.

Clone this wiki locally