Skip to content
137 changes: 130 additions & 7 deletions src/v3/compiler/parse_parser_body.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,98 @@
// recursion + list-body emission support"). Until that lands, any `.dag` port of
// the recursive-descent algorithm routes through a hidden Rust host layer.
//

/// Host-authored names that may appear as the sole RHS identifier of a
/// `type T = U` **alias** even when `U` is not declared in the same module
/// (bootstrap / prelude spellings). Keep this list conservative: expand it
/// when integration tests surface a legitimate `type X = Builtin` alias the
/// two-pass disambiguator mis-classified as a nullary sum.
const PRELUDE_BARE_RHS_ALIAS_IDENTS: &[&str] = &[
"Bit",
"Bool",
"Char",
"Classical",
"Double",
"Float",
"Float32",
"Float64",
"Int",
"Int8",
"Int16",
"Int32",
"Int64",
"List",
"Map",
"Nat",
"Never",
"Str",
"String",
"Set",
"UInt",
"UInt8",
"UInt16",
"UInt32",
"UInt64",
"Unit",
"Vec",
"Void",
"Word8",
"Word16",
"Word32",
"Word64",
];

/// Build the identifier set for which a bare `type T = U` RHS must classify
/// as [`SurfaceItem::TypeAlias`]: prelude spellings, explicit `import … { … }`
/// names, and every `type` / `data` LHS in the module (declaration order does
/// not matter — forward aliases to sibling types stay aliases).
fn collect_bare_rhs_alias_reference_idents(items: &[SurfaceItem]) -> HashSet<String> {
let mut out = HashSet::new();
for name in PRELUDE_BARE_RHS_ALIAS_IDENTS {
out.insert((*name).to_string());
}
for item in items {
match item {
SurfaceItem::Import { names, .. } => {
for n in names {
out.insert(n.clone());
}
}
SurfaceItem::TypeRecord { name, .. }
| SurfaceItem::TypeSum { name, .. }
| SurfaceItem::TypeAlias { name, .. }
| SurfaceItem::TypeAtom { name, .. } => {
out.insert(name.clone());
}
SurfaceItem::Data { name, .. } => {
out.insert(name.clone());
}
_ => {}
}
}
out
}

pub fn parse(tokens: &[Token], file: &str) -> Result<SurfaceModule, Diagnostic> {
let pass1_items = {
let mut parser = Parser {
tokens,
pos: 0,
file,
bare_rhs_alias_reference_idents: None,
};
let mut items = Vec::new();
while !parser.at_eof() {
items.push(parser.parse_item()?);
}
items
};
let refs = collect_bare_rhs_alias_reference_idents(&pass1_items);
let mut parser = Parser {
tokens,
pos: 0,
file,
bare_rhs_alias_reference_idents: Some(refs),
};
let mut items = Vec::new();
while !parser.at_eof() {
Expand All @@ -41,6 +128,10 @@ struct Parser<'a> {
tokens: &'a [Token],
pos: usize,
file: &'a str,
/// `None` during pass 1 (bare-RHS sum disambiguation disabled). `Some` during
/// pass 2: a bare `type T = U` is [`SurfaceItem::TypeSum`] iff `U` is **not**
/// in this set (prelude + imports + module `type`/`data` LHS names).
bare_rhs_alias_reference_idents: Option<HashSet<String>>,

This comment was marked as resolved.

}

impl<'a> Parser<'a> {
Expand Down Expand Up @@ -820,10 +911,13 @@ impl<'a> Parser<'a> {
}

/// After `type Name<T> =`, decide between TypeSum (one-or-more variants
/// separated by `|`) and TypeAlias (a single type expression). A variant
/// looks like `Ident` or `Ident(payload)`. A type expression can start
/// with `Ident<...>` (parameterized), `fn(...)` (arrow), or a bare
/// `Ident` that happens not to be followed by `|`.
/// separated by `|`, or a **single** variant without a top-level `|` when
/// it opens as `Variant { ... }` / `Variant(...)` — PR-A.3 EvalStrategy
/// carrier) and TypeAlias (a single type expression). A variant looks like
/// `Ident`, `Ident(...)`, or `Ident { ... }`. A type expression can start
/// with `Ident<...>` (parameterized), `fn(...)` (arrow), or a bare `Ident`
/// at RHS end (alias to another type — **not** a nullary sum; use
/// `Variant()` for a single nullary sum variant without `|`).
///
/// Optional alias-RHS `where` (DB-11): `where <expr> [, <expr>]*` parses
/// to `SurfaceExpr` (comma-separated parts fold as left-associated `&&`).
Expand Down Expand Up @@ -944,9 +1038,12 @@ impl<'a> Parser<'a> {
Ok((Some(combined), end))
}

/// Lookahead: after `=`, is the RHS a sum (contains `|` at top level before
/// the next item boundary)? Tracks paren/brace depth so a `|` inside a
/// payload list doesn't confuse the scan.
/// Lookahead: after `=`, is the RHS a sum? True when (a) a top-level `|`
/// exists before the next item boundary, or (b) the RHS opens as
/// `Variant {` / `Variant(` at depth zero (single-variant sum without `|`).
/// Tracks paren/brace depth so a `|` inside a payload list doesn't confuse
/// the scan. [`Self::parse_sum_variants`] skips a **leading** run of `|`
/// tokens so `| A | B` and `A | B` both parse.
///
/// Do **not** treat [`TokenKind::Ident`] `inhabits` as an item boundary: it
/// can spell a sum variant / record field (see [`Self::parse_field_label`],
Expand All @@ -958,6 +1055,9 @@ impl<'a> Parser<'a> {
/// `type Name =` / `type Name<` / `type Name inhabits` (next decl) via a
/// two-token lookahead when depth is zero.
fn rhs_is_sum(&self) -> bool {
if self.rhs_opens_single_variant_sum_shape() {
return true;
}
let mut i = self.pos;
let mut depth: i32 = 0;
while i < self.tokens.len() {
Expand Down Expand Up @@ -1005,7 +1105,30 @@ impl<'a> Parser<'a> {
false
}

/// After `=`, does the RHS open as a single sum variant without a top-level
/// `|`? True for `Variant { ... }` and `Variant(...)` / `Variant()` at
/// depth zero. False for `Variant<Args>` — that begins a parameterized
/// **alias** RHS (`parse_type_expr`), not a variant payload.
fn rhs_opens_single_variant_sum_shape(&self) -> bool {
let i = self.pos;
let Some(t0) = self.tokens.get(i) else {
return false;
};
let label_ok = matches!(t0.kind, TokenKind::Ident(_))
|| soft_keyword_ident_spelling(&t0.kind).is_some();
if !label_ok {
return false;
}
match self.tokens.get(i + 1).map(|t| &t.kind) {
Some(TokenKind::LBrace) | Some(TokenKind::LParen) => true,
_ => false,
}
}

fn parse_sum_variants(&mut self) -> Result<Vec<SurfaceVariant>, Diagnostic> {
while matches!(self.peek().kind, TokenKind::Pipe) {
self.bump();
}
let mut variants = vec![self.parse_variant()?];
while matches!(self.peek().kind, TokenKind::Pipe) {
self.bump();
Expand Down
46 changes: 39 additions & 7 deletions src/v3/compiler/src/parse_generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -859,10 +859,13 @@ impl<'a> Parser<'a> {
}

/// After `type Name<T> =`, decide between TypeSum (one-or-more variants
/// separated by `|`) and TypeAlias (a single type expression). A variant
/// looks like `Ident` or `Ident(payload)`. A type expression can start
/// with `Ident<...>` (parameterized), `fn(...)` (arrow), or a bare
/// `Ident` that happens not to be followed by `|`.
/// separated by `|`, or a **single** variant without a top-level `|` when
/// it opens as `Variant { ... }` / `Variant(...)` — PR-A.3 EvalStrategy
/// carrier) and TypeAlias (a single type expression). A variant looks like
/// `Ident`, `Ident(...)`, or `Ident { ... }`. A type expression can start
/// with `Ident<...>` (parameterized), `fn(...)` (arrow), or a bare `Ident`
/// at RHS end (alias to another type — **not** a nullary sum; use
/// `Variant()` for a single nullary sum variant without `|`).
///
/// Optional alias-RHS `where` (DB-11): `where <expr> [, <expr>]*` parses
/// to `SurfaceExpr` (comma-separated parts fold as left-associated `&&`).
Expand Down Expand Up @@ -983,9 +986,12 @@ impl<'a> Parser<'a> {
Ok((Some(combined), end))
}

/// Lookahead: after `=`, is the RHS a sum (contains `|` at top level before
/// the next item boundary)? Tracks paren/brace depth so a `|` inside a
/// payload list doesn't confuse the scan.
/// Lookahead: after `=`, is the RHS a sum? True when (a) a top-level `|`
/// exists before the next item boundary, or (b) the RHS opens as
/// `Variant {` / `Variant(` at depth zero (single-variant sum without `|`).
/// Tracks paren/brace depth so a `|` inside a payload list doesn't confuse
/// the scan. [`Self::parse_sum_variants`] skips a **leading** run of `|`
/// tokens so `| A | B` and `A | B` both parse.
///
/// Do **not** treat [`TokenKind::Ident`] `inhabits` as an item boundary: it
/// can spell a sum variant / record field (see [`Self::parse_field_label`],
Expand All @@ -997,6 +1003,9 @@ impl<'a> Parser<'a> {
/// `type Name =` / `type Name<` / `type Name inhabits` (next decl) via a
/// two-token lookahead when depth is zero.
fn rhs_is_sum(&self) -> bool {
if self.rhs_opens_single_variant_sum_shape() {
return true;
}
let mut i = self.pos;
let mut depth: i32 = 0;
while i < self.tokens.len() {
Expand Down Expand Up @@ -1046,7 +1055,30 @@ impl<'a> Parser<'a> {
false
}

/// After `=`, does the RHS open as a single sum variant without a top-level
/// `|`? True for `Variant { ... }` and `Variant(...)` / `Variant()` at
/// depth zero. False for `Variant<Args>` — that begins a parameterized
/// **alias** RHS (`parse_type_expr`), not a variant payload.
fn rhs_opens_single_variant_sum_shape(&self) -> bool {
let i = self.pos;
let Some(t0) = self.tokens.get(i) else {
return false;
};
let label_ok = matches!(t0.kind, TokenKind::Ident(_))
|| soft_keyword_ident_spelling(&t0.kind).is_some();
if !label_ok {
return false;
}
match self.tokens.get(i + 1).map(|t| &t.kind) {
Some(TokenKind::LBrace) | Some(TokenKind::LParen) => true,
_ => false,
}
}

fn parse_sum_variants(&mut self) -> Result<Vec<SurfaceVariant>, Diagnostic> {
while matches!(self.peek().kind, TokenKind::Pipe) {
self.bump();
}
let mut variants = vec![self.parse_variant()?];
while matches!(self.peek().kind, TokenKind::Pipe) {
self.bump();
Expand Down
3 changes: 2 additions & 1 deletion src/v3/compiler/src/regen_parse_emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ fn emit_parse_module(parser_body: &str) -> String {
BinaryOpLevel, BracketRole, ItemDispatchKind, PrimaryAtomClass, PrimaryPrefixDispatch};\n",
);
out.push_str("use crate::tokenize::{Token, TokenKind};\n");
out.push_str("use crate::operators::{LogicalOp, OperatorKind};\n\n");
out.push_str("use crate::operators::{LogicalOp, OperatorKind};\n");
out.push_str("use std::collections::HashSet;\n\n");

This comment was marked as resolved.

out.push_str(
r#"impl SurfaceType {
pub fn span(&self) -> &SourceSpan {
Expand Down
55 changes: 55 additions & 0 deletions src/v3/compiler/tests/integration/m2_substrate_inhabitance_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1640,6 +1640,61 @@ fn parse_sum_type_first_variant_may_be_named_type_keyword() {
}
}

/// PR-A.3: single-variant sum with record payload — no top-level `|` before `{`.
#[test]
fn parse_single_variant_sum_record_payload_without_pipe() {
let source = concat!(
"type EvalStrategy = ApplicativeOrder { input_order: InputEvaluationOrder }\n",
"type InputEvaluationOrder = LeftFirst ()\n",
);
let tokens = tokenize_for_test(source, "pr_a3_eval_strategy.v3").expect("tokenize");
let parsed = parse_for_test(&tokens, "pr_a3_eval_strategy.v3").expect("parse");
let mirrored: &parse_surface::SurfaceModule = &parsed;
assert_eq!(mirrored.items.len(), 2);
match &mirrored.items[0] {
parse_surface::SurfaceItem::TypeSum { name, variants, .. } => {
assert_eq!(name, "EvalStrategy");
assert_eq!(variants.len(), 1);
assert_eq!(variants[0].name, "ApplicativeOrder");
assert!(matches!(
&variants[0].payload,
parse_surface::VariantPayload::Record(fields)
if fields.len() == 1 && fields[0].name == "input_order"
));
}
other => panic!("expected TypeSum EvalStrategy, got {other:?}"),
}
match &mirrored.items[1] {
parse_surface::SurfaceItem::TypeSum { name, variants, .. } => {
assert_eq!(name, "InputEvaluationOrder");
assert_eq!(variants.len(), 1);
assert_eq!(variants[0].name, "LeftFirst");
assert!(matches!(
&variants[0].payload,
parse_surface::VariantPayload::Positional(ps) if ps.is_empty()
));
}
other => panic!("expected TypeSum InputEvaluationOrder, got {other:?}"),
}
}

/// Optional leading `|` before the first variant (same sum path as `A | B`).
#[test]
fn parse_sum_type_optional_leading_pipe_before_first_variant() {
let source = "type T = | Only\n";
let tokens = tokenize_for_test(source, "leading_pipe_sum.v3").expect("tokenize");
let parsed = parse_for_test(&tokens, "leading_pipe_sum.v3").expect("parse");
let mirrored: &parse_surface::SurfaceModule = &parsed;
match &mirrored.items[0] {
parse_surface::SurfaceItem::TypeSum { name, variants, .. } => {
assert_eq!(name, "T");
assert_eq!(variants.len(), 1);
assert_eq!(variants[0].name, "Only");
}
other => panic!("expected TypeSum, got {other:?}"),
}
}

/// Regression: `type … inhabits … =` is v3 surface-only (std `types.dag` stays
/// v2-shaped); this pins the parser + `rhs_is_sum` lookahead for the clause.
#[test]
Expand Down
Loading