Skip to content

Close #14: dispatch freestanding macros to host handlers; host-registered attributes (@Test/@Suite) - #19

Merged
odrobnik merged 3 commits into
mainfrom
claude/simple-macros-parsing-b89c1c
Aug 10, 2026
Merged

Close #14: dispatch freestanding macros to host handlers; host-registered attributes (@Test/@Suite)#19
odrobnik merged 3 commits into
mainfrom
claude/simple-macros-parsing-b89c1c

Conversation

@odrobnik

Copy link
Copy Markdown
Collaborator

Closes #14.

Parsing needed nothing — swift-syntax already parses #name(args…) in every position the issue cares about (top level, statement position, inside a try binding all produce MacroExpansionExprSyntax), and operator folding already reaches inside macro arguments. What was missing was evaluation, and this PR adds both halves the issue sketched.

Freestanding macros

evaluate(macroExpansion:) dispatches #name(args…) to a handler registered in the bridge table under the issue's key shape:

interpreter.registerMacro("expect") { args in  }   // bridges["macro #expect"] = .macro { … }

The handler receives each argument as a MacroArgumentlabel / value / sourceText — one struct instead of the issue's two parallel arrays, because labels turn out to matter (sourceLocation:, arguments:) and the same shape then serves attribute arguments unchanged. sourceText is the exact source spelling, so #expect(a == b) reports false and "a == b".

Host-registered attributes

interpreter.registerAttribute("Test")               // preflight no longer refuses @Test
interpreter.declarations(withAttribute: "Test")     // -> [AttributedDeclaration]
interpreter.call(decl.invocable!)                   // run one

The unsupported-attribute preflight now exempts registered names (everything else keeps failing exactly as before). Declarations carrying a registered attribute are recorded with their arguments evaluated to Values@Test("display name") arrives as a .string; implicit-member forms (.disabled("flaky"), nested .tags(.critical)) arrive as unresolved enum markers for the host to interpret, extending the defer-to-the-callee principle to attribute arguments; @Test(arguments: [1, 2, 3]) arrives labeled so the host can drive the parameterized run itself. @Test funcs carry an invocable .function; @Suite types are recorded without one.

The end-to-end test pastes the issue's target shape in and runs it unmodified:

import Testing

@Test func math() async throws {
    #expect(1 + 1 == 3)                 // recorded, run continues
    let n = try #require(Int("21"))     // unwraps
    #expect(n * 2 == 42)
}

Also: member-position macros no longer vanish

struct S { #foo("x") } used to load silently, dropping the member — the exact plausible-wrong-behavior class the preflight exists to prevent. All four member walks (struct/class/enum/extension) now refuse freestanding macros in member position loudly. The broader family of silently-dropped member declarations (nested types, typealiases, indexed subscripts) is filed separately as #18.

Out of scope (follow-ups)

  • Enumerating @Test methods inside @Suite types (top-level @Test funcs are the enumerable form for now; suites load and are recorded).
  • The richer decomposed-operand reporting (a == b → both operand values) — sourceText covers the common case, and the folded infix node makes this a straightforward later step.

Tests

17 new tests in two suites (MacroExpansionTests, HostAttributeTests) covering dispatch positions, source-text fidelity, catchability, labels, trailing closures, implicit-member deferral, parameterized invocation, re-eval replacement, and all three hard-error paths. Full suite: 558 tests in 62 suites pass, probe-conformance goldens included.

🤖 Generated with Claude Code

…ered attributes

Freestanding half: MacroExpansionExprSyntax now evaluates by dispatching
to a handler in the bridge table (keyed "macro #expect", registered via
registerMacro). The handler receives every argument evaluated *and* as
source text (MacroArgument: label / value / sourceText) — the property
that separates a macro from a function: #expect(a == b) can report
"a == b" alongside the false it received. Trailing closures fold into
the argument list; leading-dot arguments defer to the handler (the
issue #11 rule — the macro's parameter types live on the host).
A handler that records and returns .void gives #expect semantics
(record and continue); one that throws gives #require semantics — the
throw routes through callingBridge, so script do/catch and try? handle
it like any other error. Unregistered #name stays a hard error with
stock swiftc's wording ("no macro named 'expect'"), and generic
argument clauses are refused loudly.

Attached half: registerAttribute("Test") exempts an attribute from the
unsupported-attribute preflight, and declarations carrying it are
recorded: name, arguments evaluated to Values (implicit-member forms —
.disabled("flaky"), nested .tags(.critical) — arrive as unresolved
enum markers for the host to interpret), and, for functions, the bound
Function as an invocable Value. declarations(withAttribute:) enumerates
them; the new public call(_:arguments:) invokes one from host code.
Together these run the issue's target shape end-to-end: paste a Swift
Testing-style file, enumerate @test funcs, run them, collect
expectation failures with source text. @suite types are recorded
(without invocable); enumerating @test methods *inside* suite types is
follow-up scope.

Also: a freestanding macro in member position (struct S { #foo("x") })
was silently dropped by the member walks — the exact divergence class
the preflight guards against. All four walks (struct/class/enum/
extension) now refuse it loudly. The broader silent-drop of other
unrecognized member declarations is filed as #18.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f06a03a4e3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread Sources/SwiftScriptInterpreter/Execution/Interpreter+Macros.swift Outdated
odrobnik and others added 2 commits August 10, 2026 18:39
… members in macro args

The enum path now records host-registered attributes like the struct /
class / actor paths do — `@Suite enum Fixtures` was passing preflight
but silently missing from declarations(withAttribute:).

Macro arguments now evaluate through the same helper as attribute
arguments (renamed evaluateHostArgument), so call-shaped implicit
members (`#probe(.caseName(1))`) defer to the handler as unresolved
enum markers instead of erroring — previously only the bare form
(`.someCase`) deferred.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…he positioned-error model

RuntimeError.noMacro keeps its always-present offset, joining
unsupported / unknownIdentifier in positioned(at:)'s already-stamped
group; invalid / divisionByZero carry main's optional positions.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@odrobnik
odrobnik merged commit d298d01 into main Aug 10, 2026
5 checks passed
@odrobnik
odrobnik deleted the claude/simple-macros-parsing-b89c1c branch August 10, 2026 18:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Run a Swift Testing file: freestanding macros (#expect/#require) and host-declared attributes (@Test/@Suite)

1 participant