Implement super-traits

2c024af02ee9bf52531e652943ec0b9d915d1c98ef45192b70a8ea7cceb0b711
Alexis Sellier committed ago 1 parent 621d59be
lib/std/arch/rv64/tests/trait.supertrait.rad added +114 -0
1 +
//! Test supertrait bounds: a trait that requires its implementors to also
2 +
//! implement another trait.
3 +
//!
4 +
//! Exercises: trait Reader with a `read` method, trait Writer with a `write`
5 +
//! method, and trait ReadWriter: Reader + Writer that combines both.
6 +
//! A Socket type implements all three. Coercing a `*opaque ReadWriter` to
7 +
//! `*opaque Reader` or `*opaque Writer` should work, and dispatching through
8 +
//! any of the three trait objects should call the correct methods.
9 +
10 +
trait Reader {
11 +
    fn (*mut Reader) read(buf: *mut [u8]) -> i32;
12 +
}
13 +
14 +
trait Writer {
15 +
    fn (*mut Writer) write(data: *[u8]) -> i32;
16 +
}
17 +
18 +
trait ReadWriter: Reader + Writer {
19 +
    fn (*mut ReadWriter) flush() -> i32;
20 +
}
21 +
22 +
record Socket {
23 +
    rbuf: [u8; 32],
24 +
    rpos: i32,
25 +
    rlen: i32,
26 +
    wbuf: [u8; 32],
27 +
    wpos: i32,
28 +
}
29 +
30 +
instance Reader for Socket {
31 +
    fn (s: *mut Socket) read(buf: *mut [u8]) -> i32 {
32 +
        let mut i: u32 = 0;
33 +
        while i < buf.len and s.rpos < s.rlen {
34 +
            buf[i] = s.rbuf[s.rpos as u32];
35 +
            s.rpos = s.rpos + 1;
36 +
            i = i + 1;
37 +
        }
38 +
        return i as i32;
39 +
    }
40 +
}
41 +
42 +
instance Writer for Socket {
43 +
    fn (s: *mut Socket) write(data: *[u8]) -> i32 {
44 +
        let mut i: u32 = 0;
45 +
        while i < data.len {
46 +
            if s.wpos >= 32 {
47 +
                return s.wpos;
48 +
            }
49 +
            s.wbuf[s.wpos as u32] = data[i];
50 +
            s.wpos = s.wpos + 1;
51 +
            i = i + 1;
52 +
        }
53 +
        return s.wpos;
54 +
    }
55 +
}
56 +
57 +
instance ReadWriter for Socket {
58 +
    fn (s: *mut Socket) flush() -> i32 {
59 +
        let pos = s.wpos;
60 +
        s.wpos = 0;
61 +
        return pos;
62 +
    }
63 +
}
64 +
65 +
@default fn main() -> i32 {
66 +
    let mut sock = Socket {
67 +
        rbuf: undefined,
68 +
        rpos: 0,
69 +
        rlen: 5,
70 +
        wbuf: undefined,
71 +
        wpos: 0,
72 +
    };
73 +
    // Pre-fill the read buffer with "hello".
74 +
    sock.rbuf[0] = 'h' as u8;
75 +
    sock.rbuf[1] = 'e' as u8;
76 +
    sock.rbuf[2] = 'l' as u8;
77 +
    sock.rbuf[3] = 'l' as u8;
78 +
    sock.rbuf[4] = 'o' as u8;
79 +
80 +
    // Test 1: Use as ReadWriter trait object.
81 +
    let rw: *mut opaque ReadWriter = &mut sock;
82 +
83 +
    // Test 2: Write through the ReadWriter (dispatches via Writer supertrait).
84 +
    let wn = rw.write("abc");
85 +
    if wn != 3 {
86 +
        return 1;
87 +
    }
88 +
    if sock.wpos != 3 {
89 +
        return 2;
90 +
    }
91 +
92 +
    // Test 3: Read through the ReadWriter (dispatches via Reader supertrait).
93 +
    let mut rbuf: [u8; 8] = undefined;
94 +
    let rn = rw.read(&mut rbuf[0..8]);
95 +
    if rn != 5 {
96 +
        return 3;
97 +
    }
98 +
    if rbuf[0] != 'h' as u8 {
99 +
        return 4;
100 +
    }
101 +
    if rbuf[4] != 'o' as u8 {
102 +
        return 5;
103 +
    }
104 +
105 +
    // Test 4: Call ReadWriter's own method.
106 +
    let flushed = rw.flush();
107 +
    if flushed != 3 {
108 +
        return 6;
109 +
    }
110 +
    if sock.wpos != 0 {
111 +
        return 7;
112 +
    }
113 +
    return 0;
114 +
}
lib/std/lang/ast.rad +5 -0
6 6
use std::lang::alloc;
7 7
8 8
/// Maximum number of trait methods.
9 9
pub const MAX_TRAIT_METHODS: u32 = 8;
10 10
11 +
/// Maximum number of supertraits.
12 +
pub const MAX_SUPERTRAITS: u32 = 4;
13 +
11 14
/// Arena for all parser allocations.
12 15
///
13 16
/// Uses a bump allocator for both AST nodes and node pointer arrays.
14 17
pub record NodeArena {
15 18
    /// Bump allocator for all allocations.
815 818
    CatchClause(CatchClause),
816 819
    /// Trait declaration.
817 820
    TraitDecl {
818 821
        /// Trait name identifier.
819 822
        name: *Node,
823 +
        /// Supertrait name nodes.
824 +
        supertraits: NodeList,
820 825
        /// Method signature nodes ([`TraitMethodSig`]).
821 826
        methods: NodeList,
822 827
        /// Optional attributes.
823 828
        attrs: ?Attributes,
824 829
    },
lib/std/lang/ast/printer.rad +3 -2
436 436
        }
437 437
        case super::NodeValue::UnionDeclVariant(v) => {
438 438
            return variantToExpr(a, v.name, v.type);
439 439
        }
440 440
        case super::NodeValue::ExprStmt(e) => return toExpr(a, e),
441 -
        case super::NodeValue::TraitDecl { name, methods, .. } => {
441 +
        case super::NodeValue::TraitDecl { name, supertraits, methods, .. } => {
442 442
            let children = nodeListToExprs(a, &methods);
443 -
            return sexpr::block(a, "trait", &[toExpr(a, name)], children);
443 +
            let supers = sexpr::list(a, "supertraits", nodeListToExprs(a, &supertraits));
444 +
            return sexpr::block(a, "trait", &[toExpr(a, name), supers], children);
444 445
        }
445 446
        case super::NodeValue::TraitMethodSig { name, receiver, sig } => {
446 447
            let params = sexpr::list(a, "params", nodeListToExprs(a, &sig.params));
447 448
            let ret = toExprOrNull(a, sig.returnType);
448 449
            return sexpr::list(a, "methodSig", &[toExpr(a, receiver), toExpr(a, name), params, ret]);
lib/std/lang/lower.rad +14 -1
1108 1108
1109 1109
    let tName = traitSym.name;
1110 1110
    let typeName = typeSym.name;
1111 1111
1112 1112
    // Lower each instance method as a regular function.
1113 -
    // Collect qualified names for the v-table.
1113 +
    // Collect qualified names for the v-table. Empty entries are filled
1114 +
    // later from inherited supertrait methods.
1114 1115
    let mut methodNames: [*[u8]; ast::MAX_TRAIT_METHODS] = undefined;
1116 +
    let mut methodNameSet: [bool; ast::MAX_TRAIT_METHODS] = [false; ast::MAX_TRAIT_METHODS];
1115 1117
1116 1118
    for i in 0..methods.len {
1117 1119
        let methodNode = methods.list[i];
1118 1120
        let case ast::NodeValue::InstanceMethodDecl {
1119 1121
            name, receiverName, receiverType, sig, body
1158 1160
1159 1161
        let method = resolver::findTraitMethod(traitInfo, mName)
1160 1162
            else panic "lowerInstanceDecl: method not found in trait";
1161 1163
1162 1164
        methodNames[method.index] = qualName;
1165 +
        methodNameSet[method.index] = true;
1166 +
    }
1167 +
1168 +
    // Fill inherited method slots from supertraits.
1169 +
    // These methods were already lowered as part of the supertrait instance
1170 +
    // declarations and use the same `Type::method` qualified name.
1171 +
    for i in 0..traitInfo.methodsLen {
1172 +
        if not methodNameSet[i] {
1173 +
            let mName = traitInfo.methods[i].name;
1174 +
            methodNames[i] = instanceMethodName(self, nil, typeName, mName);
1175 +
        }
1163 1176
    }
1164 1177
1165 1178
    // Create v-table in data section, used for dynamic dispatch.
1166 1179
    let vName = vtableName(self, nil, typeName, tName);
1167 1180
    let values = try! alloc::allocSlice(
lib/std/lang/parser.rad +2 -1
2311 2311
fn parseTraitDecl(p: *mut Parser, attrs: ?ast::Attributes) -> *ast::Node
2312 2312
    throws (ParseError)
2313 2313
{
2314 2314
    try expect(p, scanner::TokenKind::Trait, "expected `trait`");
2315 2315
    let name = try parseIdent(p, "expected trait name");
2316 +
    let supertraits = try parseDerives(p);
2316 2317
    try expect(p, scanner::TokenKind::LBrace, "expected `{` after trait name");
2317 2318
2318 2319
    let mut methods = ast::nodeList(p.arena, ast::MAX_TRAIT_METHODS);
2319 2320
    while not check(p, scanner::TokenKind::RBrace) and
2320 2321
          not check(p, scanner::TokenKind::Eof)
2322 2323
        let method = try parseTraitMethodSig(p);
2323 2324
        ast::nodeListPush(&mut methods, method);
2324 2325
    }
2325 2326
    try expect(p, scanner::TokenKind::RBrace, "expected `}` after trait methods");
2326 2327
2327 -
    return node(p, ast::NodeValue::TraitDecl { name, methods, attrs });
2328 +
    return node(p, ast::NodeValue::TraitDecl { name, supertraits, methods, attrs });
2328 2329
}
2329 2330
2330 2331
/// Parse a trait method signature.
2331 2332
/// Syntax: `fn (*Trait) fnord(<params>) -> ReturnType;`
2332 2333
fn parseTraitMethodSig(p: *mut Parser) -> *ast::Node
lib/std/lang/resolver.rad +68 -10
48 48
49 49
/// Trait definition stored in the resolver.
50 50
pub record TraitType {
51 51
    /// Trait name.
52 52
    name: *[u8],
53 -
    /// Method signatures.
53 +
    /// Method signatures, including from supertraits.
54 54
    methods: [TraitMethod; ast::MAX_TRAIT_METHODS],
55 55
    /// Number of methods.
56 56
    methodsLen: u32,
57 +
    /// Supertraits that must also be implemented.
58 +
    supertraits: [*TraitType; ast::MAX_SUPERTRAITS],
59 +
    /// Number of supertraits.
60 +
    supertraitsLen: u32,
57 61
}
58 62
59 63
/// A single method signature within a trait.
60 64
pub record TraitMethod {
61 65
    /// Method name.
565 569
    FnParamOverflow(CountMismatch),
566 570
    /// Function declaration has too many throws.
567 571
    FnThrowOverflow(CountMismatch),
568 572
    /// Trait declaration has too many methods.
569 573
    TraitMethodOverflow(CountMismatch),
574 +
    /// Instance declaration is missing a required supertrait instance.
575 +
    MissingSupertraitInstance(*[u8]),
570 576
    /// Internal error.
571 577
    Internal,
572 578
}
573 579
574 580
/// Fixed-capacity diagnostic sink.
3258 3264
3259 3265
/// Allocate a trait type descriptor and return a pointer to it.
3260 3266
fn allocTraitType(self: *mut Resolver, name: *[u8]) -> *mut TraitType {
3261 3267
    let p = try! alloc::alloc(&mut self.arena, @sizeOf(TraitType), @alignOf(TraitType));
3262 3268
    let entry = p as *mut TraitType;
3263 -
    *entry = TraitType { name, methods: undefined, methodsLen: 0 };
3269 +
    *entry = TraitType { name, methods: undefined, methodsLen: 0, supertraits: undefined, supertraitsLen: 0 };
3264 3270
3265 3271
    return entry;
3266 3272
}
3267 3273
3268 3274
/// Bind a trait name in the current scope.
3291 3297
        }
3292 3298
    }
3293 3299
    return nil;
3294 3300
}
3295 3301
3296 -
/// Resolve a trait declaration body, ie. the method signatures.
3297 -
fn resolveTraitBody(self: *mut Resolver, node: *ast::Node, methods: *ast::NodeList)
3302 +
/// Resolve a trait declaration body: supertrait methods, then own methods.
3303 +
fn resolveTraitBody(self: *mut Resolver, node: *ast::Node, supertraits: *ast::NodeList, methods: *ast::NodeList)
3298 3304
    throws (ResolveError)
3299 3305
{
3300 3306
    let sym = symbolFor(self, node)
3301 3307
        else return;
3302 3308
    let case SymbolData::Trait(traitType) = sym.data
3303 3309
        else return;
3304 3310
3305 -
    if methods.len > traitType.methods.len {
3311 +
    // Resolve supertrait bounds and copy their methods into this trait.
3312 +
    for i in 0..supertraits.len {
3313 +
        if traitType.supertraitsLen >= traitType.supertraits.len {
3314 +
            throw emitError(self, node, ErrorKind::Internal);
3315 +
        }
3316 +
        let superNode = supertraits.list[i];
3317 +
        let superSym = try resolveNamePath(self, superNode);
3318 +
        let case SymbolData::Trait(superTrait) = superSym.data
3319 +
            else throw emitError(self, superNode, ErrorKind::Internal);
3320 +
        try setNodeSymbol(self, superNode, superSym);
3321 +
3322 +
        if traitType.methodsLen + superTrait.methodsLen > ast::MAX_TRAIT_METHODS {
3323 +
            throw emitError(self, node, ErrorKind::TraitMethodOverflow(CountMismatch {
3324 +
                expected: ast::MAX_TRAIT_METHODS,
3325 +
                actual: traitType.methodsLen + superTrait.methodsLen,
3326 +
            }));
3327 +
        }
3328 +
        // Copy inherited methods into this trait's method table.
3329 +
        for j in 0..superTrait.methodsLen {
3330 +
            let inherited = superTrait.methods[j];
3331 +
            if let _ = findTraitMethod(traitType, inherited.name) {
3332 +
                throw emitError(self, superNode, ErrorKind::DuplicateBinding(inherited.name));
3333 +
            }
3334 +
            traitType.methods[traitType.methodsLen] = TraitMethod {
3335 +
                name: inherited.name,
3336 +
                fnType: inherited.fnType,
3337 +
                mutable: inherited.mutable,
3338 +
                index: traitType.methodsLen,
3339 +
            };
3340 +
            traitType.methodsLen += 1;
3341 +
        }
3342 +
        traitType.supertraits[traitType.supertraitsLen] = superTrait;
3343 +
        traitType.supertraitsLen += 1;
3344 +
    }
3345 +
3346 +
    if traitType.methodsLen + methods.len > ast::MAX_TRAIT_METHODS {
3306 3347
        throw emitError(self, node, ErrorKind::TraitMethodOverflow(CountMismatch {
3307 -
            expected: traitType.methods.len,
3308 -
            actual: methods.len,
3348 +
            expected: ast::MAX_TRAIT_METHODS,
3349 +
            actual: traitType.methodsLen + methods.len,
3309 3350
        }));
3310 3351
    }
3352 +
3311 3353
    for i in 0..methods.len {
3312 3354
        let methodNode = methods.list[i];
3313 3355
        let case ast::NodeValue::TraitMethodSig { name, receiver, sig } = methodNode.value
3314 3356
            else continue;
3315 3357
        let methodName = try nodeName(self, name);
3316 3358
3317 -
        // Reject duplicate method names within the same trait.
3359 +
        // Reject duplicate method names.
3318 3360
        if let _ = findTraitMethod(traitType, methodName) {
3319 3361
            throw emitError(self, name, ErrorKind::DuplicateBinding(methodName));
3320 3362
        }
3321 3363
3322 3364
        // Determine receiver mutability from the receiver type node
3559 3601
        entry.methodsLen += 1;
3560 3602
3561 3603
        covered[tm.index] = true;
3562 3604
    }
3563 3605
3606 +
    // Fill inherited method slots from supertrait instances.
3607 +
    for si in 0..traitInfo.supertraitsLen {
3608 +
        let superTrait = traitInfo.supertraits[si];
3609 +
        let superInst = findInstance(self, superTrait, concreteType)
3610 +
            else throw emitError(self, node, ErrorKind::MissingSupertraitInstance(superTrait.name));
3611 +
        for mi in 0..superTrait.methodsLen {
3612 +
            let merged = findTraitMethod(traitInfo, superTrait.methods[mi].name)
3613 +
                else panic "resolveInstanceDecl: inherited method not found";
3614 +
            if not covered[merged.index] {
3615 +
                entry.methods[merged.index] = superInst.methods[mi];
3616 +
                entry.methodsLen += 1;
3617 +
                covered[merged.index] = true;
3618 +
            }
3619 +
        }
3620 +
    }
3621 +
3564 3622
    // Check that all trait methods are implemented.
3565 3623
    for i in 0..traitInfo.methodsLen {
3566 3624
        if not covered[i] {
3567 3625
            throw emitError(self, node, ErrorKind::MissingTraitMethod(traitInfo.methods[i].name));
3568 3626
        }
6051 6109
            case ast::NodeValue::UnionDecl(decl) => {
6052 6110
                try resolveUnionBody(self, node, decl) catch {
6053 6111
                    // Continue resolving other types even if one fails.
6054 6112
                };
6055 6113
            }
6056 -
            case ast::NodeValue::TraitDecl { methods, .. } => {
6057 -
                try resolveTraitBody(self, node, &methods) catch {
6114 +
            case ast::NodeValue::TraitDecl { supertraits, methods, .. } => {
6115 +
                try resolveTraitBody(self, node, &supertraits, &methods) catch {
6058 6116
                    // Continue resolving other types even if one fails.
6059 6117
                };
6060 6118
            }
6061 6119
            else => {
6062 6120
                // Ignore other declarations.
lib/std/lang/resolver/printer.rad +5 -0
585 585
            io::print("too many trait methods: maximum ");
586 586
            io::printU32(mismatch.expected);
587 587
            io::print(", got ");
588 588
            io::printU32(mismatch.actual);
589 589
        }
590 +
        case super::ErrorKind::MissingSupertraitInstance(name) => {
591 +
            io::print("missing instance for supertrait '");
592 +
            io::print(name);
593 +
            io::print("'");
594 +
        }
590 595
        case super::ErrorKind::Internal => {
591 596
            io::print("internal compiler error");
592 597
        }
593 598
        case super::ErrorKind::RecordFieldOutOfOrder { .. } => {
594 599
            io::print("record field out of order");