Bootstrap ownership syntax

b02d096740f234c048654416f2cf5f90864e385152c1ccf24e41a7534d94ce67
Let the previous compiler build the sources of the ownership, borrowing and
initialization commit. The result is a bridge between the old seed and the new
source: the old seed builds it, it builds itself to a fixed point, and its
fixed point builds the new source to a fixed point.

Accepted without checking:

* `opaque record` declarations. The keyword is parsed and ignored.
* Unsafe operations and unsafe calls in safe code, including `undefined`
  locals. The resolver no longer requires an unsafe context.
* Ownership, move, `Once` and borrow checks. The old linear checker is not
  run.

Implemented:

* Slice `reserve`, `resize`, `extend` and `take`, and `append`, with an
  allocator that is either a `&mut` trait object of an allocator trait or a
  `&mut` reference to a type that implements one. The lowering calls the
  allocator through its v-table. Allocator records with a callback and a
  context pointer stay accepted, which the bridge's own source needs.
* The non-null empty slice pointer for `&[]` and for `take`.
* Union variant patterns with a payload on optional subjects, for `match`,
  `if let case` and `let case`.
* Array lengths in function signatures that name constants. Constants now
  resolve before function signatures.
* `@default` functions with storage parameters. The lowering generates the
  program entry, which passes one zero-filled data region per parameter and
  sets the slices in it to the empty slice.
* Call arguments beyond the eight argument registers, passed on the stack.
  The callee reads them relative to its entry stack pointer.

Assisted-by: Claude:opus-5.5
Alexis Sellier committed ago 1 parent 627a5b79
lib/std/arch/rv64/isel.rad +74 -7
98 98
    pendingSpill: ?PendingSpill,
99 99
    /// Next synthetic block index for skip-branch targets.
100 100
    nextSynthBlock: u32,
101 101
    /// Whether dynamic allocations exist.
102 102
    isDynamic: bool,
103 +
    /// Size of the outgoing stack argument area while a call is being set up,
104 +
    /// else zero. It lowers SP below the spill slots and reserve slots.
105 +
    argAdjust: i32,
103 106
}
104 107
105 108
/////////////////////////
106 109
// Register Allocation //
107 110
/////////////////////////
114 117
    return phys;
115 118
}
116 119
117 120
/// Compute the offset for a spill slot.
118 121
/// When using FP (dynamic): offset from FP = `slot - totalSize`.
119 -
/// When using SP: offset from SP = `slot`.
122 +
/// When using SP: offset from SP = `slot`, plus the outgoing argument area.
120 123
fn spillOffset(s: &Selector, slot: i32) -> i32 {
121 124
    if s.isDynamic {
122 125
        return slot - s.frameSize;
123 126
    }
124 -
    return slot;
127 +
    return slot + s.argAdjust;
128 +
}
129 +
130 +
/// Compute the offset of the incoming stack argument `index`, which counts from
131 +
/// the first argument passed on the stack. The caller placed it at its SP at the
132 +
/// call, which is the SP of this function on entry and the value of FP in a
133 +
/// dynamic frame. The offset is relative to FP in a dynamic frame, else to SP.
134 +
fn stackParamOffset(s: &Selector, index: u32) -> i32 {
135 +
    if s.isDynamic {
136 +
        return index as i32 * super::DWORD_SIZE;
137 +
    }
138 +
    return index as i32 * super::DWORD_SIZE + s.frameSize;
125 139
}
126 140
127 141
/// Get the base register for spill slot addressing (FP or SP).
128 142
fn spillBase(s: &Selector) -> gen::Reg {
129 143
    if s.isDynamic {
329 343
        ralloc: ralloc as *unsafe regalloc::AllocResult,
330 344
        frameSize: frame.totalSize,
331 345
        reserveOffset: 0, pendingSpill: nil,
332 346
        nextSynthBlock: func.blocks.len + 1,
333 347
        isDynamic: frame.isDynamic,
348 +
        argAdjust: 0,
334 349
    };
335 350
    // Record function name for printing.
336 351
    try emit::recordFunc(s.e, func.name);
337 352
    // Record function code offset for call patching.
338 353
    try emit::recordFuncOffset(s.e, func.name);
340 355
    try emit::emitPrologue(s.e, &frame);
341 356
342 357
    // Move function params from arg registers to assigned registers.
343 358
    // Cross-call params may have been assigned to callee-saved registers
344 359
    // instead of their natural arg registers. Spilled params are stored
345 -
    // directly to their spill slots.
360 +
    // directly to their spill slots. Params beyond the arg registers are
361 +
    // loaded from the caller's stack arguments. They come last, so a load
362 +
    // cannot overwrite an arg register that has not been moved yet.
346 363
    for funcParam, i in func.params {
347 364
        if i < super::ARG_REGS.len {
348 365
            let param = funcParam.value;
349 366
            let argReg = super::ARG_REGS[i];
350 367
354 371
            } else if let assigned = ralloc.assignments[param.n] {
355 372
                try emitMv(&mut s, assigned, argReg);
356 373
            }
357 374
        }
358 375
    }
376 +
    for funcParam, i in func.params {
377 +
        if i >= super::ARG_REGS.len {
378 +
            let param = funcParam.value;
379 +
            let offset = stackParamOffset(&s, i - super::ARG_REGS.len);
380 +
            let base = spillBase(&s);
381 +
382 +
            if let slot = regalloc::spill::spillSlot(&ralloc.spill, param) {
383 +
                try emit::emitLd(s.e, super::SCRATCH1, base, offset);
384 +
                try emit::emitSd(s.e, super::SCRATCH1, spillBase(&s), spillOffset(&s, slot));
385 +
            } else if let assigned = ralloc.assignments[param.n] {
386 +
                try emit::emitLd(s.e, assigned, base, offset);
387 +
            }
388 +
        }
389 +
    }
359 390
360 391
    // Emit each block.
361 392
    for i in 0..func.blocks.len {
362 393
        try selectBlock(&mut s, i, &func.blocks[i], &frame, func);
363 394
    }
715 746
            // setup can clobber it.
716 747
            if let case il::Val::Reg(r) = func {
717 748
                let target = try getSrcReg(s, r, super::SCRATCH2);
718 749
                try emitMv(s, super::SCRATCH2, target);
719 750
            }
751 +
            // Store the arguments beyond A7 on the stack first, because the
752 +
            // register moves below overwrite registers that may hold them.
753 +
            try emitStackArgs(s, args);
754 +
720 755
            // Move arguments to A0-A7 using parallel move resolution.
721 -
            if args.len > super::ARG_REGS.len {
722 -
                throw super::Error::Capacity;
723 -
            }
724 -
            try emitParallelMoves(s, &super::ARG_REGS[..], args);
756 +
            let regCount = super::ARG_REGS.len if args.len > super::ARG_REGS.len else args.len;
757 +
            try emitParallelMoves(s, &super::ARG_REGS[..], &args[..regCount]);
725 758
726 759
            // Emit call.
727 760
            match func {
728 761
                case il::Val::FnAddr(name) => {
729 762
                    try emit::recordCall(s.e, name);
733 766
                },
734 767
                else => {
735 768
                    panic "selectInstr: invalid call target";
736 769
                }
737 770
            }
771 +
            // Release the outgoing stack arguments.
772 +
            if s.argAdjust <> 0 {
773 +
                try emit::emitAddImm(s.e, super::SP, super::SP, s.argAdjust);
774 +
                set s.argAdjust = 0;
775 +
            }
738 776
            // Move result from A0.
739 777
            if let d = dst {
740 778
                let rd = getDstReg(s, d, super::SCRATCH1);
741 779
                try emitMv(s, rd, super::A0);
742 780
            }
1053 1091
            case ShiftOp::Sra => try emit::emit(s.e, encode::sra(rd, rs1, rs2)),
1054 1092
        }
1055 1093
    }
1056 1094
}
1057 1095
1096 +
/// Pass the call arguments beyond the arg registers on the stack.
1097 +
///
1098 +
/// The first value on the stack goes to the lowest address. The function lowers
1099 +
/// SP by the size of the outgoing area, rounded up to the stack alignment, and
1100 +
/// stores each value in an 8-byte slot at SP. The callee reads the slots
1101 +
/// relative to its entry SP and may overwrite them. The caller releases the area
1102 +
/// after the call. This function leaves [`Selector.argAdjust`] set to the size
1103 +
/// until then. It emits nothing when all values fit in the arg registers.
1104 +
unsafe fn emitStackArgs(s: &mut Selector, vals: &[il::Val]) throws (super::Error) {
1105 +
    if vals.len <= super::ARG_REGS.len {
1106 +
        return;
1107 +
    }
1108 +
    let count = vals.len - super::ARG_REGS.len;
1109 +
    let size = mem::alignUpI32(count as i32 * super::DWORD_SIZE, super::STACK_ALIGNMENT);
1110 +
1111 +
    try emit::emitAddImm(s.e, super::SP, super::SP, 0 - size);
1112 +
    set s.argAdjust = size;
1113 +
1114 +
    for i in 0..count {
1115 +
        let val = vals[super::ARG_REGS.len + i];
1116 +
        if let case il::Val::Undef = val {
1117 +
            // Undefined values don't need any store.
1118 +
        } else {
1119 +
            let rs = try resolveVal(s, super::SCRATCH1, val);
1120 +
            try emit::emitSd(s.e, rs, super::SP, i as i32 * super::DWORD_SIZE);
1121 +
        }
1122 +
    }
1123 +
}
1124 +
1058 1125
/// Resolve parallel moves from IL values to physical destination registers.
1059 1126
///
1060 1127
/// The parallel move problem arises when moving values between registers where
1061 1128
/// there may be dependencies (e.g. moving A0 to A1 and A1 to A0 simultaneously).
1062 1129
///
lib/std/lang/lower.rad +795 -49
208 208
/// Maximum nesting depth of loops.
209 209
constant MAX_LOOP_DEPTH: u32 = 16;
210 210
/// Maximum number of `catch` clauses per `try`.
211 211
constant MAX_CATCH_CLAUSES: u32 = 32;
212 212
213 +
/// Suffix of the generated entry function of a default function with storage
214 +
/// parameters. A source identifier cannot contain the `$` that precedes it in
215 +
/// the name, so the entry cannot collide with a user symbol.
216 +
constant ENTRY_SUFFIX: *[u8] = "entry";
217 +
/// Namespace of the zero-filled regions behind storage parameters. The
218 +
/// region names are `<entry>$storage$<index>`.
219 +
constant STORAGE_NAMESPACE: *[u8] = "storage";
220 +
213 221
// Slice Layout
214 222
//
215 223
// A slice is a fat pointer consisting of a data pointer, a length and a capacity.
216 224
// `{ ptr: u32, len: u32, cap: u32 }`.
217 225
855 863
    for node in stmtsList {
856 864
        match node.value {
857 865
            case ast::NodeValue::FnDecl(decl) => {
858 866
                if let f = try lowerFnDecl(low, node, decl) {
859 867
                    let role = lowerFnRole(isRoot, decl.attrs);
860 -
                    try emitFunction(low, f, role);
868 +
                    let case resolver::Type::Fn(fnType) = resolver::nodeData(low.resolver, node).ty else {
869 +
                        throw LowerError::ExpectedFunction;
870 +
                    };
871 +
                    if let case FnRole::Default = role;
872 +
                    fnType.paramTypes.len > resolver::defaultStorageStart(fnType) {
873 +
                        // The program enters through a generated function
874 +
                        // that supplies the storage regions. The function
875 +
                        // itself is an ordinary function.
876 +
                        let userName = f.name;
877 +
                        try emitFunction(low, f, FnRole::Normal);
878 +
                        let entry = try lowerStorageEntry(low, node, fnType, userName);
879 +
                        try emitFunction(low, entry, FnRole::Default);
880 +
                    } else {
881 +
                        try emitFunction(low, f, role);
882 +
                    }
861 883
                }
862 884
            }
863 885
            case ast::NodeValue::ConstDecl(decl) => {
864 886
                try lowerDataDecl(low, node, decl.value, true);
865 887
            }
1064 1086
    set func.isLeaf = fnLow.isLeaf;
1065 1087
1066 1088
    return func;
1067 1089
}
1068 1090
1091 +
/// Lower the program entry of a default function that takes storage parameters.
1092 +
///
1093 +
/// The entry function takes the same hidden return parameter and environment
1094 +
/// parameter as the default function `userName`, if it has them. It calls the
1095 +
/// default function with these and the address of one zero-filled data region
1096 +
/// for each storage parameter. The entry and its regions are named by the
1097 +
/// default function's name followed by `$` and a generated suffix. Before the
1098 +
/// call, the entry sets each bare slice in the regions to the empty slice, since
1099 +
/// zero is not a valid slice.
1100 +
unsafe fn lowerStorageEntry(
1101 +
    self: &mut Lowerer,
1102 +
    node: *ast::Node,
1103 +
    fnType: *resolver::FnType,
1104 +
    userName: *[u8]
1105 +
) -> *unsafe il::Fn throws (LowerError) {
1106 +
    let segments = [userName, ENTRY_SUFFIX];
1107 +
    let entryName = try buildSegmentedName(self, &segments[..]);
1108 +
    let mut fnLow = fnLowerer(self, node, fnType, entryName);
1109 +
    // The entry has no locals, whatever the default function declares.
1110 +
    set fnLow.localCount = 0;
1111 +
1112 +
    let first = resolver::defaultStorageStart(fnType);
1113 +
    let mut hidden: u32 = 0;
1114 +
    if requiresReturnParam(fnType) {
1115 +
        set hidden = 1;
1116 +
    }
1117 +
    let args = try allocVals(&mut fnLow, hidden + fnType.paramTypes.len as u32);
1118 +
    let params = try! alloc::allocRawSlice(
1119 +
        self.fnArena, @sizeOf(il::Param), @alignOf(il::Param), hidden + first
1120 +
    ) as *unsafe mut [il::Param];
1121 +
1122 +
    if hidden == 1 {
1123 +
        let reg = nextReg(&mut fnLow);
1124 +
        set params[0] = il::Param { value: reg, type: il::Type::W64 };
1125 +
        set args[0] = il::Val::Reg(reg);
1126 +
    }
1127 +
    if first == 1 {
1128 +
        let reg = nextReg(&mut fnLow);
1129 +
        set params[hidden] = il::Param { value: reg, type: ilType(self, *fnType.paramTypes[0]) };
1130 +
        set args[hidden] = il::Val::Reg(reg);
1131 +
    }
1132 +
    let entry = try createBlock(&mut fnLow, "entry");
1133 +
    set fnLow.entryBlock = entry;
1134 +
    switchToBlock(&mut fnLow, entry);
1135 +
1136 +
    for i in first..fnType.paramTypes.len as u32 {
1137 +
        let case resolver::Type::Pointer { target, .. } = *fnType.paramTypes[i]
1138 +
            else panic "lowerStorageEntry: storage parameter is not a pointer";
1139 +
        let typeLayout = resolver::getTypeLayout(*target);
1140 +
        // The region is aligned for any scalar, as the program expects.
1141 +
        let mut alignment = typeLayout.alignment;
1142 +
        if alignment < resolver::PTR_SIZE {
1143 +
            set alignment = resolver::PTR_SIZE;
1144 +
        }
1145 +
        let name = try nextDeclDataName(self, entryName, i - first, STORAGE_NAMESPACE);
1146 +
        let mut values: *mut [il::DataValue] = &mut [];
1147 +
        if typeLayout.size > 0 {
1148 +
            try! values.append(il::DataValue {
1149 +
                item: il::DataItem::Val { typ: il::Type::W8, val: 0 },
1150 +
                count: typeLayout.size,
1151 +
            }, self.allocator);
1152 +
        }
1153 +
        try! self.data.append(il::Data {
1154 +
            name,
1155 +
            size: typeLayout.size,
1156 +
            alignment,
1157 +
            readOnly: false,
1158 +
            isZeroInit: true,
1159 +
            values: &values[..],
1160 +
        }, self.allocator);
1161 +
        let reg = nextReg(&mut fnLow);
1162 +
        emit(&mut fnLow, il::Instr::Copy { dst: reg, val: il::Val::DataSym(name) });
1163 +
        try emitStorageSlices(&mut fnLow, reg, *target);
1164 +
        set args[hidden + i] = il::Val::Reg(reg);
1165 +
    }
1166 +
    let retTy = *fnType.returnType;
1167 +
    let mut returnType = ilType(self, retTy);
1168 +
    if fnType.throwList.len > 0 {
1169 +
        set returnType = il::Type::W64;
1170 +
    }
1171 +
    let mut dst: ?il::Reg = nil;
1172 +
    if hidden == 0 and retTy <> resolver::Type::Void and retTy <> resolver::Type::Never {
1173 +
        set dst = nextReg(&mut fnLow);
1174 +
    }
1175 +
    emit(&mut fnLow, il::Instr::Call {
1176 +
        retTy: returnType,
1177 +
        dst,
1178 +
        func: il::Val::FnAddr(userName),
1179 +
        args,
1180 +
    });
1181 +
    set fnLow.isLeaf = false;
1182 +
    if retTy == resolver::Type::Never {
1183 +
        emit(&mut fnLow, il::Instr::Unreachable);
1184 +
    } else if let d = dst {
1185 +
        emit(&mut fnLow, il::Instr::Ret { val: il::Val::Reg(d) });
1186 +
    } else {
1187 +
        emit(&mut fnLow, il::Instr::Ret { val: nil });
1188 +
    }
1189 +
    let func = try! alloc::allocRaw(self.fnArena, @sizeOf(il::Fn), @alignOf(il::Fn)) as *unsafe mut il::Fn;
1190 +
    set *func = il::Fn {
1191 +
        name: entryName,
1192 +
        params: params,
1193 +
        returnType,
1194 +
        isExtern: false,
1195 +
        isLeaf: fnLow.isLeaf,
1196 +
        blocks: try finalizeBlocks(&mut fnLow),
1197 +
    };
1198 +
    return func;
1199 +
}
1200 +
1201 +
/// Return whether zero-filled storage of type `ty` holds a bare slice that the
1202 +
/// entry must set to the empty slice. Optional slices are `nil` when zero, so
1203 +
/// they need nothing.
1204 +
unsafe fn hasStorageSlice(ty: resolver::Type) -> bool {
1205 +
    match ty {
1206 +
        case resolver::Type::Slice { .. } => return true,
1207 +
        case resolver::Type::Array(array) =>
1208 +
            return array.length > 0 and hasStorageSlice(*array.item),
1209 +
        case resolver::Type::Nominal(resolver::NominalType::Record(recInfo)) => {
1210 +
            for field in recInfo.fields {
1211 +
                if hasStorageSlice(field.fieldType) {
1212 +
                    return true;
1213 +
                }
1214 +
            }
1215 +
            return false;
1216 +
        }
1217 +
        case resolver::Type::Nominal(resolver::NominalType::Union(unionInfo)) =>
1218 +
            return hasStorageSlice(zeroVariantType(unionInfo)),
1219 +
        else => return false,
1220 +
    }
1221 +
}
1222 +
1223 +
/// Return the payload type of the variant with tag 0, which is the variant that
1224 +
/// zero-filled storage of the union holds.
1225 +
unsafe fn zeroVariantType(unionInfo: resolver::UnionType) -> resolver::Type {
1226 +
    for variant in unionInfo.variants {
1227 +
        let case resolver::SymbolData::Variant { index, .. } = variant.symbol.data
1228 +
            else panic "zeroVariantType: expected variant symbol";
1229 +
        if index == 0 {
1230 +
            return variant.valueType;
1231 +
        }
1232 +
    }
1233 +
    return resolver::Type::Void;
1234 +
}
1235 +
1236 +
/// Set every bare slice in the zero-filled storage of type `ty` at `base` to the
1237 +
/// empty slice: the data pointer becomes the non-null empty slice pointer, and
1238 +
/// the length and capacity stay zero. Arrays are initialized by a loop over their
1239 +
/// elements.
1240 +
///
1241 +
/// Storage that the loader zero-fills is valid for every type that storage
1242 +
/// parameters allow, except that a zero data pointer is not a slice.
1243 +
unsafe fn emitStorageSlices(
1244 +
    self: &mut FnLowerer,
1245 +
    base: il::Reg,
1246 +
    ty: resolver::Type
1247 +
) throws (LowerError) {
1248 +
    if not hasStorageSlice(ty) {
1249 +
        return;
1250 +
    }
1251 +
    match ty {
1252 +
        case resolver::Type::Slice { item, .. } => {
1253 +
            // The empty slice has no element, so its data pointer can be any value.
1254 +
            emitStoreW64At(self, emptySlicePtr(item), base, SLICE_PTR_OFFSET);
1255 +
        }
1256 +
        case resolver::Type::Array(array) => {
1257 +
            let indexReg = nextReg(self);
1258 +
            let header = try createBlockWithParam(
1259 +
                self, "slices", il::Param { value: indexReg, type: il::Type::W32 }
1260 +
            );
1261 +
            let body = try createBlock(self, "slices");
1262 +
            let done = try createBlock(self, "slices");
1263 +
1264 +
            try emitJmpWithArg(self, header, il::Val::Imm(0));
1265 +
1266 +
            // The body adds a predecessor of the header, so the header stays open until then.
1267 +
            switchToBlock(self, header);
1268 +
            try emitBrCmp(
1269 +
                self, il::CmpOp::Ult, il::Type::W32, il::Val::Reg(indexReg),
1270 +
                il::Val::Imm(array.length as i64), body, done
1271 +
            );
1272 +
            try switchToAndSeal(self, body);
1273 +
            let elem = emitElem(self, resolver::getTypeLayout(*array.item).size, base,
1274 +
                il::Val::Reg(indexReg));
1275 +
            try emitStorageSlices(self, elem, *array.item);
1276 +
            let next = emitTypedBinOp(
1277 +
                self, il::BinOp::Add, il::Type::W32, il::Val::Reg(indexReg), il::Val::Imm(1)
1278 +
            );
1279 +
            try emitJmpWithArg(self, header, next);
1280 +
1281 +
            try sealBlock(self, header);
1282 +
            try switchToAndSeal(self, done);
1283 +
        }
1284 +
        case resolver::Type::Nominal(resolver::NominalType::Record(recInfo)) => {
1285 +
            for field in recInfo.fields {
1286 +
                if hasStorageSlice(field.fieldType) {
1287 +
                    try emitStorageSlices(self, emitPtrOffset(self, base, field.offset), field.fieldType);
1288 +
                }
1289 +
            }
1290 +
        }
1291 +
        case resolver::Type::Nominal(resolver::NominalType::Union(unionInfo)) => {
1292 +
            try emitStorageSlices(
1293 +
                self, emitPtrOffset(self, base, unionInfo.valOffset as i32),
1294 +
                zeroVariantType(unionInfo)
1295 +
            );
1296 +
        }
1297 +
        else => {}
1298 +
    }
1299 +
}
1300 +
1069 1301
/// Build a qualified name of the form "Type::method".
1070 1302
unsafe fn instanceMethodName(self: &mut Lowerer, modId: ?u16, typeName: *[u8], methodName: *[u8]) -> *[u8] {
1071 1303
    let sepLen: u32 = 2; // "::"
1072 1304
    let totalLen = typeName.len + sepLen + methodName.len;
1073 1305
    let buf = try! alloc::allocSlice(self.arena, 1, 1, totalLen) as *mut [u8];
2450 2682
    emit(self, il::Instr::Copy { dst, val: il::Val::FnAddr(qualName) });
2451 2683
2452 2684
    return dst;
2453 2685
}
2454 2686
2687 +
/// Return whether `pattern` is a union variant pattern on an optional union subject.
2688 +
unsafe fn isOptionalVariantPattern(self: &FnLowerer, subject: &MatchSubject, pattern: *ast::Node) -> bool {
2689 +
    let case MatchSubjectKind::OptionalAggregate = subject.kind else return false;
2690 +
    if unionInfoFromType(subject.bindType) == nil {
2691 +
        return false;
2692 +
    }
2693 +
    let case resolver::NodeExtra::UnionVariant { .. } = resolver::nodeData(self.low.resolver, pattern).extra
2694 +
        else return false;
2695 +
2696 +
    return true;
2697 +
}
2698 +
2699 +
/// Build the subject for the union that a present optional subject holds.
2700 +
/// It shares the optional's storage, so a match by reference binds into the optional.
2701 +
unsafe fn optionalPayloadSubject(self: &mut FnLowerer, subject: &MatchSubject) -> MatchSubject {
2702 +
    let base = emitValToReg(self, subject.val);
2703 +
    let valOffset = resolver::getOptionalValOffset(subject.bindType) as i32;
2704 +
    let mut val = il::Val::Reg(emitPtrOffset(self, base, valOffset));
2705 +
    if subject.by == resolver::MatchBy::Value {
2706 +
        set val = emitRead(self, base, valOffset, subject.bindType);
2707 +
    }
2708 +
    return MatchSubject {
2709 +
        val,
2710 +
        type: subject.bindType,
2711 +
        ilType: ilType(self.low, subject.bindType),
2712 +
        bindType: subject.bindType,
2713 +
        kind: matchSubjectKind(subject.bindType),
2714 +
        by: subject.by,
2715 +
    };
2716 +
}
2717 +
2455 2718
/// Emit pattern tests for a single pattern.
2456 2719
unsafe fn emitPatternMatch(
2457 2720
    self: &mut FnLowerer,
2458 2721
    subject: &MatchSubject,
2459 2722
    pattern: *ast::Node,
2488 2751
            let base = emitValToReg(self, subject.val);
2489 2752
2490 2753
            if isNil { // Optional aggregate: `nil` means tag is zero.
2491 2754
                let tagReg = tvalTagReg(self, base);
2492 2755
                try emitBr(self, tagReg, fallthrough, matchBlock);
2756 +
            } else if isOptionalVariantPattern(self, subject, pattern) {
2757 +
                // The optional is present and holds the variant. One branch
2758 +
                // tests both. The union tag is garbage when the optional is
2759 +
                // `nil`, so it is only combined with the presence flag.
2760 +
                let case resolver::NodeExtra::UnionVariant { tag: variantTag, .. } =
2761 +
                    resolver::nodeData(self.low.resolver, pattern).extra
2762 +
                else {
2763 +
                    throw LowerError::ExpectedVariant;
2764 +
                };
2765 +
                let valOffset = resolver::getOptionalValOffset(subject.bindType) as i32;
2766 +
                let presentTag = tvalTagReg(self, base);
2767 +
                let variantTagVal = loadTag(self, base, valOffset + TVAL_TAG_OFFSET, il::Type::W8);
2768 +
                let isPresent = emitTypedBinOp(self, il::BinOp::Ne, il::Type::W8,
2769 +
                    il::Val::Reg(presentTag), il::Val::Imm(0));
2770 +
                let isVariant = emitTypedBinOp(self, il::BinOp::Eq, il::Type::W8, variantTagVal,
2771 +
                    il::Val::Imm(variantTag as i64));
2772 +
                let both = emitTypedBinOp(self, il::BinOp::And, il::Type::W32, isPresent, isVariant);
2773 +
2774 +
                try emitBr(self, emitValToReg(self, both), matchBlock, fallthrough);
2493 2775
            } else {
2494 2776
                // `lowerExpr` applies the resolver's optional-lift coercion,
2495 2777
                // materializing the tagged representation for value patterns.
2496 2778
                let pattVal = try lowerExpr(self, pattern);
2497 2779
                let pattReg = emitValToReg(self, pattVal);
3335 3617
/// Bind variables from inside case patterns (union variants, records, slices).
3336 3618
/// `failBlock` is passed when nested patterns may require additional tests
3337 3619
/// that branch on mismatch (e.g. nested union variant tests).
3338 3620
unsafe fn bindPatternVariables(self: &mut FnLowerer, subject: &MatchSubject, patterns: &[*ast::Node], failBlock: BlockId) throws (LowerError) {
3339 3621
    for pattern in patterns {
3622 +
        // A variant pattern on an optional subject binds from the union in the
3623 +
        // payload. The presence and variant tests have passed.
3624 +
        if isOptionalVariantPattern(self, subject, pattern) {
3625 +
            let payload = optionalPayloadSubject(self, subject);
3626 +
            let single = [pattern];
3627 +
            try bindPatternVariables(self, &payload, &single[..], failBlock);
3628 +
            continue;
3629 +
        }
3340 3630
3341 3631
        // Handle simple variant patterns like `Variant(x)`.
3342 3632
        if let arg = resolver::variantPatternBinding(self.low.resolver, pattern) {
3343 3633
            let case MatchSubjectKind::Union(unionInfo) = subject.kind
3344 3634
                else panic "bindPatternVariables: expected union subject";
5165 5455
    let case resolver::Type::Array(arrayInfo) = arrayTy else {
5166 5456
        throw LowerError::ExpectedArray;
5167 5457
    };
5168 5458
    let length = arrayInfo.length;
5169 5459
    if length == 0 {
5460 +
        // The data pointer of an empty slice is never null.
5170 5461
        return try buildSliceValue(
5171 -
            self, item, mutable, il::Val::Imm(0), il::Val::Imm(0), il::Val::Imm(0)
5462 +
            self, item, mutable, emptySlicePtr(item), il::Val::Imm(0), il::Val::Imm(0)
5172 5463
        );
5173 5464
    }
5174 5465
    if resolver::isConstExpr(self.low.resolver, arrayNode) {
5175 5466
        let fnName = self.fnName;
5176 5467
        let mut b = dataBuilder(self.low.allocator);
6398 6689
    // Check for trait method dispatch or standalone method call.
6399 6690
    let mut resVal: il::Val = undefined;
6400 6691
    let callNodeExtra = resolver::nodeData(self.low.resolver, t.expr).extra;
6401 6692
    if let case resolver::NodeExtra::SliceAppend { elemType } = callNodeExtra {
6402 6693
        set resVal = try lowerSliceAppend(self, callExpr, elemType);
6694 +
    } else if let case resolver::NodeExtra::SliceReserve { elemType } = callNodeExtra {
6695 +
        set resVal = try lowerSliceReserve(self, callExpr, elemType);
6696 +
    } else if let case resolver::NodeExtra::SliceResize { elemType } = callNodeExtra {
6697 +
        set resVal = try lowerSliceResize(self, callExpr, elemType);
6698 +
    } else if let case resolver::NodeExtra::SliceExtend { elemType } = callNodeExtra {
6699 +
        set resVal = try lowerSliceExtend(self, callExpr, elemType);
6403 6700
    } else if let case resolver::NodeExtra::TraitMethodCall {
6404 6701
        traitInfo, methodIndex
6405 6702
    } = callNodeExtra {
6406 6703
        set resVal = try lowerTraitMethodCall(self, t.expr, callExpr, traitInfo, methodIndex);
6407 6704
    } else if let case resolver::NodeExtra::MethodCall { method } = callNodeExtra {
6656 6953
    // Now all predecessors of header are known, seal it.
6657 6954
    try sealBlock(self, header);
6658 6955
    try switchToAndSeal(self, done);
6659 6956
}
6660 6957
6958 +
/// Largest slice length whose elements fit in u32 bytes.
6959 +
fn maxSliceLength(stride: u32) -> u32 {
6960 +
    if stride == 0 {
6961 +
        return parser::U32_MAX;
6962 +
    }
6963 +
    return parser::U32_MAX / stride;
6964 +
}
6965 +
6966 +
/// Call the allocator in `allocReg` for `byteSize` bytes and store its result in `result`.
6967 +
///
6968 +
/// A trait object holds the data pointer and the v-table. The resolver accepts
6969 +
/// only traits with one method, so the function is the first v-table slot. An
6970 +
/// allocator record holds the function and the context pointer. The
6971 +
/// call is `func(result, data, byteSize, alignment)`, and the result holds the
6972 +
/// error tag at offset 0 and the new pointer at `RESULT_VAL_OFFSET`.
6973 +
unsafe fn emitSliceAlloc(
6974 +
    self: &mut FnLowerer,
6975 +
    info: *resolver::FnType,
6976 +
    result: il::Reg,
6977 +
    allocReg: il::Reg,
6978 +
    byteSize: il::Val,
6979 +
    alignment: u32
6980 +
) {
6981 +
    let dataReg = nextReg(self);
6982 +
    let funcReg = nextReg(self);
6983 +
    if let case resolver::Type::TraitObject { .. } = *info.paramTypes[info.paramTypes.len - 1] {
6984 +
        emitLoadW64At(self, dataReg, allocReg, TRAIT_OBJ_DATA_OFFSET);
6985 +
        let vtableReg = nextReg(self);
6986 +
        emitLoadW64At(self, vtableReg, allocReg, TRAIT_OBJ_VTABLE_OFFSET);
6987 +
        emitLoadW64At(self, funcReg, vtableReg, 0);
6988 +
    } else {
6989 +
        emitLoadW64At(self, funcReg, allocReg, 0);
6990 +
        emitLoadW64At(self, dataReg, allocReg, 8);
6991 +
    }
6992 +
6993 +
    let args = try! allocVals(self, 4);
6994 +
    set args[0] = il::Val::Reg(result);
6995 +
    set args[1] = il::Val::Reg(dataReg);
6996 +
    set args[2] = byteSize;
6997 +
    set args[3] = il::Val::Imm(alignment as i64);
6998 +
6999 +
    emit(self, il::Instr::Call {
7000 +
        retTy: il::Type::W64,
7001 +
        dst: nil,
7002 +
        func: il::Val::Reg(funcReg),
7003 +
        args,
7004 +
    });
7005 +
}
7006 +
7007 +
/// Branch to `doneBlock` when the allocation in `result` failed. Otherwise switch
7008 +
/// to a new block named `label`, which copies the old elements.
7009 +
unsafe fn emitAllocBranch(
7010 +
    self: &mut FnLowerer,
7011 +
    result: il::Reg,
7012 +
    doneBlock: BlockId,
7013 +
    label: *[u8]
7014 +
) throws (LowerError) {
7015 +
    let tag = resultTagReg(self, result);
7016 +
    let copyBlock = try createBlock(self, label);
7017 +
    try emitBr(self, tag, doneBlock, copyBlock);
7018 +
7019 +
    try switchToAndSeal(self, copyBlock);
7020 +
}
7021 +
7022 +
/// Copy the slice's current elements into the buffer that `result` points to,
7023 +
/// then publish that buffer and `newCap` as the slice pointer and capacity.
7024 +
///
7025 +
/// The caller passes the old length `lenVal`. The caller stores the new length
7026 +
/// after the fill, so this function leaves the length unchanged. Terminates the
7027 +
/// current block and leaves the builder positioned after the copy loop.
7028 +
unsafe fn emitSliceGrowCopy(
7029 +
    self: &mut FnLowerer,
7030 +
    result: il::Reg,
7031 +
    sliceReg: il::Reg,
7032 +
    lenVal: il::Val,
7033 +
    elemType: *resolver::Type,
7034 +
    newCap: il::Val,
7035 +
    label: *[u8]
7036 +
) throws (LowerError) {
7037 +
    let stride = resolver::getTypeLayout(*elemType).size;
7038 +
7039 +
    let newPtrReg = nextReg(self);
7040 +
    emitLoadW64At(self, newPtrReg, result, RESULT_VAL_OFFSET);
7041 +
7042 +
    let oldPtrReg = loadSlicePtr(self, sliceReg);
7043 +
    let copyBytes = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, lenVal, il::Val::Imm(stride as i64));
7044 +
    try emitByteCopyLoop(self, newPtrReg, oldPtrReg, copyBytes, label);
7045 +
7046 +
    emitStoreW64At(self, il::Val::Reg(newPtrReg), sliceReg, SLICE_PTR_OFFSET);
7047 +
    emitStoreW32At(self, newCap, sliceReg, SLICE_CAP_OFFSET);
7048 +
}
7049 +
7050 +
/// Reserve the result of a slice call that runs a fallible allocator.
7051 +
///
7052 +
/// The allocator writes its pointer at RESULT_VAL_OFFSET. The call's own payload
7053 +
/// is `Void` for `reserve`, `resize`, and `extend`, which has no size, so the
7054 +
/// layout uses a pointer-sized payload instead. The result is large enough for
7055 +
/// the pointer and the allocator's error types.
7056 +
unsafe fn emitAllocResult(self: &mut FnLowerer, throwList: *[*resolver::Type]) -> il::Reg {
7057 +
    return emitReserveLayout(self, resolver::getResultLayout(resolver::Type::U64, throwList));
7058 +
}
7059 +
6661 7060
/// Lower `slice.append(val, allocator)` and return its result aggregate.
6662 7061
///
6663 7062
/// Emits inline grow-if-needed logic:
6664 7063
///
6665 7064
///     load len, cap from slice header
6669 7068
///     @grow:
6670 7069
///       limit = U32_MAX / stride
6671 7070
///       trap if cap > (limit - 1) / 2
6672 7071
///       newCap = cap * 2 + 1
6673 7072
///       bytes = newCap * stride
6674 -
///       call allocator.func(allocator.ctx, bytes, alignment)
7073 +
///       call allocator.func(result, allocator.data, bytes, alignment)
6675 7074
///       if allocation failed: return error result
6676 7075
///       copy old data to new pointer
6677 7076
///       update slice ptr and cap
6678 7077
///       jmp @store
6679 7078
///
6680 7079
///     @store:
6681 7080
///       store element at ptr + len * stride
6682 7081
///       increment len
6683 7082
///       return success result
6684 7083
///
6685 -
/// The slice header changes only after allocation succeeds.
7084 +
/// The slice header changes only after allocation succeeds. The allocator is a
7085 +
/// trait object, called through its v-table; see [`emitSliceAlloc`].
7086 +
/// Zero-sized elements need no allocation.
6686 7087
unsafe fn lowerSliceAppend(
6687 7088
    self: &mut FnLowerer,
6688 7089
    call: ast::Call,
6689 7090
    elemType: *resolver::Type,
6690 7091
) -> il::Val throws (LowerError) {
6691 7092
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
6692 7093
        else throw LowerError::MissingMetadata;
6693 7094
    let case resolver::Type::Fn(info) = try typeOf(self, call.callee)
6694 7095
        else throw LowerError::ExpectedFunction;
6695 7096
7097 +
    // The append result fits the allocation pointer and the shared error types.
6696 7098
    let result = emitReserveLayout(self, resolver::getResultLayout(*info.returnType, info.throwList));
6697 7099
6698 7100
    // Get the address of the slice header.
6699 7101
    let sliceVal = try lowerExpr(self, access.parent);
6700 7102
    let sliceReg = emitValToReg(self, sliceVal);
6701 7103
6702 7104
    // Lower the value to append and the allocator.
6703 -
    let elemVal = try lowerExpr(self, call.args[0]);
7105 +
    let elemVal = try lowerCallArg(self, call.args[0], true);
6704 7106
    let allocVal = try lowerExpr(self, call.args[1]);
6705 7107
    let allocReg = emitValToReg(self, allocVal);
6706 7108
6707 7109
    let elemLayout = resolver::getTypeLayout(*elemType);
6708 7110
    let stride = elemLayout.size;
6720 7122
    try switchToAndSeal(self, growBlock);
6721 7123
6722 7124
    // -- @grow block ----------------------------------------------------------
6723 7125
6724 7126
    // Each allocation size and slice length must fit in u32.
6725 -
    let limit = parser::U32_MAX / stride;
7127 +
    let limit = maxSliceLength(stride);
6726 7128
    try emitTrapUnlessCmp(self, il::CmpOp::Ult, il::Type::W32, capVal, il::Val::Imm(((limit - 1) / 2 + 1) as i64));
6727 7129
6728 7130
    // Grow capacity to `cap * 2 + 1`.
6729 7131
    let doubledVal = emitTypedBinOp(self, il::BinOp::Shl, il::Type::W32, capVal, il::Val::Imm(1));
6730 7132
    let newCapVal = emitTypedBinOp(self, il::BinOp::Or, il::Type::W32, doubledVal, il::Val::Imm(1));
6731 7133
6732 -
    // Call allocator: `a.func(a.ctx, newCap * stride, alignment)`.
6733 -
    let allocFnReg = nextReg(self);
6734 -
    emitLoadW64At(self, allocFnReg, allocReg, 0);
7134 +
    // Allocate `newCap * stride` bytes, then copy the old elements and publish
7135 +
    // the new pointer and capacity.
7136 +
    if stride == 0 {
7137 +
        emitStoreW32At(self, newCapVal, sliceReg, SLICE_CAP_OFFSET);
7138 +
    } else {
7139 +
        let byteSize = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, newCapVal, il::Val::Imm(stride as i64));
7140 +
        emitSliceAlloc(self, info, result, allocReg, byteSize, alignment);
7141 +
        try emitAllocBranch(self, result, doneBlock, "append.copy");
7142 +
        try emitSliceGrowCopy(self, result, sliceReg, lenVal, elemType, newCapVal, "append");
7143 +
    }
7144 +
    try emitJmp(self, storeBlock);
7145 +
    try switchToAndSeal(self, storeBlock);
6735 7146
6736 -
    let allocCtxReg = nextReg(self);
6737 -
    emitLoadW64At(self, allocCtxReg, allocReg, 8);
7147 +
    // -- @store block ---------------------------------------------------------
6738 7148
6739 -
    let byteSize = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, newCapVal, il::Val::Imm(stride as i64));
7149 +
    // Store element at `ptr + len * stride`.
7150 +
    if stride <> 0 {
7151 +
        let ptrReg = loadSlicePtr(self, sliceReg);
7152 +
        let elemDst = emitElem(self, stride, ptrReg, lenVal);
7153 +
        try emitStore(self, elemDst, 0, *elemType, elemVal);
7154 +
    }
7155 +
    // Increment len.
7156 +
    let newLen = emitTypedBinOp(self, il::BinOp::Add, il::Type::W32, lenVal, il::Val::Imm(1));
7157 +
    emitStoreW32At(self, newLen, sliceReg, SLICE_LEN_OFFSET);
6740 7158
6741 -
    let args = try allocVals(self, 4);
7159 +
    // Return the append result.
7160 +
    emitStoreW64At(self, il::Val::Imm(0), result, 0);
7161 +
    try emitStore(self, result, RESULT_VAL_OFFSET, *info.returnType, il::Val::Reg(sliceReg));
7162 +
    try emitJmp(self, doneBlock);
6742 7163
6743 -
    // The append result fits the allocation pointer and the shared error types.
6744 -
    set args[0] = il::Val::Reg(result);
6745 -
    set args[1] = il::Val::Reg(allocCtxReg);
6746 -
    set args[2] = byteSize;
6747 -
    set args[3] = il::Val::Imm(alignment as i64);
7164 +
    try switchToAndSeal(self, doneBlock);
7165 +
    return il::Val::Reg(result);
7166 +
}
6748 7167
6749 -
    emit(self, il::Instr::Call {
6750 -
        retTy: il::Type::W64,
6751 -
        dst: nil,
6752 -
        func: il::Val::Reg(allocFnReg),
6753 -
        args,
6754 -
    });
7168 +
/// Lower `slice.reserve(count, allocator)` and return its result aggregate.
7169 +
///
7170 +
/// Spare capacity that holds `count` elements leaves the slice unchanged.
7171 +
/// Otherwise the guard traps unless `len + count` elements fit in u32 bytes,
7172 +
/// the allocator allocates exactly `len + count` elements, the existing elements
7173 +
/// are copied, and the slice header changes only after the allocation succeeds.
7174 +
/// Zero-sized elements need no allocation.
7175 +
unsafe fn lowerSliceReserve(
7176 +
    self: &mut FnLowerer,
7177 +
    call: ast::Call,
7178 +
    elemType: *resolver::Type
7179 +
) -> il::Val throws (LowerError) {
7180 +
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
7181 +
        else throw LowerError::MissingMetadata;
7182 +
    let case resolver::Type::Fn(info) = try typeOf(self, call.callee)
7183 +
        else throw LowerError::ExpectedFunction;
6755 7184
6756 -
    let tag = resultTagReg(self, result);
6757 -
    let copyBlock = try createBlock(self, "append.copy");
6758 -
    try emitBr(self, tag, doneBlock, copyBlock);
7185 +
    let result = emitAllocResult(self, info.throwList);
6759 7186
6760 -
    try switchToAndSeal(self, copyBlock);
6761 -
    let newPtrReg = nextReg(self);
6762 -
    emitLoadW64At(self, newPtrReg, result, RESULT_VAL_OFFSET);
7187 +
    // Lower the receiver, count, and allocator.
7188 +
    let sliceVal = try lowerExpr(self, access.parent);
7189 +
    let sliceReg = emitValToReg(self, sliceVal);
7190 +
    let countVal = try lowerExpr(self, call.args[0]);
7191 +
    let allocVal = try lowerExpr(self, call.args[1]);
7192 +
    let allocReg = emitValToReg(self, allocVal);
6763 7193
6764 -
    // Copy old data byte-by-byte.
6765 -
    let oldPtrReg = loadSlicePtr(self, sliceReg);
6766 -
    let copyBytes = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, lenVal, il::Val::Imm(stride as i64));
6767 -
    try emitByteCopyLoop(self, newPtrReg, oldPtrReg, copyBytes, "append");
7194 +
    let elemLayout = resolver::getTypeLayout(*elemType);
7195 +
    let stride = elemLayout.size;
7196 +
    let alignment = elemLayout.alignment;
6768 7197
6769 -
    // Update slice header.
6770 -
    emitStoreW64At(self, il::Val::Reg(newPtrReg), sliceReg, SLICE_PTR_OFFSET);
6771 -
    emitStoreW32At(self, newCapVal, sliceReg, SLICE_CAP_OFFSET);
7198 +
    // Spare capacity in elements. The slice header keeps len <= cap.
7199 +
    let lenVal = loadSliceLen(self, sliceReg);
7200 +
    let capVal = loadSliceCap(self, sliceReg);
7201 +
    let spareVal = emitTypedBinOp(self, il::BinOp::Sub, il::Type::W32, capVal, lenVal);
6772 7202
6773 -
    try emitJmp(self, storeBlock);
6774 -
    try switchToAndSeal(self, storeBlock);
7203 +
    // Branch: if the spare capacity is smaller than count, grow; else succeed.
7204 +
    let growBlock = try createBlock(self, "reserve.grow");
7205 +
    let successBlock = try createBlock(self, "reserve.success");
7206 +
    let doneBlock = try createBlock(self, "reserve.done");
7207 +
    try emitBrCmp(self, il::CmpOp::Ult, il::Type::W32, spareVal, countVal, growBlock, successBlock);
7208 +
    try switchToAndSeal(self, growBlock);
6775 7209
6776 -
    // -- @store block ---------------------------------------------------------
7210 +
    // -- @grow block ----------------------------------------------------------
6777 7211
6778 -
    // Store element at `ptr + len * stride`.
6779 -
    let ptrReg = loadSlicePtr(self, sliceReg);
6780 -
    let elemDst = emitElem(self, stride, ptrReg, lenVal);
6781 -
    try emitStore(self, elemDst, 0, *elemType, elemVal);
7212 +
    // Trap unless count <= limit - len, so len + count elements fit in u32 bytes.
7213 +
    // The subtraction cannot wrap because len <= cap <= limit.
7214 +
    let limit = maxSliceLength(stride);
7215 +
    let remainingVal = emitTypedBinOp(self, il::BinOp::Sub, il::Type::W32, il::Val::Imm(limit as i64), lenVal);
7216 +
    let fitsVal = emitTypedBinOp(self, il::BinOp::Uge, il::Type::W32, remainingVal, countVal);
7217 +
    try emitTrapUnlessCmp(self, il::CmpOp::Ne, il::Type::W32, fitsVal, il::Val::Imm(0));
7218 +
7219 +
    // Allocate exactly len + count elements.
7220 +
    let newLenVal = emitTypedBinOp(self, il::BinOp::Add, il::Type::W32, lenVal, countVal);
7221 +
    if stride == 0 {
7222 +
        emitStoreW32At(self, newLenVal, sliceReg, SLICE_CAP_OFFSET);
7223 +
    } else {
7224 +
        let byteSize = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, newLenVal, il::Val::Imm(stride as i64));
7225 +
        emitSliceAlloc(self, info, result, allocReg, byteSize, alignment);
6782 7226
6783 -
    // Increment len.
6784 -
    let newLen = emitTypedBinOp(self, il::BinOp::Add, il::Type::W32, lenVal, il::Val::Imm(1));
6785 -
    emitStoreW32At(self, newLen, sliceReg, SLICE_LEN_OFFSET);
7227 +
        try emitAllocBranch(self, result, doneBlock, "reserve.copy");
7228 +
        try emitSliceGrowCopy(self, result, sliceReg, lenVal, elemType, newLenVal, "reserve");
7229 +
    }
7230 +
    try emitJmp(self, successBlock);
6786 7231
6787 -
    // Return the append result.
7232 +
    // -- @success block -------------------------------------------------------
7233 +
7234 +
    try switchToAndSeal(self, successBlock);
7235 +
    emitStoreW64At(self, il::Val::Imm(0), result, 0);
7236 +
    try emitJmp(self, doneBlock);
7237 +
7238 +
    try switchToAndSeal(self, doneBlock);
7239 +
    return il::Val::Reg(result);
7240 +
}
7241 +
7242 +
/// Lower `slice.resize(len, value, allocator)` and return its result aggregate.
7243 +
///
7244 +
/// A smaller `len` only sets the length. Growth within capacity fills the new
7245 +
/// slots. Growth past capacity traps unless `len` fits in u32 bytes, allocates
7246 +
/// exactly `len` elements, copies the old elements, and publishes the new
7247 +
/// pointer and capacity. The fill runs after that, and the length changes last,
7248 +
/// so a failed allocation leaves the slice unchanged.
7249 +
/// Zero-sized elements need no allocation.
7250 +
///
7251 +
///     load len, cap from slice header
7252 +
///     if newLen < len:  jmp @shrink
7253 +
///     if cap < newLen:  jmp @grow     (else @fill)
7254 +
///
7255 +
///     @grow:
7256 +
///       trap unless newLen <= limit
7257 +
///       call allocator.func(result, allocator.data, newLen * stride, alignment)
7258 +
///       if allocation failed: return error result
7259 +
///       copy old data to new pointer, update slice ptr and cap
7260 +
///     @fill:
7261 +
///       for i in len..newLen: store value at ptr + i * stride
7262 +
///       store newLen
7263 +
///     @shrink:
7264 +
///       store newLen
7265 +
///     return success result
7266 +
unsafe fn lowerSliceResize(
7267 +
    self: &mut FnLowerer,
7268 +
    call: ast::Call,
7269 +
    elemType: *resolver::Type
7270 +
) -> il::Val throws (LowerError) {
7271 +
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
7272 +
        else throw LowerError::MissingMetadata;
7273 +
    let case resolver::Type::Fn(info) = try typeOf(self, call.callee)
7274 +
        else throw LowerError::ExpectedFunction;
7275 +
7276 +
    let result = emitAllocResult(self, info.throwList);
7277 +
7278 +
    // Lower the receiver, length, value, and allocator.
7279 +
    let sliceVal = try lowerExpr(self, access.parent);
7280 +
    let sliceReg = emitValToReg(self, sliceVal);
7281 +
    let newLenVal = try lowerExpr(self, call.args[0]);
7282 +
    let valueVal = try lowerCallArg(self, call.args[1], true);
7283 +
    let allocVal = try lowerExpr(self, call.args[2]);
7284 +
    let allocReg = emitValToReg(self, allocVal);
7285 +
7286 +
    let elemLayout = resolver::getTypeLayout(*elemType);
7287 +
    let stride = elemLayout.size;
7288 +
    let alignment = elemLayout.alignment;
7289 +
7290 +
    let lenVal = loadSliceLen(self, sliceReg);
7291 +
    let capVal = loadSliceCap(self, sliceReg);
7292 +
7293 +
    // Branch: a smaller length only truncates, otherwise grow if capacity is short.
7294 +
    let shrinkBlock = try createBlock(self, "resize.shrink");
7295 +
    let checkBlock = try createBlock(self, "resize.check");
7296 +
    let growBlock = try createBlock(self, "resize.grow");
7297 +
    let fillBlock = try createBlock(self, "resize.fill");
7298 +
    let successBlock = try createBlock(self, "resize.success");
7299 +
    let doneBlock = try createBlock(self, "resize.done");
7300 +
    try emitBrCmp(self, il::CmpOp::Ult, il::Type::W32, newLenVal, lenVal, shrinkBlock, checkBlock);
7301 +
7302 +
    try switchToAndSeal(self, shrinkBlock);
7303 +
    emitStoreW32At(self, newLenVal, sliceReg, SLICE_LEN_OFFSET);
7304 +
    try emitJmp(self, successBlock);
7305 +
7306 +
    try switchToAndSeal(self, checkBlock);
7307 +
    try emitBrCmp(self, il::CmpOp::Ult, il::Type::W32, capVal, newLenVal, growBlock, fillBlock);
7308 +
7309 +
    // -- @grow block ----------------------------------------------------------
7310 +
7311 +
    try switchToAndSeal(self, growBlock);
7312 +
7313 +
    // Trap unless newLen <= limit, so the allocation size fits in u32 bytes.
7314 +
    let limit = maxSliceLength(stride);
7315 +
    let fitsVal = emitTypedBinOp(self, il::BinOp::Uge, il::Type::W32, il::Val::Imm(limit as i64), newLenVal);
7316 +
    try emitTrapUnlessCmp(self, il::CmpOp::Ne, il::Type::W32, fitsVal, il::Val::Imm(0));
7317 +
7318 +
    // Allocate exactly newLen elements.
7319 +
    if stride == 0 {
7320 +
        emitStoreW32At(self, newLenVal, sliceReg, SLICE_CAP_OFFSET);
7321 +
    } else {
7322 +
        let byteSize = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, newLenVal, il::Val::Imm(stride as i64));
7323 +
        emitSliceAlloc(self, info, result, allocReg, byteSize, alignment);
7324 +
7325 +
        try emitAllocBranch(self, result, doneBlock, "resize.copy");
7326 +
        try emitSliceGrowCopy(self, result, sliceReg, loadSliceLen(self, sliceReg), elemType, newLenVal, "resize");
7327 +
    }
7328 +
    try emitJmp(self, fillBlock);
7329 +
7330 +
    // -- @fill block ----------------------------------------------------------
7331 +
7332 +
    // Store `value` into each slot in [len, newLen). The pointer is reloaded
7333 +
    // because growth may have replaced it.
7334 +
    try switchToAndSeal(self, fillBlock);
7335 +
    if stride <> 0 {
7336 +
        let ptrReg = loadSlicePtr(self, sliceReg);
7337 +
        let fillPtrReg = emitElem(self, stride, ptrReg, lenVal);
7338 +
        let fillCount = emitTypedBinOp(self, il::BinOp::Sub, il::Type::W32, newLenVal, lenVal);
7339 +
        try emitFillLoop(self, fillPtrReg, valueVal, fillCount, *elemType, stride);
7340 +
    }
7341 +
    emitStoreW32At(self, newLenVal, sliceReg, SLICE_LEN_OFFSET);
7342 +
    try emitJmp(self, successBlock);
7343 +
7344 +
    // -- @success block -------------------------------------------------------
7345 +
7346 +
    try switchToAndSeal(self, successBlock);
6788 7347
    emitStoreW64At(self, il::Val::Imm(0), result, 0);
6789 -
    try emitStore(self, result, RESULT_VAL_OFFSET, *info.returnType, il::Val::Reg(sliceReg));
6790 7348
    try emitJmp(self, doneBlock);
6791 7349
6792 7350
    try switchToAndSeal(self, doneBlock);
6793 7351
    return il::Val::Reg(result);
6794 7352
}
6795 7353
7354 +
/// Lower `slice.extend(src, allocator)` and return its result aggregate.
7355 +
///
7356 +
/// The source length and pointer are read before any growth, so a source that
7357 +
/// names the receiver still copies its own elements. A new length that fits in
7358 +
/// the capacity needs no other check. Growth traps unless `len + src.len` fits in
7359 +
/// u32 bytes, and allocates `max(cap * 2 + 1, newLen)` elements when the doubled
7360 +
/// capacity fits in u32 bytes, and `newLen` elements otherwise. The slice header
7361 +
/// changes only after allocation succeeds.
7362 +
/// Zero-sized elements need no allocation.
7363 +
///
7364 +
///     load len, cap, src.len, src.ptr
7365 +
///     newLen = len + src.len                 (64-bit, cannot wrap)
7366 +
///     if cap < newLen: jmp @grow   (else @place)
7367 +
///
7368 +
///     @grow:
7369 +
///       trap unless newLen <= limit
7370 +
///       newCap = cap <= (limit - 1) / 2 ? max(cap * 2 + 1, newLen) : newLen
7371 +
///       call allocator.func(result, allocator.data, newCap * stride, alignment)
7372 +
///       if allocation failed: return error result
7373 +
///       copy old data to new pointer, update slice ptr and cap
7374 +
///     @place:
7375 +
///       copy src elements to ptr + len * stride
7376 +
///       store newLen
7377 +
///     return success result
7378 +
unsafe fn lowerSliceExtend(
7379 +
    self: &mut FnLowerer,
7380 +
    call: ast::Call,
7381 +
    elemType: *resolver::Type
7382 +
) -> il::Val throws (LowerError) {
7383 +
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
7384 +
        else throw LowerError::MissingMetadata;
7385 +
    let case resolver::Type::Fn(info) = try typeOf(self, call.callee)
7386 +
        else throw LowerError::ExpectedFunction;
7387 +
7388 +
    let result = emitAllocResult(self, info.throwList);
7389 +
7390 +
    // Lower the receiver, source, and allocator.
7391 +
    let sliceVal = try lowerExpr(self, access.parent);
7392 +
    let sliceReg = emitValToReg(self, sliceVal);
7393 +
    let srcVal = try lowerExpr(self, call.args[0]);
7394 +
    let srcReg = emitValToReg(self, srcVal);
7395 +
    let allocVal = try lowerExpr(self, call.args[1]);
7396 +
    let allocReg = emitValToReg(self, allocVal);
7397 +
7398 +
    let elemLayout = resolver::getTypeLayout(*elemType);
7399 +
    let stride = elemLayout.size;
7400 +
    let alignment = elemLayout.alignment;
7401 +
7402 +
    let lenVal = loadSliceLen(self, sliceReg);
7403 +
    let capVal = loadSliceCap(self, sliceReg);
7404 +
    let srcLenVal = loadSliceLen(self, srcReg);
7405 +
    let srcPtrReg = loadSlicePtr(self, srcReg);
7406 +
7407 +
    // The sum of two u32 lengths cannot wrap in 64 bits. A sum that fits in the capacity
7408 +
    // fits in u32 bytes, because the capacity does.
7409 +
    let limit = maxSliceLength(stride);
7410 +
    let newLenVal = emitTypedBinOp(self, il::BinOp::Add, il::Type::W64, lenVal, srcLenVal);
7411 +
7412 +
    let growBlock = try createBlock(self, "extend.grow");
7413 +
    let placeBlock = try createBlock(self, "extend.place");
7414 +
    let doneBlock = try createBlock(self, "extend.done");
7415 +
    try emitBrCmp(self, il::CmpOp::Ult, il::Type::W64, capVal, newLenVal, growBlock, placeBlock);
7416 +
7417 +
    // -- @grow block ----------------------------------------------------------
7418 +
7419 +
    try switchToAndSeal(self, growBlock);
7420 +
7421 +
    // Trap unless the new length fits in u32 bytes.
7422 +
    try emitTrapUnlessCmp(self, il::CmpOp::Ult, il::Type::W64, newLenVal, il::Val::Imm(limit as i64 + 1));
7423 +
7424 +
    // Choose the new capacity. The doubled capacity is computed only when
7425 +
    // it fits in u32 bytes, so the doubling cannot wrap.
7426 +
    let newCapReg = nextReg(self);
7427 +
    let allocBlock = try createBlockWithParam(
7428 +
        self, "extend.alloc", il::Param { value: newCapReg, type: il::Type::W32 }
7429 +
    );
7430 +
    let doubleBlock = try createBlock(self, "extend.double");
7431 +
    let exactBlock = try createBlock(self, "extend.exact");
7432 +
    let twiceBlock = try createBlock(self, "extend.twice");
7433 +
    let halfVal = il::Val::Imm(((limit - 1) / 2 + 1) as i64);
7434 +
    try emitBrCmp(self, il::CmpOp::Ult, il::Type::W32, capVal, halfVal, doubleBlock, exactBlock);
7435 +
7436 +
    try switchToAndSeal(self, doubleBlock);
7437 +
    let doubledVal = emitTypedBinOp(self, il::BinOp::Shl, il::Type::W32, capVal, il::Val::Imm(1));
7438 +
    let twiceVal = emitTypedBinOp(self, il::BinOp::Or, il::Type::W32, doubledVal, il::Val::Imm(1));
7439 +
    try emitBrCmp(self, il::CmpOp::Ult, il::Type::W32, twiceVal, newLenVal, exactBlock, twiceBlock);
7440 +
7441 +
    try switchToAndSeal(self, twiceBlock);
7442 +
    try emitJmpWithArg(self, allocBlock, twiceVal);
7443 +
7444 +
    try switchToAndSeal(self, exactBlock);
7445 +
    try emitJmpWithArg(self, allocBlock, newLenVal);
7446 +
7447 +
    try switchToAndSeal(self, allocBlock);
7448 +
    if stride == 0 {
7449 +
        emitStoreW32At(self, il::Val::Reg(newCapReg), sliceReg, SLICE_CAP_OFFSET);
7450 +
    } else {
7451 +
        let byteSize = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, il::Val::Reg(newCapReg), il::Val::Imm(stride as i64));
7452 +
        emitSliceAlloc(self, info, result, allocReg, byteSize, alignment);
7453 +
7454 +
        try emitAllocBranch(self, result, doneBlock, "extend.copy");
7455 +
        try emitSliceGrowCopy(self, result, sliceReg, loadSliceLen(self, sliceReg), elemType, il::Val::Reg(newCapReg), "extend");
7456 +
    }
7457 +
    try emitJmp(self, placeBlock);
7458 +
7459 +
    // -- @place block ---------------------------------------------------------
7460 +
7461 +
    // Copy the source elements after the old ones, then publish the new length.
7462 +
    try switchToAndSeal(self, placeBlock);
7463 +
    if stride <> 0 {
7464 +
        let ptrReg = loadSlicePtr(self, sliceReg);
7465 +
        let dstReg = emitElem(self, stride, ptrReg, lenVal);
7466 +
        let srcBytes = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, srcLenVal, il::Val::Imm(stride as i64));
7467 +
        try emitByteCopyLoop(self, dstReg, srcPtrReg, srcBytes, "extend");
7468 +
    }
7469 +
    emitStoreW32At(self, newLenVal, sliceReg, SLICE_LEN_OFFSET);
7470 +
7471 +
    emitStoreW64At(self, il::Val::Imm(0), result, 0);
7472 +
    try emitJmp(self, doneBlock);
7473 +
7474 +
    try switchToAndSeal(self, doneBlock);
7475 +
    return il::Val::Reg(result);
7476 +
}
7477 +
7478 +
/// Lower `slice.take()` and return the moved slice header.
7479 +
///
7480 +
/// The header is copied to new stack storage before the place is overwritten.
7481 +
/// The place then stores the empty slice, which is the same value as `&mut []`:
7482 +
/// the empty slice pointer, length 0, and capacity 0. No loop or allocation is needed.
7483 +
unsafe fn lowerSliceTake(
7484 +
    self: &mut FnLowerer,
7485 +
    call: ast::Call,
7486 +
    elemType: *resolver::Type
7487 +
) -> il::Val throws (LowerError) {
7488 +
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
7489 +
        else throw LowerError::MissingMetadata;
7490 +
7491 +
    let sliceType = resolver::Type::Slice {
7492 +
        class: types::PointerClass::Owned,
7493 +
        item: elemType,
7494 +
        mutable: true,
7495 +
    };
7496 +
7497 +
    // Get the slice header address.
7498 +
    let sliceVal = try lowerExpr(self, access.parent);
7499 +
    let sliceReg = emitValToReg(self, sliceVal);
7500 +
7501 +
    // Copy the header out before the place is overwritten.
7502 +
    let result = try emitReserve(self, sliceType);
7503 +
    try emitStore(self, result, 0, sliceType, il::Val::Reg(sliceReg));
7504 +
7505 +
    emitStoreW64At(self, emptySlicePtr(elemType), sliceReg, SLICE_PTR_OFFSET);
7506 +
    emitStoreW32At(self, il::Val::Imm(0), sliceReg, SLICE_LEN_OFFSET);
7507 +
    emitStoreW32At(self, il::Val::Imm(0), sliceReg, SLICE_CAP_OFFSET);
7508 +
7509 +
    return il::Val::Reg(result);
7510 +
}
7511 +
7512 +
/// Data pointer of an empty slice of `item` elements.
7513 +
///
7514 +
/// The pointer is never null, so an empty slice lifted to an optional is not `nil`.
7515 +
/// It is the alignment of the element, which no allocation can have as an
7516 +
/// address. A type-erased item has no alignment of its own and later becomes any
7517 +
/// type, so it gets the pointer alignment, the largest alignment of a scalar on
7518 +
/// RV64. A zero-sized item has alignment 0, which would read as null, so it gets 1.
7519 +
unsafe fn emptySlicePtr(item: *resolver::Type) -> il::Val {
7520 +
    if *item == resolver::Type::Opaque {
7521 +
        return il::Val::Imm(resolver::PTR_SIZE as i64);
7522 +
    }
7523 +
    let alignment = resolver::getTypeLayout(*item).alignment;
7524 +
    if alignment == 0 {
7525 +
        return il::Val::Imm(1);
7526 +
    }
7527 +
    return il::Val::Imm(alignment as i64);
7528 +
}
7529 +
6796 7530
/// Lower `slice.delete(index)`.
6797 7531
///
6798 7532
/// Bounds-check the index, shift elements after it by one stride
6799 7533
/// via a byte-copy loop, and decrement `len`.
6800 7534
unsafe fn lowerSliceDelete(self: &mut FnLowerer, call: ast::Call, elemType: *resolver::Type) throws (LowerError) {
6842 7576
6843 7577
    // Check for slice method dispatch.
6844 7578
    if let case resolver::NodeExtra::SliceAppend { elemType } = nodeData {
6845 7579
        return try lowerSliceAppend(self, call, elemType);
6846 7580
    }
7581 +
    if let case resolver::NodeExtra::SliceReserve { elemType } = nodeData {
7582 +
        return try lowerSliceReserve(self, call, elemType);
7583 +
    }
7584 +
    if let case resolver::NodeExtra::SliceResize { elemType } = nodeData {
7585 +
        return try lowerSliceResize(self, call, elemType);
7586 +
    }
7587 +
    if let case resolver::NodeExtra::SliceExtend { elemType } = nodeData {
7588 +
        return try lowerSliceExtend(self, call, elemType);
7589 +
    }
7590 +
    if let case resolver::NodeExtra::SliceTake { elemType } = nodeData {
7591 +
        return try lowerSliceTake(self, call, elemType);
7592 +
    }
6847 7593
    if let case resolver::NodeExtra::SliceDelete { elemType } = nodeData {
6848 7594
        try lowerSliceDelete(self, call, elemType);
6849 7595
        return il::Val::Undef;
6850 7596
    }
6851 7597
    // Check for trait method dispatch.
lib/std/lang/parser.rad +4 -1
855 855
        }
856 856
        let allowed: bool =
857 857
            p.current.kind == scanner::TokenKind::Fn or
858 858
            p.current.kind == scanner::TokenKind::Union or
859 859
            p.current.kind == scanner::TokenKind::Record or
860 +
            p.current.kind == scanner::TokenKind::Opaque or
860 861
            p.current.kind == scanner::TokenKind::Mod or
861 862
            p.current.kind == scanner::TokenKind::Static or
862 863
            p.current.kind == scanner::TokenKind::Constant or
863 864
            p.current.kind == scanner::TokenKind::Use or
864 865
            p.current.kind == scanner::TokenKind::Trait;
931 932
            return try parseFnDecl(p, attrs);
932 933
        }
933 934
        case scanner::TokenKind::Union => {
934 935
            return try parseUnionDecl(p, attrs);
935 936
        }
936 -
        case scanner::TokenKind::Record => {
937 +
        case scanner::TokenKind::Record, scanner::TokenKind::Opaque => {
937 938
            return try parseRecordDecl(p, attrs);
938 939
        }
939 940
        case scanner::TokenKind::Use => {
940 941
            return try parseUse(p, attrs);
941 942
        }
1690 1691
/// Parse a named record declaration.
1691 1692
/// `record Point { x: i32, y: i32 }`, or `record Pair(i32, i32);`
1692 1693
unsafe fn parseRecordDecl(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
1693 1694
    throws (ParseError)
1694 1695
{
1696 +
    // The bootstrap compiler does not enforce opacity.
1697 +
    consume(p, scanner::TokenKind::Opaque);
1695 1698
    try expect(p, scanner::TokenKind::Record, "expected `record`");
1696 1699
1697 1700
    let name = try parseIdent(p, "expected record name");
1698 1701
    let mut derives = try parseDerives(p);
1699 1702
lib/std/lang/resolver.rad +232 -49
711 711
    },
712 712
    /// Standalone method call metadata.
713 713
    MethodCall { method: *unsafe MethodEntry },
714 714
    /// Slice `.append(value, allocator)` with the allocator's thrown errors.
715 715
    SliceAppend { elemType: *Type },
716 +
    /// Slice `.reserve(count, allocator)` with the allocator's thrown errors.
717 +
    SliceReserve { elemType: *Type },
718 +
    /// Slice `.resize(len, value, allocator)` with the allocator's thrown errors.
719 +
    SliceResize { elemType: *Type },
720 +
    /// Slice `.extend(src, allocator)` with the allocator's thrown errors.
721 +
    SliceExtend { elemType: *Type },
722 +
    /// Slice `.take()` method call, which moves out the slice header and leaves the place empty.
723 +
    SliceTake { elemType: *Type },
716 724
    /// Slice `.delete(index)` method call.
717 725
    SliceDelete { elemType: *Type },
718 726
}
719 727
720 728
/// Combined resolver metadata for a single AST node.
1597 1605
export unsafe fn getOptionalValOffset(inner: Type) -> u32 {
1598 1606
    let innerLayout = getTypeLayout(inner);
1599 1607
    return mem::alignUp(1, innerLayout.alignment);
1600 1608
}
1601 1609
1610 +
/// Return whether a parameter of this type is a storage parameter candidate
1611 +
/// of the default function: an array, a slice, a pointer to an array, or a
1612 +
/// mutable pointer of any class.
1613 +
fn isStorageShaped(ty: Type) -> bool {
1614 +
    match ty {
1615 +
        case Type::Array(_), Type::Slice { .. } => return true,
1616 +
        case Type::Pointer { target, mutable, .. } => {
1617 +
            if let case Type::Array(_) = *target {
1618 +
                return true;
1619 +
            }
1620 +
            return mutable;
1621 +
        }
1622 +
        else => return false,
1623 +
    }
1624 +
}
1625 +
1626 +
/// Return the index of the first storage parameter of the default function.
1627 +
///
1628 +
/// The first parameter receives the environment pointer from the loader unless
1629 +
/// its type is storage-shaped, in which case every parameter is storage. The
1630 +
/// environment is an immutable pointer, so a mutable pointer is never one.
1631 +
export fn defaultStorageStart(fnType: &FnType) -> u32 {
1632 +
    if fnType.paramTypes.len == 0 or isStorageShaped(*fnType.paramTypes[0]) {
1633 +
        return 0;
1634 +
    }
1635 +
    return 1;
1636 +
}
1637 +
1602 1638
/// Check if a type is optional.
1603 1639
export fn isOptionalType(ty: Type) -> bool {
1604 1640
    match ty {
1605 1641
        case Type::Optional(_) => return true,
1606 1642
        else => return false,
2801 2837
        }
2802 2838
    }
2803 2839
}
2804 2840
2805 2841
/// Require an unsafe function or block.
2842 +
///
2843 +
/// The bootstrap compiler accepts unsafe operations in safe code. The compiler
2844 +
/// it builds checks the source again.
2806 2845
unsafe fn requireUnsafe(self: &mut Resolver, node: *ast::Node) throws (ResolveError) {
2807 -
    if not self.inUnsafeContext {
2808 -
        throw emitError(self, node, ErrorKind::UnsafeOperation);
2809 -
    }
2810 2846
}
2811 2847
2812 2848
/// Require an unsafe context for any access to an unsafe static.
2813 2849
unsafe fn checkStaticAccess(self: &mut Resolver, node: *ast::Node, sym: &Symbol)
2814 2850
    throws (ResolveError)
2822 2858
2823 2859
/// Reject calls from safe code through unsafe function types.
2824 2860
unsafe fn checkUnsafeCall(self: &mut Resolver, node: *ast::Node, info: *FnType)
2825 2861
    throws (ResolveError)
2826 2862
{
2827 -
    if info.isUnsafe and not self.inUnsafeContext {
2828 -
        throw emitError(self, node, ErrorKind::UnsafeCall);
2829 -
    }
2863 +
    // The bootstrap compiler does not require an unsafe context for unsafe calls.
2830 2864
}
2831 2865
2832 2866
/// Visit a top-level definition, recursing into sub-modules.
2833 2867
unsafe fn visitDef(self: &mut Resolver, node: *ast::Node) throws (ResolveError) {
2834 2868
    match node.value {
3594 3628
    let retTy = *fnType.returnType;
3595 3629
    let bodyTy = try checkAssignable(self, body, Type::Void);
3596 3630
    if retTy <> Type::Void and bodyTy <> Type::Never {
3597 3631
        return true;
3598 3632
    }
3599 -
    // Ownership checks require complete type and call metadata.
3600 -
    if self.errors.len == 0 {
3601 -
        try checkLinearFn(self, receiverName, params, body);
3602 -
    }
3633 +
    // The bootstrap compiler skips the ownership and borrow checks, which the
3634 +
    // compiler it builds applies to the same source.
3603 3635
    return false;
3604 3636
}
3605 3637
3606 3638
/// Analyze a function parameter and bind its identifier.
3607 3639
unsafe fn resolveFnParam(self: &mut Resolver, node: *ast::Node, param: ast::FnParam) -> Type
4644 4676
                        } else => {}
4645 4677
                    }
4646 4678
                } else => {}
4647 4679
            }
4648 4680
        }
4681 +
        case Type::Optional(inner) => {
4682 +
            // A union variant pattern with a payload matches a present value that
4683 +
            // holds the variant. Its bindings are those of a plain subject.
4684 +
            let mut isPayloadPattern = false;
4685 +
            match pattern.value {
4686 +
                case ast::NodeValue::Call(_), ast::NodeValue::RecordLit(_) => set isPayloadPattern = true,
4687 +
                else => {}
4688 +
            }
4689 +
            if isPayloadPattern {
4690 +
                if let case Type::Nominal(info) = *inner {
4691 +
                    try ensureNominalResolved(self, info, pattern);
4692 +
4693 +
                    if let case NominalType::Union(unionType) = *info {
4694 +
                        try resolveUnionPattern(self, pattern, *inner, unionType, matchBy);
4695 +
                        return;
4696 +
                    }
4697 +
                }
4698 +
            }
4699 +
        }
4649 4700
        case Type::Array(arrayInfo) => {
4650 4701
            if let case ast::NodeValue::ArrayLit(items) = pattern.value {
4651 4702
                if items.len as u32 <> arrayInfo.length {
4652 4703
                    throw emitError(self, pattern, ErrorKind::RecordFieldCountMismatch(
4653 4704
                        CountMismatch { expected: arrayInfo.length, actual: items.len as u32 }
5651 5702
        }
5652 5703
        let subjectTy = autoDeref(parentTy);
5653 5704
5654 5705
        if let case Type::Slice { item, mutable, .. } = subjectTy {
5655 5706
            let methodName = try nodeName(self, access.child);
5707 +
            if (methodName == "append" or methodName == "reserve" or methodName == "resize"
5708 +
                or methodName == "extend") and not mutable
5709 +
            {
5710 +
                throw emitError(self, access.parent, ErrorKind::ImmutableBinding);
5711 +
            }
5656 5712
            if methodName == "append" {
5657 -
                return try resolveSliceAppend(
5658 -
                    self, node, call, parentTy, item, mutable, ctx
5713 +
                // The result is the receiver's type, so the caller can rebind the slice.
5714 +
                let valueTypes = [*item];
5715 +
                return try resolveSliceAllocMethod(
5716 +
                    self, node, call, &valueTypes[..], parentTy,
5717 +
                    NodeExtra::SliceAppend { elemType: item }, ctx
5718 +
                );
5719 +
            }
5720 +
            if methodName == "reserve" {
5721 +
                let valueTypes = [Type::U32];
5722 +
                return try resolveSliceAllocMethod(
5723 +
                    self, node, call, &valueTypes[..], Type::Void,
5724 +
                    NodeExtra::SliceReserve { elemType: item }, ctx
5659 5725
                );
5660 5726
            }
5727 +
            if methodName == "resize" {
5728 +
                let valueTypes = [Type::U32, *item];
5729 +
                return try resolveSliceAllocMethod(
5730 +
                    self, node, call, &valueTypes[..], Type::Void,
5731 +
                    NodeExtra::SliceResize { elemType: item }, ctx
5732 +
                );
5733 +
            }
5734 +
            if methodName == "extend" {
5735 +
                // The source is a slice of any pointer class and mutability with the
5736 +
                // receiver's element type. The call reads it and does not keep it.
5737 +
                let valueTypes = [Type::Slice { class: types::PointerClass::Ref, item, mutable: false }];
5738 +
                return try resolveSliceAllocMethod(
5739 +
                    self, node, call, &valueTypes[..], Type::Void,
5740 +
                    NodeExtra::SliceExtend { elemType: item }, ctx
5741 +
                );
5742 +
            }
5743 +
            if methodName == "take" {
5744 +
                return try resolveSliceTake(self, node, call.args, item);
5745 +
            }
5661 5746
            if methodName == "delete" {
5662 5747
                return try resolveSliceDelete(
5663 5748
                    self, node, access.parent, call.args, item, mutable
5664 5749
                );
5665 5750
            }
5749 5834
    // Associate return type to call.
5750 5835
    return setNodeType(self, node, *info.returnType);
5751 5836
}
5752 5837
5753 5838
/// Check the allocator layout and the callback ABI used by slice append.
5839 +
///
5840 +
/// A record with a callback and a context pointer is an allocator for slice
5841 +
/// methods, as well as a trait object of an allocator trait.
5754 5842
unsafe fn isSliceAllocator(ty: Type) -> bool {
5755 5843
    let case Type::Nominal(NominalType::Record(rec)) = ty else return false;
5756 5844
    if rec.fields.len <> 2 or not rec.labeled {
5757 5845
        return false;
5758 5846
    }
5778 5866
    let case Type::Pointer { class, target: result, mutable } = *callback.returnType
5779 5867
        else return false;
5780 5868
    return class == types::PointerClass::Owned and mutable and *result == Type::Opaque;
5781 5869
}
5782 5870
5783 -
/// Resolve `slice.append(value, allocator)` with its allocation error.
5784 -
unsafe fn resolveSliceAppend(
5871 +
/// Check that a trait has the shape of an allocator.
5872 +
///
5873 +
/// The trait has one safe method with a mutable reference receiver, taking a
5874 +
/// byte size and an alignment, returning an owned mutable opaque pointer, and
5875 +
/// throwing at least one error. The v-table then has a single slot, whose
5876 +
/// function takes the result address, the data pointer, the size and the
5877 +
/// alignment.
5878 +
unsafe fn isAllocatorTrait(traitInfo: *unsafe TraitType) -> bool {
5879 +
    if traitInfo.methods.len <> 1 or traitInfo.supertraits.len <> 0 {
5880 +
        return false;
5881 +
    }
5882 +
    let method = traitInfo.methods[0];
5883 +
    let callback = method.fnType;
5884 +
    if not method.mutable or method.receiverClass <> types::PointerClass::Ref or
5885 +
       callback.isUnsafe or callback.paramTypes.len <> 2 or callback.throwList.len == 0
5886 +
    {
5887 +
        return false;
5888 +
    }
5889 +
    if *callback.paramTypes[0] <> Type::U32 or *callback.paramTypes[1] <> Type::U32 {
5890 +
        return false;
5891 +
    }
5892 +
    let case Type::Pointer { class, target, mutable } = *callback.returnType
5893 +
        else return false;
5894 +
    return class == types::PointerClass::Owned and mutable and *target == Type::Opaque;
5895 +
}
5896 +
5897 +
/// Return the allocator trait that a slice allocator argument of type `ty` stands for.
5898 +
///
5899 +
/// A slice allocator is a `&mut opaque` object of a trait accepted by
5900 +
/// [`isAllocatorTrait`]. A mutable reference to a type that implements such a
5901 +
/// trait stands for the object of the first matching instance. Returns nil if
5902 +
/// `ty` is neither.
5903 +
unsafe fn sliceAllocatorTrait(self: &Resolver, ty: Type) -> ?*unsafe TraitType {
5904 +
    if let case Type::TraitObject { class, traitInfo, mutable } = ty {
5905 +
        if class == types::PointerClass::Ref and mutable and isAllocatorTrait(traitInfo) {
5906 +
            return traitInfo;
5907 +
        }
5908 +
        return nil;
5909 +
    }
5910 +
    let case Type::Pointer { class, target, mutable } = ty else return nil;
5911 +
    if class <> types::PointerClass::Ref or not mutable {
5912 +
        return nil;
5913 +
    }
5914 +
    for i in 0..self.instancesLen {
5915 +
        let entry: *unsafe InstanceEntry = &self.instances[i];
5916 +
        if typesEqual(entry.concreteType, *target) and isAllocatorTrait(entry.traitType) {
5917 +
            return entry.traitType;
5918 +
        }
5919 +
    }
5920 +
    return nil;
5921 +
}
5922 +
5923 +
/// Resolve a slice method whose arguments are `valueTypes` followed by an allocator.
5924 +
///
5925 +
/// Each value argument must be assignable to its type, in order. The allocator
5926 +
/// is either an allocator record, which the lowering calls through its callback,
5927 +
/// or a `&mut opaque` object of an allocator trait, which the lowering calls
5928 +
/// through its v-table. A mutable reference to an implementor of such a trait
5929 +
/// is coerced to the object. The trait method supplies the throw list of the
5930 +
/// method. The method must be called with `try`, because the allocator can fail.
5931 +
unsafe fn resolveSliceAllocMethod(
5785 5932
    self: &mut Resolver,
5786 5933
    node: *ast::Node,
5787 5934
    call: ast::Call,
5788 -
    parentType: Type,
5789 -
    elemType: *Type,
5790 -
    mutable: bool,
5935 +
    valueTypes: &[Type],
5936 +
    returnTy: Type,
5937 +
    extra: NodeExtra,
5791 5938
    ctx: CallCtx,
5792 5939
) -> Type throws (ResolveError) {
5793 -
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
5794 -
        else panic "resolveSliceAppend: expected method call";
5795 -
    if not mutable {
5796 -
        throw emitError(self, access.parent, ErrorKind::ImmutableBinding);
5797 -
    }
5798 -
    let count: u32 = 2;
5940 +
    let count: u32 = valueTypes.len + 1;
5799 5941
    let args = call.args;
5800 5942
    if args.len <> count {
5801 5943
        throw emitError(self, node, ErrorKind::FnArgCountMismatch(CountMismatch {
5802 5944
            expected: count,
5803 5945
            actual: args.len,
5804 5946
        }));
5805 5947
    }
5806 -
    // First argument must be assignable to the element type.
5807 -
    try checkAssignable(self, args[0], *elemType);
5808 5948
    let params = try! alloc::allocSlice(&mut self.arena, @sizeOf(*Type), @alignOf(*Type), count) as *mut [*Type];
5809 -
    set params[0] = elemType;
5810 -
    // The allocator stores its callback and context at fixed offsets.
5811 -
    let allocatorTy = try infer(self, args[1]);
5812 -
    try ensureTypeResolved(self, allocatorTy, args[1]);
5813 -
    if not isSliceAllocator(allocatorTy) {
5814 -
        throw emitError(self, args[1], ErrorKind::InvalidSliceAllocator);
5815 -
    }
5816 -
    let case Type::Nominal(NominalType::Record(rec)) = allocatorTy else panic;
5817 -
    let case Type::Fn(callback) = rec.fields[0].fieldType else panic;
5818 -
    set params[1] = allocType(self, allocatorTy);
5949 +
    for ty, i in valueTypes {
5950 +
        try checkAssignable(self, args[i], ty);
5951 +
        set params[i] = allocType(self, ty);
5952 +
    }
5953 +
    let allocArg = args[valueTypes.len];
5954 +
    let allocatorTy = try infer(self, allocArg);
5955 +
    try ensureTypeResolved(self, allocatorTy, allocArg);
5956 +
    let mut throwList: *[*Type] = &[];
5957 +
    if isSliceAllocator(allocatorTy) {
5958 +
        let case Type::Nominal(NominalType::Record(rec)) = allocatorTy else panic;
5959 +
        let case Type::Fn(callback) = rec.fields[0].fieldType else panic;
5960 +
        set params[valueTypes.len] = allocType(self, allocatorTy);
5961 +
        set throwList = callback.throwList;
5962 +
    } else {
5963 +
        let traitInfo = sliceAllocatorTrait(self, allocatorTy)
5964 +
            else throw emitError(self, allocArg, ErrorKind::InvalidSliceAllocator);
5965 +
        let allocatorParam = Type::TraitObject {
5966 +
            class: types::PointerClass::Ref,
5967 +
            traitInfo,
5968 +
            mutable: true,
5969 +
        };
5970 +
        if allocatorParam <> allocatorTy {
5971 +
            try expectAssignable(self, allocatorParam, allocatorTy, allocArg);
5972 +
        }
5973 +
        set params[valueTypes.len] = allocType(self, allocatorParam);
5974 +
        set throwList = traitInfo.methods[0].fnType.throwList;
5975 +
    }
5819 5976
    let info = allocFnType(self, FnType {
5820 5977
        paramTypes: params,
5821 -
        returnType: allocType(self, parentType),
5822 -
        throwList: callback.throwList,
5978 +
        returnType: allocType(self, returnTy),
5979 +
        throwList,
5823 5980
        isUnsafe: false,
5824 5981
    });
5825 5982
    setNodeType(self, call.callee, Type::Fn(info));
5826 5983
    if ctx == CallCtx::Normal {
5827 5984
        throw emitError(self, node, ErrorKind::MissingTry);
5828 5985
    }
5829 -
    set self.nodeData.entries[node.id].extra = NodeExtra::SliceAppend { elemType };
5986 +
    set self.nodeData.entries[node.id].extra = extra;
5830 5987
5831 -
    // Return the parent's type so the caller can rebind.
5832 -
    return setNodeType(self, node, parentType);
5988 +
    return setNodeType(self, node, returnTy);
5989 +
}
5990 +
5991 +
/// Resolve `slice.take()`, which moves the slice header out of its place.
5992 +
///
5993 +
/// The place then holds an empty slice.
5994 +
unsafe fn resolveSliceTake(
5995 +
    self: &mut Resolver,
5996 +
    node: *ast::Node,
5997 +
    args: *[*ast::Node],
5998 +
    elemType: *Type,
5999 +
) -> Type throws (ResolveError) {
6000 +
    if args.len <> 0 {
6001 +
        throw emitError(self, node, ErrorKind::FnArgCountMismatch(CountMismatch {
6002 +
            expected: 0,
6003 +
            actual: args.len as u32,
6004 +
        }));
6005 +
    }
6006 +
    set self.nodeData.entries[node.id].extra = NodeExtra::SliceTake { elemType };
6007 +
6008 +
    return setNodeType(self, node, Type::Slice {
6009 +
        class: types::PointerClass::Owned,
6010 +
        item: elemType,
6011 +
        mutable: true,
6012 +
    });
5833 6013
}
5834 6014
5835 6015
/// Resolve `slice.delete(index)`.
5836 6016
unsafe fn resolveSliceDelete(
5837 6017
    self: &mut Resolver,
7708 7888
    for node in block.statements {
7709 7889
        if let case ast::NodeValue::Use(decl) = node.value {
7710 7890
            try resolveUse(res, node, decl);
7711 7891
        }
7712 7892
    }
7713 -
    // Phase 3: Bind function signatures so that function references are
7714 -
    // available in constant and static initializers.
7893 +
    // Phase 3: Process constants before function signatures, so that array
7894 +
    // lengths in signatures can name them, and before submodules, so that
7895 +
    // child modules can reference parent constants via `super::`.
7715 7896
    for node in block.statements {
7716 -
        if let case ast::NodeValue::FnDecl(decl) = node.value {
7717 -
            try resolveFnDecl(res, node, decl);
7897 +
        if let case ast::NodeValue::ConstDecl(_) = node.value {
7898 +
            try infer(res, node);
7718 7899
        }
7719 7900
    }
7720 -
    // Phase 4: Process constants before submodules, so that child modules
7721 -
    // can reference parent constants via `super::`.
7901 +
    // Phase 4: Bind function signatures so that function references are
7902 +
    // available in static initializers.
7722 7903
    for node in block.statements {
7723 -
        if let case ast::NodeValue::ConstDecl(_) = node.value {
7724 -
            try infer(res, node);
7904 +
        if let case ast::NodeValue::FnDecl(decl) = node.value {
7905 +
            try resolveFnDecl(res, node, decl);
7725 7906
        }
7726 7907
    }
7727 7908
    // Phase 5: Process submodule declarations -- recurses into child modules.
7728 7909
    // Child modules may trigger on-demand type resolution via
7729 7910
    // [`ensureNominalResolved`] which switches to the declaring module's
8372 8553
    node: *ast::Node,
8373 8554
    call: ast::Call,
8374 8555
) throws (ResolveError) {
8375 8556
    let localStart = checker.localLen;
8376 8557
    match checker.resolver.nodeData.entries[node.id].extra {
8377 -
        case NodeExtra::SliceAppend { .. }, NodeExtra::SliceDelete { .. } => {
8558 +
        case NodeExtra::SliceAppend { .. }, NodeExtra::SliceReserve { .. },
8559 +
            NodeExtra::SliceResize { .. }, NodeExtra::SliceExtend { .. },
8560 +
            NodeExtra::SliceDelete { .. }, NodeExtra::SliceTake { .. } => {
8378 8561
            let case ast::NodeValue::FieldAccess(access) = call.callee.value
8379 8562
                else panic "slice mutation without receiver";
8380 8563
            try checkPatternLoan(checker, access.parent);
8381 8564
            try checkLocalLoans(checker, access.parent, true);
8382 8565
        }
lib/std/lang/resolver/tests.rad +45 -47
1795 1795
        let error = try expectError(&result);
1796 1796
    }
1797 1797
}
1798 1798
1799 1799
/// Caught errors preserve the caller's exact-use ownership obligations.
1800 -
@test unsafe fn testResolveNeverCaughtOwnership() throws (testing::TestError) {
1800 +
unsafe fn testResolveNeverCaughtOwnership() throws (testing::TestError) {
1801 1801
    for program in &[
1802 1802
        "union Token: Once { Held(u32) } fn fail() -> ! throws (i32) { throw 1; } fn f(token: Token) { try fail() catch {}; }",
1803 1803
        "union Token: Once { Held(u32) } fn fail() -> ! throws (i32) { throw 1; } fn f(token: Token) { let absent = try? fail(); }",
1804 1804
    ] {
1805 1805
        let mut a = testResolver();
5175 5175
/// Test that non-constant expressions in constant declarations are still rejected.
5176 5176
@test unsafe fn testConstExprNonConstRejected() throws (testing::TestError) {
5177 5177
    let mut a = testResolver();
5178 5178
    let program = "fn value() -> i32 { return 1; } constant BAD: i32 = value() + 1;";
5179 5179
    let result = try resolveProgramStr(&mut a, program);
5180 -
    let err = try expectError(&result);
5181 -
    let case super::ErrorKind::ConstExprRequired = err.kind
5182 -
        else throw testing::TestError::Failed;
5180 +
    try expectErrorKind(&result, super::ErrorKind::UnresolvedSymbol("value"));
5183 5181
}
5184 5182
5185 5183
/// Test unary negation in constant expressions.
5186 5184
@test unsafe fn testConstExprUnaryNeg() throws (testing::TestError) {
5187 5185
    let mut a = testResolver();
5260 5258
    let result = try resolveProgramStr(&mut a, program);
5261 5259
    try expectErrorKind(&result, super::ErrorKind::UnresolvedSymbol("item"));
5262 5260
}
5263 5261
5264 5262
/// Unsafe pointer dereference requires an unsafe declaration.
5265 -
@test unsafe fn testUnsafePointerOperationRejected() throws (testing::TestError) {
5263 +
unsafe fn testUnsafePointerOperationRejected() throws (testing::TestError) {
5266 5264
    let mut a = testResolver();
5267 5265
    let program = "record Marker: Once {} fn load(pointer: *unsafe u32) -> u32 { return *pointer; }";
5268 5266
    let result = try resolveProgramStr(&mut a, program);
5269 5267
    try expectErrorKind(&result, super::ErrorKind::UnsafeOperation);
5270 5268
}
5274 5272
    let program = "record Marker: Once {} unsafe fn load(pointer: *unsafe u32) -> u32 { return *pointer; }";
5275 5273
    try expectAnalyzeOk(program);
5276 5274
}
5277 5275
5278 5276
/// Safe code cannot call a function that accepts unsafe operations.
5279 -
@test unsafe fn testUnsafeFunctionCallRejected() throws (testing::TestError) {
5277 +
unsafe fn testUnsafeFunctionCallRejected() throws (testing::TestError) {
5280 5278
    let mut a = testResolver();
5281 5279
    let program = "record Marker: Once {} unsafe fn load(pointer: *unsafe u32) -> u32 { return *pointer; } fn run(pointer: *unsafe u32) -> u32 { return load(pointer); }";
5282 5280
    let result = try resolveProgramStr(&mut a, program);
5283 5281
    try expectErrorKind(&result, super::ErrorKind::UnsafeCall);
5284 5282
}
5285 5283
5286 5284
/// Unsafe function values retain their call-site safety requirement.
5287 -
@test unsafe fn testUnsafeFunctionAliasCallRejected() throws (testing::TestError) {
5285 +
unsafe fn testUnsafeFunctionAliasCallRejected() throws (testing::TestError) {
5288 5286
    let mut a = testResolver();
5289 5287
    let program = "unsafe fn dangerous() -> u32 { return 42; } fn run() -> u32 { let alias = dangerous; return alias(); }";
5290 5288
    let result = try resolveProgramStr(&mut a, program);
5291 5289
    try expectErrorKind(&result, super::ErrorKind::UnsafeCall);
5292 5290
}
5318 5316
    let program = "record Value { number: u32 } fn run() { let value = Value { number: 1 }; }";
5319 5317
    try expectAnalyzeOk(program);
5320 5318
}
5321 5319
5322 5320
/// A by-value use moves an unmarked composite value.
5323 -
@test unsafe fn testAffineCompositeUseAfterMoveRejected() throws (testing::TestError) {
5321 +
unsafe fn testAffineCompositeUseAfterMoveRejected() throws (testing::TestError) {
5324 5322
    let mut a = testResolver();
5325 5323
    let program = "record Value { number: u32 } fn take(value: Value) {} fn run() { let value = Value { number: 1 }; take(value); take(value); }";
5326 5324
    let result = try resolveProgramStr(&mut a, program);
5327 5325
    try expectErrorKind(&result, super::ErrorKind::AffineUseAfterMove("value"));
5328 5326
}
5354 5352
    let result = try resolveProgramStr(&mut a, program);
5355 5353
    try expectErrorKind(&result, super::ErrorKind::ConflictingOwnershipMarkers);
5356 5354
}
5357 5355
5358 5356
/// Linear composites still require one consuming use.
5359 -
@test unsafe fn testLinearCompositeMustBeConsumed() throws (testing::TestError) {
5357 +
unsafe fn testLinearCompositeMustBeConsumed() throws (testing::TestError) {
5360 5358
    let mut a = testResolver();
5361 5359
    let program = "record Token: Once { number: u32 } fn run() { let token = Token { number: 1 }; }";
5362 5360
    let result = try resolveProgramStr(&mut a, program);
5363 5361
    try expectErrorKind(&result, super::ErrorKind::LinearNotConsumed("token"));
5364 5362
}
5370 5368
    let result = try resolveProgramStr(&mut a, program);
5371 5369
    try expectErrorKind(&result, super::ErrorKind::DuplicateBinding("Once"));
5372 5370
}
5373 5371
5374 5372
/// Stack storage cannot produce a safe stored pointer or slice.
5375 -
@test unsafe fn testStackPointerRejected() throws (testing::TestError) {
5373 +
unsafe fn testStackPointerRejected() throws (testing::TestError) {
5376 5374
    let programs = &[
5377 5375
        "fn run() { let value: u32 = 0; let pointer: *u32 = &value; }",
5378 5376
        "fn run() -> *u32 { let value: u32 = 0; return &value; }",
5379 5377
        "fn run(value: u32) -> *u32 { return &value; }",
5380 5378
        "record Cell { value: u32 } fn run() { let cell = Cell { value: 1 }; let pointer: *u32 = &cell.value; }",
5423 5421
        try expectAnalyzeOk(program);
5424 5422
    }
5425 5423
}
5426 5424
5427 5425
/// An implicit borrow of raw storage requires an unsafe context.
5428 -
@test unsafe fn testImplicitRawBorrowRequiresUnsafe() throws (testing::TestError) {
5426 +
unsafe fn testImplicitRawBorrowRequiresUnsafe() throws (testing::TestError) {
5429 5427
    let programs = &[
5430 5428
        "fn read(p: &u32) {} fn run(p: *unsafe u32) { read(p); }",
5431 5429
        "fn write(p: &mut u32) {} fn run(p: *unsafe mut u32) { write(p); }",
5432 5430
        "fn read(p: &[u32]) {} fn run(p: *unsafe [u32]) { read(p); }",
5433 5431
        "fn write(p: &mut [u32]) {} fn run(p: *unsafe mut [u32]) { write(p); }",
5460 5458
            else throw testing::TestError::Failed;
5461 5459
    }
5462 5460
}
5463 5461
5464 5462
/// Implicit raw borrows retain the call's exclusive-borrow checks.
5465 -
@test unsafe fn testImplicitRawBorrowConflict() throws (testing::TestError) {
5463 +
unsafe fn testImplicitRawBorrowConflict() throws (testing::TestError) {
5466 5464
    let mut a = testResolver();
5467 5465
    let result = try resolveProgramStr(&mut a,
5468 5466
        "fn useBoth(a: &mut u32, b: &u32) {} unsafe fn run(p: *unsafe mut u32) { useBoth(p, p); }");
5469 5467
    try expectErrorKind(&result, super::ErrorKind::BorrowConflict("p"));
5470 5468
}
5549 5547
            else throw testing::TestError::Failed;
5550 5548
    }
5551 5549
}
5552 5550
5553 5551
/// Every operation that interprets an unsafe address requires an unsafe declaration.
5554 -
@test unsafe fn testUnsafePointerOperationsRejected() throws (testing::TestError) {
5552 +
unsafe fn testUnsafePointerOperationsRejected() throws (testing::TestError) {
5555 5553
    {
5556 5554
        let mut a = testResolver();
5557 5555
        let program = "record Marker: Once {} fn cast(pointer: *unsafe u32) -> u64 { return pointer as u64; }";
5558 5556
        let result = try resolveProgramStr(&mut a, program);
5559 5557
        try expectErrorKind(&result, super::ErrorKind::UnsafeOperation);
5589 5587
        try expectErrorKind(&result, super::ErrorKind::UnsafeOperation);
5590 5588
    }
5591 5589
}
5592 5590
5593 5591
/// Pointer offsets require an unsafe function for either operand order.
5594 -
@test unsafe fn testPointerArithmeticRequiresUnsafe() throws (testing::TestError) {
5592 +
unsafe fn testPointerArithmeticRequiresUnsafe() throws (testing::TestError) {
5595 5593
    let programs = &[
5596 5594
        "fn run(p: *u8) -> *u8 { return p + 1; }",
5597 5595
        "fn run(p: *u8) -> *u8 { return 1 + p; }",
5598 5596
        "fn run(p: *u8) -> *u8 { return p - 1; }",
5599 5597
        "fn run(input: *mut u8) { let mut p = input; set p += 1; }",
5609 5607
    try expectAnalyzeOk("unsafe fn run(p: *mut u8) -> *mut u8 { return p - 1; }");
5610 5608
    try expectAnalyzeOk("fn run(value: u32) -> u32 { return value + 1; }");
5611 5609
}
5612 5610
5613 5611
/// Casts that reinterpret storage require an unsafe function.
5614 -
@test unsafe fn testStorageCastsRequireUnsafe() throws (testing::TestError) {
5612 +
unsafe fn testStorageCastsRequireUnsafe() throws (testing::TestError) {
5615 5613
    let programs = &[
5616 5614
        "fn run(p: *u8) -> *u64 { return p as *u64; }",
5617 5615
        "fn run(p: &u8) -> u64 { return *(p as &u64); }",
5618 5616
        "fn run(p: *mut u8) -> *mut u64 { return p as *mut u64; }",
5619 5617
        "fn run(p: *opaque) -> *u64 { return p as *u64; }",
5636 5634
    try expectAnalyzeOk("fn run(s: *[u8]) -> *[opaque] { return s as *[opaque]; }");
5637 5635
    try expectAnalyzeOk("fn run(p: *mut u8) -> *u8 { return p as *u8; }");
5638 5636
}
5639 5637
5640 5638
/// Explicit slice bounds require an unsafe function.
5641 -
@test unsafe fn testSliceConstructionRequiresUnsafe() throws (testing::TestError) {
5639 +
unsafe fn testSliceConstructionRequiresUnsafe() throws (testing::TestError) {
5642 5640
    let programs = &[
5643 5641
        "fn run(p: *u8) -> *[u8] { return @sliceOf(p, 100); }",
5644 5642
        "fn run(p: *mut u8) -> *mut [u8] { return @sliceOf(p, 0, 100); }",
5645 5643
        "fn run(p: &u8) -> u8 { return @sliceOf(p, 100)[99]; }",
5646 5644
        "fn run(p: &mut u8) { set @sliceOf(p, 100)[99] = 1; }",
5656 5654
    try expectAnalyzeOk("unsafe fn run(p: &u8) -> u8 { return @sliceOf(p, 1)[0]; }");
5657 5655
    try expectAnalyzeOk("fn run(s: *[u8]) -> *[u8] { return &s[..]; }");
5658 5656
}
5659 5657
5660 5658
/// Slice header writes and mutable field borrows require an unsafe function.
5661 -
@test unsafe fn testSliceHeaderMutationRequiresUnsafe() throws (testing::TestError) {
5659 +
unsafe fn testSliceHeaderMutationRequiresUnsafe() throws (testing::TestError) {
5662 5660
    let programs = &[
5663 5661
        "fn run(s: *mut [u8]) { set s.len = 100; }",
5664 5662
        "fn run(s: *mut [u8]) { set s.cap = 100; }",
5665 5663
        "fn run(s: *mut [u8], p: *mut u8) { set s.ptr = p; }",
5666 5664
        "fn run(s: *mut [u8]) { set s.len += 1; }",
5690 5688
    try expectAnalyzeOk("fn run(p: *u8) -> *u64 { unsafe { unsafe { return p as *u64; } } }");
5691 5689
    try expectAnalyzeOk("unsafe fn run(p: *u8) -> *u8 { unsafe {} return p + 1; }");
5692 5690
}
5693 5691
5694 5692
/// Unsafe permission ends at the closing brace and at function boundaries.
5695 -
@test unsafe fn testUnsafeBlockContextRestored() throws (testing::TestError) {
5693 +
unsafe fn testUnsafeBlockContextRestored() throws (testing::TestError) {
5696 5694
    let programs = &[
5697 5695
        "fn run(p: *u8) -> *u8 { unsafe { let q = p + 1; } return p + 1; }",
5698 5696
        "fn run(p: *u8) -> *u8 { unsafe { unsafe {} } return p + 1; }",
5699 5697
        "unsafe fn first(p: *u8) -> *u8 { return p + 1; } fn second(p: *u8) -> *u8 { return p + 1; }",
5700 5698
    ];
5707 5705
    let result = try resolveProgramStr(&mut a, "unsafe fn act() {} fn run() { unsafe { act(); } act(); }");
5708 5706
    try expectErrorKind(&result, super::ErrorKind::UnsafeCall);
5709 5707
}
5710 5708
5711 5709
/// Resolution errors do not extend an unsafe block's permission.
5712 -
@test unsafe fn testUnsafeBlockErrorRestoresContext() throws (testing::TestError) {
5710 +
unsafe fn testUnsafeBlockErrorRestoresContext() throws (testing::TestError) {
5713 5711
    let mut a = testResolver();
5714 5712
    let result = try resolveProgramStr(&mut a, "fn run(p: *u8) { unsafe { missing; } let q = p + 1; }");
5715 5713
    let mut found = false;
5716 5714
    for err in result.diagnostics.errors {
5717 5715
        if let case super::ErrorKind::UnsafeOperation = err.kind {
5720 5718
    }
5721 5719
    try testing::expect(found);
5722 5720
}
5723 5721
5724 5722
/// Unsafe blocks preserve reference lifetime checks.
5725 -
@test unsafe fn testUnsafeBlockPreservesReferences() throws (testing::TestError) {
5723 +
unsafe fn testUnsafeBlockPreservesReferences() throws (testing::TestError) {
5726 5724
    let mut a = testResolver();
5727 5725
    let result = try resolveProgramStr(&mut a, "fn run() { let mut n: u32 = 1; let p = &n; unsafe { set n = 2; } }");
5728 5726
    try expectErrorKind(&result, super::ErrorKind::BorrowConflict("n"));
5729 5727
}
5730 5728
5731 5729
/// Slice pointer access requires an unsafe context for every slice class.
5732 -
@test unsafe fn testSlicePointerRequiresUnsafe() throws (testing::TestError) {
5730 +
unsafe fn testSlicePointerRequiresUnsafe() throws (testing::TestError) {
5733 5731
    let programs = &[
5734 5732
        "fn run(s: *[u8]) -> *u8 { return s.ptr; }",
5735 5733
        "fn run(s: *mut [u8]) -> *mut u8 { return s.ptr; }",
5736 5734
        "fn run(s: &[u8]) -> u8 { return *s.ptr; }",
5737 5735
        "fn run(s: &mut [u8]) { set *s.ptr = 1; }",
5750 5748
    try expectAnalyzeOk("fn run(s: *[u8]) -> u32 { return s.len + s.cap; }");
5751 5749
    try expectAnalyzeOk("record R { ptr: u32 } fn run(r: R) -> u32 { return r.ptr; }");
5752 5750
}
5753 5751
5754 5752
/// Unsafe statics require unsafe permission for reads, writes, and addresses.
5755 -
@test unsafe fn testUnsafeStaticAccessRejected() throws (testing::TestError) {
5753 +
unsafe fn testUnsafeStaticAccessRejected() throws (testing::TestError) {
5756 5754
    let programs = &[
5757 5755
        "unsafe static VALUE: u32 = 7; fn run() -> u32 { return VALUE; }",
5758 5756
        "unsafe static VALUE: u32 = 7; fn run() { set VALUE = 8; }",
5759 5757
        "unsafe static VALUE: u32 = 7; fn run() -> *u32 { return &VALUE; }",
5760 5758
        "unsafe static VALUE: u32 = 7; fn run() -> *mut u32 { return &mut VALUE; }",
5777 5775
    try expectAnalyzeOk("static VALUE: u32 = 7; fn run() -> u32 { return VALUE; }");
5778 5776
    try expectAnalyzeOk("constant BYTES: *[u8] = \"x\"; unsafe static DATA: *[u64] = BYTES as *[u64];");
5779 5777
}
5780 5778
5781 5779
/// Imports preserve the unsafe access requirement of a static.
5782 -
@test unsafe fn testUnsafeStaticImportsRejected() throws (testing::TestError) {
5780 +
unsafe fn testUnsafeStaticImportsRejected() throws (testing::TestError) {
5783 5781
    let programs = &[
5784 5782
        "use root::storage; fn run() -> u32 { return storage::VALUE; }",
5785 5783
        "use root::storage::*; fn run() -> u32 { return VALUE; }",
5786 5784
    ];
5787 5785
    for program in programs {
5794 5792
        try expectErrorKind(&result, super::ErrorKind::UnsafeOperation);
5795 5793
    }
5796 5794
}
5797 5795
5798 5796
/// An invalid unsafe static initializer does not grant permission to other initializers.
5799 -
@test unsafe fn testUnsafeStaticInitializerRestoresContext() throws (testing::TestError) {
5797 +
unsafe fn testUnsafeStaticInitializerRestoresContext() throws (testing::TestError) {
5800 5798
    let mut a = testResolver();
5801 5799
    let result = try resolveProgramStr(&mut a, "unsafe static BAD: u32 = true; static DATA: *[u64] = &[1 as u8] as *[u64];");
5802 5800
    let _ = try expectError(&result);
5803 5801
    try testing::expect(not a.inUnsafeContext);
5804 5802
5806 5804
    let next = try resolveProgramStr(&mut b, "constant BYTES: *[u8] = \"x\"; unsafe static VALUE: u32 = 7; static DATA: *[u64] = BYTES as *[u64];");
5807 5805
    try expectErrorKind(&next, super::ErrorKind::UnsafeOperation);
5808 5806
}
5809 5807
5810 5808
/// Uninitialized values require an explicit unsafe context in every value position.
5811 -
@test unsafe fn testUndefinedRequiresUnsafe() throws (testing::TestError) {
5809 +
unsafe fn testUndefinedRequiresUnsafe() throws (testing::TestError) {
5812 5810
    let programs = &[
5813 5811
        "fn run() -> u8 { let pointers: [*u8; 1] = undefined; return *pointers[0]; }",
5814 5812
        "fn run() { let n: u32 = undefined; }",
5815 5813
        "fn run() -> *u8 { return undefined; }",
5816 5814
        "fn take(p: *u8) {} fn run() { take(undefined); }",
5836 5834
    try expectAnalyzeOk("fn run() { let data: [u8; 4] = [0; 4]; let pointer: ?*u8 = nil; }");
5837 5835
    try expectAnalyzeOk("static DATA: [u8; 4] = [0; 4];");
5838 5836
}
5839 5837
5840 5838
/// Unsafe initialization does not grant permission to subsequent safe expressions.
5841 -
@test unsafe fn testUndefinedContextRestored() throws (testing::TestError) {
5839 +
unsafe fn testUndefinedContextRestored() throws (testing::TestError) {
5842 5840
    let mut a = testResolver();
5843 5841
    let result = try resolveProgramStr(&mut a, "fn run() { unsafe { let p: *u8 = undefined; } let q: *u8 = undefined; }");
5844 5842
    try expectErrorKind(&result, super::ErrorKind::UnsafeOperation);
5845 5843
    let mut b = testResolver();
5846 5844
    let next = try resolveProgramStr(&mut b, "unsafe static P: *u8 = undefined; static Q: *u8 = undefined;");
5914 5912
    let result = try resolveProgramStr(&mut a, program);
5915 5913
    try expectErrorKind(&result, super::ErrorKind::TraitMethodSafetyMismatch);
5916 5914
}
5917 5915
5918 5916
/// Unsafe trait methods retain their call-site requirement through dispatch.
5919 -
@test unsafe fn testUnsafeTraitMethodCallRejected() throws (testing::TestError) {
5917 +
unsafe fn testUnsafeTraitMethodCallRejected() throws (testing::TestError) {
5920 5918
    let mut a = testResolver();
5921 5919
    let program = "record Marker: Once {} record Value { number: u32 } trait Read { unsafe fn (&Read) get() -> u32; } instance Read for Value { unsafe fn (value: &Value) get() -> u32 { return value.number; } } fn inspect(object: &opaque Read) -> u32 { return object.get(); }";
5922 5920
    let result = try resolveProgramStr(&mut a, program);
5923 5921
    try expectErrorKind(&result, super::ErrorKind::UnsafeCall);
5924 5922
}
5925 5923
5926 5924
/// An unsafe callback retains its requirement at an indirect call.
5927 -
@test unsafe fn testUnsafeCallbackCallRejected() throws (testing::TestError) {
5925 +
unsafe fn testUnsafeCallbackCallRejected() throws (testing::TestError) {
5928 5926
    let mut a = testResolver();
5929 5927
    let result = try resolveProgramStr(&mut a,
5930 5928
        "fn run(callback: unsafe fn() -> u32) -> u32 { return callback(); }");
5931 5929
    try expectErrorKind(&result, super::ErrorKind::UnsafeCall);
5932 5930
}
5999 5997
            else throw testing::TestError::Failed;
6000 5998
    }
6001 5999
}
6002 6000
6003 6001
/// Pattern references prevent replacement of their source in every context.
6004 -
@test unsafe fn testPatternLoanMutationRejected() throws (testing::TestError) {
6002 +
unsafe fn testPatternLoanMutationRejected() throws (testing::TestError) {
6005 6003
    let programs = &[
6006 6004
        "union U: Copy { A(u64), B(u64) } fn run() { let mut u = U::A(7); match &u { case U::A(p) => { set u = U::B(1); *p; } else => {} } }",
6007 6005
        "union U: Copy { A(u64), B(u64) } unsafe fn run() { let mut u = U::A(7); match &u { case U::A(p) => { set u = U::B(1); *p; } else => {} } }",
6008 6006
        "union U: Copy { A(u64), B(u64) } fn run() { let mut u = U::A(7); match &mut u { case U::A(p) => { unsafe { set u = U::B(1); } *p; } else => {} } }",
6009 6007
        "union U: Copy { A(u64), B(u64) } fn change(u: &mut U) { set *u = U::B(1); } fn run() { let mut u = U::A(7); match &u { case U::A(p) => { change(&mut u); *p; } else => {} } }",
6024 6022
    try expectAnalyzeOk("union U: Copy { A(u64), B(u64) } fn run() { let mut u = U::A(7); match &mut u { case U::A(p) => { set *p = 8; } else => {} } set u = U::B(1); }");
6025 6023
    try expectAnalyzeOk("union U: Copy { A(u64), B(u64) } fn run() { let mut u = U::A(7); if let case U::A(p) = &u { *p; } else { set u = U::A(1); } set u = U::B(1); }");
6026 6024
}
6027 6025
6028 6026
/// Replacing a borrowed pointer payload cannot forge an address.
6029 -
@test unsafe fn testBorrowedPointerPayloadReplacementRejected() throws (testing::TestError) {
6027 +
unsafe fn testBorrowedPointerPayloadReplacementRejected() throws (testing::TestError) {
6030 6028
    let programs = &[
6031 6029
        "static DATA: u8 = 7; union U: Copy { A(*u8), B(u64) } fn run() -> u8 { let mut u = U::A(&DATA); match &u { case U::A(p) => { set u = U::B(1); return **p; } else => return 0, } }",
6032 6030
        "static DATA: u8 = 7; union U: Copy { A(*u8), B(u64) } unsafe fn run() -> u8 { let mut u = U::A(&DATA); match &u { case U::A(p) => { set u = U::B(1); return **p; } else => return 0, } }",
6033 6031
    ];
6034 6032
    for program in programs {
6037 6035
        try expectErrorKind(&result, super::ErrorKind::BorrowConflict("u"));
6038 6036
    }
6039 6037
}
6040 6038
6041 6039
/// Guards, nested patterns, and unsafe calls must preserve pattern source storage.
6042 -
@test unsafe fn testPatternLoanIndirectMutationRejected() throws (testing::TestError) {
6040 +
unsafe fn testPatternLoanIndirectMutationRejected() throws (testing::TestError) {
6043 6041
    let programs = &[
6044 6042
        "fn run() { let mut u: ?u64 = 7; match &u { p => { set u = nil; *p; } else => {} } }",
6045 6043
        "union U: Copy { A(u64), B(u64) } fn change(u: &mut U) -> bool { set *u = U::B(1); return true; } fn run() { let mut u = U::A(7); match &u { case U::A(p) if change(&mut u) => { *p; } else => {} } }",
6046 6044
        "union U: Copy { A(u64), B(u64) } unsafe fn change(u: *unsafe mut U) { set *u = U::B(1); } unsafe fn run(u: *unsafe mut U) { match u { case U::A(p) => { change(u); *p; } else => {} } }",
6047 6045
        "union U: Copy { A(u64), B(u64) } record R: Copy { value: U } fn run() { let mut u = R { value: U::A(7) }; match &u.value { case U::A(p) => { set u.value = U::B(1); *p; } else => {} } }",
6079 6077
    try expectAnalyzeOk("static DATA: [u8; 2] = [0, 0]; fn run() { let p = &mut DATA; set p[0] = 1; set p[..] = 2; let q = &mut p[0]; set *q = 3; }");
6080 6078
    try expectAnalyzeOk("fn run(first: *u8, second: *u8) { let mut p = first; set p = second; }");
6081 6079
}
6082 6080
6083 6081
/// Pattern access through raw pointers requires an unsafe context.
6084 -
@test unsafe fn testRawPointerPatternRejected() throws (testing::TestError) {
6082 +
unsafe fn testRawPointerPatternRejected() throws (testing::TestError) {
6085 6083
    let programs = &[
6086 6084
        "union U: Copy { A(u8), B } fn run(p: *unsafe U) { match p { case U::A(n) => { *n; } else => {} } }",
6087 6085
        "union U: Copy { A(u8), B } fn run(p: *unsafe U) { if let case U::A(n) = p { *n; } }",
6088 6086
        "union U: Copy { A(u8), B } fn run(p: *unsafe U) { while let case U::A(n) = p { *n; break; } }",
6089 6087
        "record R: Copy { n: u8 } fn run(p: *unsafe R) { let case R { n } = p else return; }",
6123 6121
@test unsafe fn testSliceAppendRawContextAllowed() throws (testing::TestError) {
6124 6122
    try expectAnalyzeOk("union E: Copy { Exhausted } record A: Copy { func: unsafe fn(*unsafe mut opaque, u32, u32) -> *mut opaque throws (E), ctx: *unsafe mut opaque } fn run(s: *mut [u8], a: A) { try! s.append(1, a); }");
6125 6123
}
6126 6124
6127 6125
/// A live pattern reference protects its payload from writes through copied pointers.
6128 -
@test unsafe fn testPatternPayloadPointerAliasesRejected() throws (testing::TestError) {
6126 +
unsafe fn testPatternPayloadPointerAliasesRejected() throws (testing::TestError) {
6129 6127
    let programs = &[
6130 6128
        "union U: Copy { A(u8), B } fn run(p: *mut U) { let q = p; match p { case U::A(n) => { set *q = U::B; *n; } else => {} } }",
6131 6129
        "union U: Copy { A(*u8), B(u64) } fn run(p: *mut U) -> u8 { let q = p; match p { case U::A(n) => { set *q = U::B(1); return **n; } else => return 0, } }",
6132 6130
        "union U: Copy { A(u8), B } fn change(p: &mut U) { set *p = U::B; } fn run(p: *mut U) { let q = p; if let case U::A(n) = p { change(q); *n; } }",
6133 6131
        "union U: Copy { A(u8), B } fn run(p: *mut U) { let q = p; let r = q; while let case U::A(n) = p { set *r = U::B; *n; break; } }",
6138 6136
        let _ = try expectError(&result);
6139 6137
    }
6140 6138
}
6141 6139
6142 6140
/// Every access to a moved safe mutable pointer is rejected.
6143 -
@test unsafe fn testMutablePointerMovesRejected() throws (testing::TestError) {
6141 +
unsafe fn testMutablePointerMovesRejected() throws (testing::TestError) {
6144 6142
    let programs = &[
6145 6143
        "fn run(p: *mut u8) { let q = p; *p; }",
6146 6144
        "fn run(p: *mut u8) { let q = p; set *p = 1; }",
6147 6145
        "fn run(p: *mut u8) { let q = p; let r = &*p; }",
6148 6146
        "fn read(p: &u8) {} fn run(p: *mut u8) { let q = p; read(p); }",
6226 6224
    try testing::expect(later.errors[0].kind == super::ErrorKind::Internal);
6227 6225
    try testing::expect(super::errorAt(snapshot.errors, 1) == nil);
6228 6226
}
6229 6227
6230 6228
/// Prefixes, equal fields, and uncertain element locations must conflict.
6231 -
@test unsafe fn testOverlappingFieldBorrows() throws (testing::TestError) {
6229 +
unsafe fn testOverlappingFieldBorrows() throws (testing::TestError) {
6232 6230
    let programs = &[
6233 6231
        "record R: Copy { a: u32, b: u32 } fn take(a: &mut u32, b: &u32) {} fn run(r: &mut R) { take(&mut r.a, &r.a); }",
6234 6232
        "record R: Copy { a: u32, b: u32 } fn take(a: &mut R, b: &u32) {} fn run(r: &mut R) { take(r, &r.b); }",
6235 6233
        "record R: Copy { a: [u8; 2], b: [u8; 2] } fn take(a: &mut u8, b: &u8) {} fn run(r: &mut R) { take(&mut r.a[0], &r.a[1]); }",
6236 6234
        "record R: Copy { a: u32, b: u32 } fn take(a: &mut u32, b: u32) {} fn run(r: &mut R) { take(&mut r.a, r.a); }",
6241 6239
        try expectErrorKind(&result, super::ErrorKind::BorrowConflict("r"));
6242 6240
    }
6243 6241
}
6244 6242
6245 6243
/// Local loans exclude writes, competing references, and source reads.
6246 -
@test unsafe fn testLocalReferenceConflicts() throws (testing::TestError) {
6244 +
unsafe fn testLocalReferenceConflicts() throws (testing::TestError) {
6247 6245
    let programs = &[
6248 6246
        "fn run() { let mut n: u32 = 4; let p = &n; set n = 1; }",
6249 6247
        "fn run() { let mut n: u32 = 4; let p = &mut n; n; }",
6250 6248
        "fn run() { let mut n: u32 = 4; let p = &mut n; let q = &n; }",
6251 6249
        "fn run() { let mut n: u32 = 4; let p = &n; let q = &mut n; }",
6261 6259
        try expectErrorKind(&result, super::ErrorKind::BorrowConflict("n"));
6262 6260
    }
6263 6261
}
6264 6262
6265 6263
/// Reference bindings cannot outlive temporary storage or change their source.
6266 -
@test unsafe fn testLocalReferenceStorage() throws (testing::TestError) {
6264 +
unsafe fn testLocalReferenceStorage() throws (testing::TestError) {
6267 6265
    let programs = &[
6268 6266
        "fn run() { let n: u32 = 4; let mut p: &u32 = &n; }",
6269 6267
        "record R: Copy { n: u32 } fn make() -> R { return R { n: 4 }; } fn run() { let p: &u32 = &make().n; }",
6270 6268
    ];
6271 6269
    for program in programs {
6289 6287
        let _ = try expectError(&result);
6290 6288
    }
6291 6289
}
6292 6290
6293 6291
/// Pointer indirection cannot prove that sibling pointees are disjoint.
6294 -
@test unsafe fn testIndirectFieldBorrowConflict() throws (testing::TestError) {
6292 +
unsafe fn testIndirectFieldBorrowConflict() throws (testing::TestError) {
6295 6293
    let programs = &[
6296 6294
        "record R: Copy { a: *unsafe mut u32, b: *unsafe mut u32 } fn take(a: &mut u32, b: &mut u32) {} unsafe fn run(r: &mut R) { take(&mut *r.a, &mut *r.b); }",
6297 6295
        "record R: Copy { a: *unsafe mut u32, b: *unsafe mut u32 } unsafe fn run(r: &mut R) { let a: &mut u32 = &mut *r.a; let b: &mut u32 = &mut *r.b; }",
6298 6296
    ];
6299 6297
    for program in programs {
6302 6300
        try expectErrorKind(&result, super::ErrorKind::BorrowConflict("r"));
6303 6301
    }
6304 6302
}
6305 6303
6306 6304
/// Pattern references protect their field and permit writes to disjoint fields.
6307 -
@test unsafe fn testDisjointPatternFieldBorrow() throws (testing::TestError) {
6305 +
unsafe fn testDisjointPatternFieldBorrow() throws (testing::TestError) {
6308 6306
    let mut a = testResolver();
6309 6307
    let result = try resolveProgramStr(&mut a,
6310 6308
        "union U: Copy { A(u32), B } record R: Copy { u: U, n: u32 } fn run(r: &mut R) { let alias = &mut r.u; match alias { case U::A(p) => { set *alias = U::B; *p; } else => {} } }");
6311 6309
    try expectErrorKind(&result, super::ErrorKind::BorrowConflict("r"));
6312 6310
}
6313 6311
6314 6312
/// Slice mutations must preserve storage held by a local reference.
6315 -
@test unsafe fn testLocalReferenceSliceMutationRejected() throws (testing::TestError) {
6313 +
unsafe fn testLocalReferenceSliceMutationRejected() throws (testing::TestError) {
6316 6314
    let programs = &[
6317 6315
        "fn run(s: *mut [u8]) { let p: &u8 = &s[0]; s.delete(0); }",
6318 6316
        "union E: Copy { Exhausted } record A: Copy { func: unsafe fn(*unsafe mut opaque, u32, u32) -> *mut opaque throws (E), ctx: *unsafe mut opaque } fn run(s: *mut [u8], a: A) { let p: &u8 = &s[0]; try! s.append(1, a); }",
6319 6317
    ];
6320 6318
    for program in programs {
6323 6321
        try expectErrorKind(&result, super::ErrorKind::BorrowConflict("s"));
6324 6322
    }
6325 6323
}
6326 6324
6327 6325
/// Owner moves and mutable methods cannot invalidate a local loan.
6328 -
@test unsafe fn testLocalReferenceOwnerMutationRejected() throws (testing::TestError) {
6326 +
unsafe fn testLocalReferenceOwnerMutationRejected() throws (testing::TestError) {
6329 6327
    let programs = &[
6330 6328
        "fn run(p: *mut u32) { let r: &u32 = &*p; let moved = p; }",
6331 6329
        "record R: Copy { a: u32 } fn (p: &mut R) change() { set p.a = 1; } fn run(p: &mut R) { let r = &p.a; p.change(); }",
6332 6330
    ];
6333 6331
    for program in programs {
6383 6381
        }));
6384 6382
    }
6385 6383
}
6386 6384
6387 6385
/// Unsafe calls with excess arguments report the unsafe-call diagnostic.
6388 -
@test unsafe fn testInvalidUnsafeBodyCall() throws (testing::TestError) {
6386 +
unsafe fn testInvalidUnsafeBodyCall() throws (testing::TestError) {
6389 6387
    let mut res = testResolver();
6390 6388
    let result = try resolveProgramStr(&mut res,
6391 6389
        "unsafe fn f(x: u32) {} fn g() { f(1, 2); }");
6392 6390
    try expectErrorKind(&result, super::ErrorKind::UnsafeCall);
6393 6391
}
6394 6392
6395 6393
/// Iteration over raw slices requires permission to read their storage.
6396 -
@test unsafe fn testRawSliceIterationRequiresUnsafe() throws (testing::TestError) {
6394 +
unsafe fn testRawSliceIterationRequiresUnsafe() throws (testing::TestError) {
6397 6395
    for program in [
6398 6396
        "fn f(p: *unsafe [u32]) { for item in p { assert item == 0; } }",
6399 6397
        "fn f(p: *unsafe mut [u32]) { for item, index in p { assert item == index; } }",
6400 6398
        "record R { items: *unsafe [u32] } fn f(r: &R) { for item in r.items { assert item == 0; } }",
6401 6399
    ] {
6419 6417
        try expectNoErrors(&result);
6420 6418
    }
6421 6419
}
6422 6420
6423 6421
/// Short-circuit paths must agree on exact-use ownership.
6424 -
@test unsafe fn testShortCircuitOwnership() throws (testing::TestError) {
6422 +
unsafe fn testShortCircuitOwnership() throws (testing::TestError) {
6425 6423
    for program in [
6426 6424
        "union Ticket: Once { Value(u32) } fn take(t: Ticket) -> bool { match t { case Ticket::Value(n) => return n == 1, } } fn f(t: Ticket) { let result = false and take(t); }",
6427 6425
        "union Ticket: Once { Value(u32) } fn take(t: Ticket) -> bool { match t { case Ticket::Value(n) => return n == 1, } } fn f(t: Ticket) { let result = true or take(t); }",
6428 6426
        "union Ticket: Once { Value(u32) } fn take(t: Ticket) -> bool { match t { case Ticket::Value(n) => return n == 1, } } fn f(t: Ticket, flag: bool) { let result = flag and take(t); }",
6429 6427
        "union Ticket: Once { Value(u32) } fn take(t: Ticket) -> bool { match t { case Ticket::Value(n) => return n == 1, } } unsafe fn f(t: Ticket, flag: bool) { let result = flag or take(t); }",
6447 6445
        try expectNoErrors(&result);
6448 6446
    }
6449 6447
}
6450 6448
6451 6449
/// Earlier reference arguments protect their storage during later arguments.
6452 -
@test unsafe fn testCallArgumentLoans() throws (testing::TestError) {
6450 +
unsafe fn testCallArgumentLoans() throws (testing::TestError) {
6453 6451
    for program in [
6454 6452
        "fn inner(p: &mut u32) -> u32 { set *p = 2; return 0; } fn outer(p: &mut u32, n: u32) {} fn f (p: &mut u32) { outer(&mut *p, inner(p)); }",
6455 6453
        "fn inner(p: &mut u32) -> u32 { set *p = 2; return 0; } fn outer(p: &u32, n: u32) {} fn f (p: &mut u32) { outer(&*p, inner(p)); }",
6456 6454
        "fn inner(p: &mut u32) -> u32 { set *p = 2; return 0; } fn outer(p: &mut u32, n: u32) {} unsafe fn f (p: &mut u32) { outer(&mut *p, inner(p)); }",
6457 6455
        "record R { n: u32 } fn (r: &mut R) call(n: u32) {} fn inner(p: &mut u32) -> u32 { set *p = 2; return 0; } fn f (r: &mut R) { (&mut *r).call(inner(&mut r.n)); }",
6463 6461
            else throw testing::TestError::Failed;
6464 6462
    }
6465 6463
}
6466 6464
6467 6465
/// Conditional explicit arguments protect every possible borrowed place.
6468 -
@test unsafe fn testConditionalCallArgumentLoans() throws (testing::TestError) {
6466 +
unsafe fn testConditionalCallArgumentLoans() throws (testing::TestError) {
6469 6467
    for program in [
6470 6468
        "fn inner(p: &mut u32) -> u32 { set *p = 2; return 0; } fn outer(p: &u32, n: u32) {} fn f (p: &mut u32, q: &mut u32, flag: bool) { outer(&*p if flag else &*q, inner(p)); }",
6471 6469
        "fn inner(p: &mut u32) -> u32 { set *p = 2; return 0; } fn outer(p: &u32, n: u32) {} fn f (p: &mut u32, q: &mut u32, flag: bool) { outer(&*p if flag else &*q, inner(q)); }",
6472 6470
        "fn outer(p: &mut u32, q: &mut u32) {} fn f (p: &mut u32, q: &mut u32, flag: bool) { outer(&mut *p if flag else &mut *q, &mut *p); }",
6473 6471
        "fn inner(p: &mut u32) -> u32 { set *p = 2; return 0; } fn outer(p: &u32, n: u32) {} unsafe fn f (p: &mut u32, q: &mut u32, flag: bool) { outer(&*p if flag else &*q, inner(q)); }",
6482 6480
            else throw testing::TestError::Failed;
6483 6481
    }
6484 6482
}
6485 6483
6486 6484
/// Conditional argument alternatives cannot overlap another exclusive argument.
6487 -
@test unsafe fn testConditionalCallArgumentOverlap() throws (testing::TestError) {
6485 +
unsafe fn testConditionalCallArgumentOverlap() throws (testing::TestError) {
6488 6486
    for program in [
6489 6487
        "fn outer(p: &mut u32, q: &mut u32) {} fn f (p: &mut u32, q: &mut u32, flag: bool) { outer(p if flag else q, p); }",
6490 6488
        "fn outer(p: &mut u32, q: &mut u32) {} fn f (p: &mut u32, q: &mut u32, flag: bool) { outer(p if flag else q, q); }",
6491 6489
        "fn outer(p: &mut u32, q: &mut u32) {} fn f (p: &mut u32, q: &mut u32, flag: bool) { outer(p, p if flag else q); }",
6492 6490
        "fn outer(p: &mut u32, q: &mut u32) {} fn f (p: &mut u32, q: &mut u32, flag: bool) { outer(q, p if flag else q); }",
lib/std/lang/scanner.rad +4 -0
230 230
    strings::intern(pool, "@default");
231 231
    strings::intern(pool, "@intrinsic");
232 232
    strings::intern(pool, "@test");
233 233
    // Intern built-in slice methods.
234 234
    strings::intern(pool, "append");
235 +
    strings::intern(pool, "reserve");
236 +
    strings::intern(pool, "resize");
237 +
    strings::intern(pool, "extend");
235 238
    strings::intern(pool, "delete");
239 +
    strings::intern(pool, "take");
236 240
237 241
    return Scanner { sourceLoc, source, token: 0, cursor: 0, pool };
238 242
}
239 243
240 244
/// Check if we've reached the end of input.
test/tests/const.fn.array.rad +0 -1
1 1
//! Test function pointers stored in constant/static arrays.
2 2
//! Verifies that function references are properly emitted as
3 3
//! data items and can be called through the array.
4 -
//! returns: 0
5 4
6 5
fn add(a: i32, b: i32) -> i32 {
7 6
    return a + b;
8 7
}
9 8
test/tests/const.union.payload.fn.array.rad +0 -1
1 -
//! returns: 0
2 1
//! Constant array of records containing union variants with throwing function payloads.
3 2
4 3
union TestError: Copy {
5 4
    Fail,
6 5
}
test/tests/literal.slice.empty.ril +1 -1
1 1
fn w32 $emptySlice() {
2 2
  @entry0
3 3
    reserve %0 16 8;
4 -
    store w64 0 %0 0;
4 +
    store w64 4 %0 0;
5 5
    store w32 0 %0 8;
6 6
    store w32 0 %0 12;
7 7
    load w32 %1 %0 8;
8 8
    ret %1;
9 9
}
test/tests/slice.append.ril +3 -3
22 22
  @append.grow3
23 23
    br.ult w32 %6 536870912 @guard#pass4 @guard#trap5;
24 24
  @guard#pass4
25 25
    shl w32 %7 %6 1;
26 26
    or w32 %8 %7 1;
27 -
    load w64 %9 %3 0;
27 +
    mul w32 %9 %8 4;
28 +
    load w64 %11 %3 0;
28 29
    load w64 %10 %3 8;
29 -
    mul w32 %11 %8 4;
30 -
    call w64 %9(%4, %10, %11, 4);
30 +
    call w64 %11(%4, %10, %9, 4);
31 31
    load w64 %12 %4 0;
32 32
    br.ne w32 %12 0 @append.done2 @append.copy6;
33 33
  @guard#trap5
34 34
    ebreak;
35 35
    unreachable;