lang: Parse type forms in postfix brackets

8754ed5285b3ede1745dd3625dbc99e8666532258bfc846808c31ce46fa50440
Allow explicit type and region operands in postfix bracket lists.
Parse shared forms as expressions and diagnose explicit type forms
where resolution requires an index value.

Assisted-by: Codex:gpt-6
Change-Id: I01ec3c2472d2874c7240658d0161ddcd3da73e8a
Alexis Sellier committed ago 1 parent 8ffa307c
lib/std/lang/ast.rad +2 -0
817 817
    Range(Range),
818 818
    /// Array literal expression.
819 819
    ArrayLit(*[*Node]),
820 820
    /// Array repeat literal expression.
821 821
    ArrayRepeatLit(ArrayRepeatLit),
822 +
    /// Explicit type or region syntax in a bracket operand.
823 +
    BracketArgument(*Node),
822 824
    /// Postfix bracket expression.
823 825
    Bracket {
824 826
        /// Expression before the brackets.
825 827
        base: *Node,
826 828
        /// Arguments in source order.
lib/std/lang/ast/printer.rad +2 -0
344 344
        }
345 345
        case super::NodeValue::TypeBinder { name, bound } =>
346 346
            return sexpr::list(a, "binder", &[toExpr(a, name), toExprOrNull(a, bound)]),
347 347
        case super::NodeValue::BuiltinCall { kind, args } =>
348 348
            return sexpr::list(a, super::builtinText(kind), nodeListToExprs(a, args)),
349 +
        case super::NodeValue::BracketArgument(arg) =>
350 +
            return sexpr::list(a, "arg", &[toExpr(a, arg)]),
349 351
        case super::NodeValue::Bracket { base, items } => {
350 352
            let buf = try! sexpr::allocExprs(a, items.len as u32 + 1);
351 353
            set buf[0] = toExpr(a, base);
352 354
            for item, i in items {
353 355
                set buf[i + 1] = toExpr(a, item);
lib/std/lang/parser.rad +84 -1
128 128
    /// Conditional context where `{` always begins a block
129 129
    /// and `if` is reserved for guards.
130 130
    Condition,
131 131
}
132 132
133 +
/// The forms that can start an expression operand.
134 +
union OperandGrammar: Copy {
135 +
    /// Value expressions.
136 +
    Value,
137 +
    /// Value expressions and explicit type and region forms.
138 +
    Bracket,
139 +
}
140 +
133 141
/// A single parser error with location information.
134 142
export record Error: Copy {
135 143
    /// Human-readable error message.
136 144
    message: *[u8],
137 145
    /// The token where the error occurred.
194 202
    arena: ast::NodeArena,
195 203
    /// String pool used to intern identifiers and literals.
196 204
    pool: strings::Pool,
197 205
    /// Current parsing context (normal or conditional).
198 206
    context: Context,
207 +
    /// Operand forms permitted inside the current expression.
208 +
    operands: OperandGrammar,
199 209
    /// Whether comments and blank lines are kept. Set it before parsing a
200 210
    /// module. Comment text points into the module's source.
201 211
    triviaMode: TriviaMode,
202 212
    /// Trivia attached to nodes of the current module in [`TriviaMode::Keep`],
203 213
    /// ordered by node id.
234 244
        previous: scanner::invalid(0, ""),
235 245
        errors: emptyErrorList(),
236 246
        arena,
237 247
        pool: owned,
238 248
        context: Context::Normal,
249 +
        operands: OperandGrammar::Value,
239 250
        triviaMode: TriviaMode::Discard,
240 251
        trivia: &mut [],
241 252
        pending: &mut [],
242 253
        base: 0,
243 254
        closing: &mut [],
441 452
    try markBroken(p, cond, beforeIf or beforeElse, ast::BrokenSite::Chain);
442 453
443 454
    return cond;
444 455
}
445 456
457 +
/// Mark a type or region form that occurs in the bracket operand grammar.
458 +
fn bracketArgument(p: &mut Parser, arg: *ast::Node) -> *ast::Node
459 +
    throws (AllocError)
460 +
{
461 +
    return try node(p, ast::NodeValue::BracketArgument(arg));
462 +
}
463 +
446 464
/// Parse one bracket item, including a range with no start.
447 465
fn parseBracketItem(p: &mut Parser) -> *ast::Node
448 466
    throws (ParseError, AllocError)
449 467
{
450 468
    if not try consume(p, scanner::TokenKind::DotDot) {
463 481
fn parseBracket(p: &mut Parser, base: *ast::Node) -> *ast::Node
464 482
    throws (ParseError, AllocError)
465 483
{
466 484
    try advance(p);
467 485
    let mut outer = openList(p);
486 +
    let saved = p.operands;
487 +
    set p.operands = OperandGrammar::Bracket;
468 488
    let items = try parseItems(
469 489
        p, scanner::TokenKind::RBracket, parseBracketItem, &mut outer
470 -
    );
490 +
    ) catch err as ParseError {
491 +
        set p.operands = saved;
492 +
        throw err;
493 +
    } catch err as AllocError {
494 +
        set p.operands = saved;
495 +
        throw err;
496 +
    };
497 +
    set p.operands = saved;
471 498
    try closeSoftList(p, outer, &items[..]);
472 499
    try expect(p, scanner::TokenKind::RBracket, "expected `]` after bracket items");
473 500
    let bracket: *ast::Node = try node(p, ast::NodeValue::Bracket { base, items });
474 501
    try attachClosing(p, bracket);
475 502
    return bracket;
553 580
            let value = try parseUnaryExpr(p);
554 581
            return try nodeUnary(p, ast::UnaryOp::BitNot, value);
555 582
        }
556 583
        case scanner::TokenKind::Star => {
557 584
            try advance(p);
585 +
            if p.operands == OperandGrammar::Bracket {
586 +
                if try consume(p, scanner::TokenKind::Unsafe) {
587 +
                    let pointer = try parsePointerLikeType(p, types::PointerClass::Unsafe);
588 +
                    return try bracketArgument(p, pointer);
589 +
                }
590 +
                if check(p, scanner::TokenKind::Mut) or check(p, scanner::TokenKind::Opaque) {
591 +
                    let pointer = try parsePointerLikeType(p, types::PointerClass::Owned);
592 +
                    return try bracketArgument(p, pointer);
593 +
                }
594 +
            }
558 595
            let value = try parseUnaryExpr(p);
559 596
            return try node(p, ast::NodeValue::Deref(value));
560 597
        }
561 598
        case scanner::TokenKind::Amp => {
562 599
            try advance(p);
600 +
            if p.operands == OperandGrammar::Bracket and check(p, scanner::TokenKind::Region) {
601 +
                let pointer = try parsePointerLikeType(p, types::PointerClass::Ref);
602 +
                return try bracketArgument(p, pointer);
603 +
            }
563 604
            let mutable = try consume(p, scanner::TokenKind::Mut);
605 +
            if p.operands == OperandGrammar::Bracket and check(p, scanner::TokenKind::Opaque) {
606 +
                let pointer = try parsePointerTarget(p, types::PointerClass::Ref, mutable, nil);
607 +
                return try bracketArgument(p, pointer);
608 +
            }
564 609
            let target = try parseUnaryExpr(p);
565 610
            return try node(p, ast::NodeValue::AddressOf({ target: target, mutable: mutable }));
566 611
        }
567 612
        else => {
568 613
            // Parse a primary expression (leaf nodes followed by postfix operators).
747 792
            if p.context <> Context::Normal {
748 793
                throw failParsing(p, "unexpected `{` in this context");
749 794
            }
750 795
            return try parseRecordLit(p, nil);
751 796
        }
797 +
        case
798 +
            scanner::TokenKind::Question,
799 +
            scanner::TokenKind::Fn,
800 +
            scanner::TokenKind::Unsafe,
801 +
            scanner::TokenKind::Opaque,
802 +
            scanner::TokenKind::Bool,
803 +
            scanner::TokenKind::U8,
804 +
            scanner::TokenKind::U16,
805 +
            scanner::TokenKind::U32,
806 +
            scanner::TokenKind::U64,
807 +
            scanner::TokenKind::I8,
808 +
            scanner::TokenKind::I16,
809 +
            scanner::TokenKind::I32,
810 +
            scanner::TokenKind::I64 =>
811 +
        {
812 +
            if p.operands <> OperandGrammar::Bracket {
813 +
                throw failParsing(p, "expected expression");
814 +
            }
815 +
            let type = try parseType(p);
816 +
            return try bracketArgument(p, type);
817 +
        }
818 +
        case scanner::TokenKind::Region => {
819 +
            if p.operands <> OperandGrammar::Bracket {
820 +
                throw failParsing(p, "expected expression");
821 +
            }
822 +
            let region = try parseRegion(p);
823 +
            return try bracketArgument(p, region);
824 +
        }
752 825
        else => {
753 826
            throw failParsing(p, "expected expression");
754 827
        }
755 828
    }
756 829
}
2523 2596
    let mut region: ?*ast::Node = nil;
2524 2597
    if class == types::PointerClass::Ref and p.current.kind == scanner::TokenKind::Region {
2525 2598
        set region = try parseRegion(p);
2526 2599
    }
2527 2600
    let mutable = try consume(p, scanner::TokenKind::Mut);
2601 +
    return try parsePointerTarget(p, class, mutable, region);
2602 +
}
2528 2603
2604 +
/// Parse the target of a pointer-like type after its prefix.
2605 +
fn parsePointerTarget(
2606 +
    p: &mut Parser,
2607 +
    class: types::PointerClass,
2608 +
    mutable: bool,
2609 +
    region: ?*ast::Node
2610 +
) -> *ast::Node throws (ParseError, AllocError) {
2529 2611
    if try consume(p, scanner::TokenKind::LBracket) {
2530 2612
        let itemType = try parseType(p);
2531 2613
2532 2614
        // `[T; N]` after a prefix is a pointer to an array, `[T]` a slice.
2533 2615
        if try consume(p, scanner::TokenKind::Semicolon) {
3000 3082
    set p.scanner = scanner::scanner(sourceLoc, input, &mut p.pool);
3001 3083
    set p.current = scanner::invalid(0, "");
3002 3084
    set p.previous = scanner::invalid(0, "");
3003 3085
    set p.errors = emptyErrorList();
3004 3086
    set p.context = Context::Normal;
3087 +
    set p.operands = OperandGrammar::Value;
3005 3088
    set p.trivia = &mut [];
3006 3089
    set p.pending = &mut [];
3007 3090
    set p.base = 0;
3008 3091
    set p.closing = &mut [];
3009 3092
}
lib/std/lang/parser/tests.rad +16 -0
3946 3946
    try expectIdent(path.parent, "widgets");
3947 3947
    try expectIdent(path.child, "Widget");
3948 3948
    try testing::expect(items.len == 1);
3949 3949
    try expectTypeIdent(items[0], "M");
3950 3950
}
3951 +
3952 +
/// Check explicit type forms and common subscript syntax in bracket items.
3953 +
@test unsafe fn testParseBracketTypeForms() throws (testing::TestError) {
3954 +
    for source in [
3955 +
        "mem::sizeOf[[u32; 4]]()",
3956 +
        "make[?T, fn(T) -> T, &'r T, *mut [T], &mut opaque Widget[M]]",
3957 +
        "View['r, Box[T]] { item: x }",
3958 +
        "handlers[i + 1](event)",
3959 +
        "&values[lo..hi]",
3960 +
    ] {
3961 +
        let mut parser = mkParser(source);
3962 +
        try super::parseValue(&mut parser, scanner::SourceLoc::String, source) catch {
3963 +
            throw testing::TestError::Failed;
3964 +
        };
3965 +
    }
3966 +
}
lib/std/lang/pretty.rad +2 -0
1290 1290
            try add(a, &mut kids, SOFT_INDENT, try group(a, nil, inner));
1291 1291
            try punct(a, &mut kids, SOFT, "]");
1292 1292
            let forced = takeMark(p, node, ast::BrokenSite::List);
1293 1293
            return try forceBroken(a, try group(a, node, kids), forced);
1294 1294
        }
1295 +
        case ast::NodeValue::BracketArgument(arg) =>
1296 +
            return try expr(a, p, arg, ctx),
1295 1297
        case ast::NodeValue::Bracket { base, items } => {
1296 1298
            try putOperand(
1297 1299
                a, p, &mut kids, NONE, base, ctx, LEVEL_POSTFIX
1298 1300
            );
1299 1301
            let list = SoftSpec {
lib/std/lang/resolver.rad +7 -1
632 632
export union BracketError: Copy {
633 633
    /// The base must be an array or slice.
634 634
    Base,
635 635
    /// A subscript must have exactly one index or range.
636 636
    Arity,
637 +
    /// A type or region occurs in a value expression.
638 +
    ExpectedValue,
637 639
    /// The compiler cannot resolve a generic declaration or application.
638 640
    Generic,
639 641
}
640 642
641 643
/// High-level classification for semantic diagnostics.
3557 3559
3558 3560
            setNodeSymbol(self, node, sym);
3559 3561
3560 3562
            return ty;
3561 3563
        }
3562 -
        else => panic "resolveTypeName: unsupported node value",
3564 +
        case ast::NodeValue::Bracket { .. } =>
3565 +
            throw emitError(self, node, ErrorKind::Bracket(BracketError::Generic)),
3566 +
        else => throw emitError(self, node, ErrorKind::ExpectedIdentifier),
3563 3567
    }
3564 3568
}
3565 3569
3566 3570
/// Visit a top-level declaration in the declaration phase.
3567 3571
/// This binds all names and analyzes signatures, types, and initializers.
3821 3825
            return try checkConstructed(self, node, try resolveRecordLit(self, node, &lit, hint)),
3822 3826
        case ast::NodeValue::ArrayLit(items) =>
3823 3827
            return try checkConstructed(self, node, try resolveArrayLit(self, node, items, hint)),
3824 3828
        case ast::NodeValue::ArrayRepeatLit(lit) =>
3825 3829
            return try checkConstructed(self, node, try resolveArrayRepeat(self, node, lit, hint)),
3830 +
        case ast::NodeValue::BracketArgument(_) =>
3831 +
            throw emitError(self, node, ErrorKind::Bracket(BracketError::ExpectedValue)),
3826 3832
        case ast::NodeValue::Bracket { base, items } =>
3827 3833
            return try resolveBracket(self, node, base, items),
3828 3834
        case ast::NodeValue::ScopeAccess(access) =>
3829 3835
            return try resolveScopeAccess(self, node, access),
3830 3836
        case ast::NodeValue::AddressOf(addr) => return try resolveAddressOf(self, node, addr, hint),
lib/std/lang/resolver/printer.rad +2 -0
515 515
            match error {
516 516
                case super::BracketError::Base =>
517 517
                    io::print("expected array or slice"),
518 518
                case super::BracketError::Arity =>
519 519
                    io::print("a subscript requires exactly one index or range"),
520 +
                case super::BracketError::ExpectedValue =>
521 +
                    io::print("expected a value, found a type or region"),
520 522
                case super::BracketError::Generic =>
521 523
                    io::print("generic declarations and types cannot be resolved"),
522 524
            }
523 525
        }
524 526
        case super::ErrorKind::InvalidAlignmentValue(val) => {
lib/std/lang/resolver/tests/core.rad +23 -0
1647 1647
            resolver::BracketError::Arity
1648 1648
        ));
1649 1649
    }
1650 1650
}
1651 1651
1652 +
/// Check that type and region operands do not supply index or range values.
1653 +
@test unsafe fn testResolveBracketExpectedValue() throws (testing::TestError) {
1654 +
    for program in [
1655 +
        @embed("lang/resolver/tests/fixtures/subscript/type_index.rad"),
1656 +
        @embed("lang/resolver/tests/fixtures/subscript/type_in_index.rad"),
1657 +
        @embed("lang/resolver/tests/fixtures/subscript/type_range.rad"),
1658 +
        @embed("lang/resolver/tests/fixtures/subscript/region_index.rad"),
1659 +
    ] {
1660 +
        let mut a = testResolver();
1661 +
        let result = try resolveProgramStr(&mut a, program);
1662 +
        try expectErrorKind(&result, resolver::ErrorKind::Bracket(
1663 +
            resolver::BracketError::ExpectedValue
1664 +
        ));
1665 +
    }
1666 +
}
1667 +
1668 +
/// Check that a record constructor with unresolved type arguments reports an error.
1669 +
@test unsafe fn testResolveUnresolvedRecordApplication() throws (testing::TestError) {
1670 +
    let mut a = testResolver();
1671 +
    let result = try resolveProgramStr(&mut a, "record R { x: u32 } R[u32] { x: 3 };");
1672 +
    try expectErrorKind(&result, resolver::ErrorKind::Bracket(resolver::BracketError::Generic));
1673 +
}
1674 +
1652 1675
@test unsafe fn testResolveSliceFieldUnknown() throws (testing::TestError) {
1653 1676
    let mut a = testResolver();
1654 1677
    let program = "let xs: [i32; 2] = [1, 2]; (&xs[0..]).unknown;";
1655 1678
    let result = try resolveProgramStr(&mut a, program);
1656 1679
    try expectErrorKind(&result, resolver::ErrorKind::SliceFieldUnknown("unknown"));
lib/std/lang/resolver/tests/fixtures/subscript/region_index.rad added +2 -0
1 +
let xs: [u32; 2] = [1, 2];
2 +
xs['r];
lib/std/lang/resolver/tests/fixtures/subscript/type_in_index.rad added +2 -0
1 +
let xs: [u32; 2] = [1, 2];
2 +
xs[1 + u32];
lib/std/lang/resolver/tests/fixtures/subscript/type_index.rad added +2 -0
1 +
let xs: [u32; 2] = [1, 2];
2 +
xs[u32];
lib/std/lang/resolver/tests/fixtures/subscript/type_range.rad added +2 -0
1 +
let xs: [u32; 2] = [1, 2];
2 +
&xs[.. u32];
lib/std/std.manifest +4 -0
129 129
    embed: [
130 130
        "lang/manifest/tests/fixtures/kernel.manifest",
131 131
        "lang/manifest/tests/fixtures/module_order.manifest",
132 132
        "lang/resolver/tests/fixtures/subscript/empty.rad",
133 133
        "lang/resolver/tests/fixtures/subscript/range_and_index.rad",
134 +
        "lang/resolver/tests/fixtures/subscript/region_index.rad",
134 135
        "lang/resolver/tests/fixtures/subscript/store_two_indices.rad",
136 +
        "lang/resolver/tests/fixtures/subscript/type_in_index.rad",
137 +
        "lang/resolver/tests/fixtures/subscript/type_index.rad",
138 +
        "lang/resolver/tests/fixtures/subscript/type_range.rad",
135 139
    ],
136 140
}