lang: Scope unsafe operations to functions

e233053f50d35d77a51801c1d9a6cb2394ad3b9b1a3fddf873dc01f1af3291ce
An `unsafe mod` made every function in the module unsafe, which hid
which functions actually perform unsafe operations.

Track whether the current function is unsafe instead of the nesting
depth of unsafe modules and functions, and reject `unsafe` on modules.
Unsafe operations and calls to unsafe functions are permitted only in
the body of an `unsafe fn`.

Assisted-by: Claude:opus-5.5
Alexis Sellier committed ago 1 parent 2ead9b54
lib/std/lang/parser.rad +1 -2
837 837
    // is inside functions.
838 838
    let attrs = parseAttributes(p);
839 839
    if let list = attrs {
840 840
        if ast::attributesContains(&list, ast::Attribute::Unsafe)
841 841
            and p.current.kind <> scanner::TokenKind::Fn
842 -
            and p.current.kind <> scanner::TokenKind::Mod
843 842
        {
844 -
            throw failParsing(p, "`unsafe` is only allowed on functions and modules");
843 +
            throw failParsing(p, "`unsafe` is only allowed on functions");
845 844
        }
846 845
        let allowed: bool =
847 846
            p.current.kind == scanner::TokenKind::Fn or
848 847
            p.current.kind == scanner::TokenKind::Union or
849 848
            p.current.kind == scanner::TokenKind::Record or
lib/std/lang/parser/tests.rad +4 -8
1147 1147
@test fn testParseUnsafeUnsupportedDecl() throws (testing::TestError) {
1148 1148
    let recordDecl: ?*ast::Node = try? parseStmtStr("unsafe record R {}");
1149 1149
    try testing::expect(recordDecl == nil);
1150 1150
    let constDecl: ?*ast::Node = try? parseStmtStr("unsafe constant X = 1;");
1151 1151
    try testing::expect(constDecl == nil);
1152 +
    let moduleDecl: ?*ast::Node = try? parseStmtStr("unsafe mod io;");
1153 +
    try testing::expect(moduleDecl == nil);
1152 1154
}
1153 1155
1154 -
/// Test `unsafe` on the other declaration forms that support it.
1155 -
@test fn testParseUnsafeMethodAndModule() throws (testing::TestError) {
1156 -
    let moduleNode = try! parseStmtStr("unsafe mod io;");
1157 -
    let case ast::NodeValue::Mod(moduleDecl) = moduleNode.value
1158 -
        else throw testing::TestError::Failed;
1159 -
    let moduleAttrs = moduleDecl.attrs else throw testing::TestError::Failed;
1160 -
    assert ast::attributesContains(&moduleAttrs, ast::Attribute::Unsafe);
1161 -
1156 +
/// Test unsafe method declarations.
1157 +
@test fn testParseUnsafeMethods() throws (testing::TestError) {
1162 1158
    let instanceNode = try! parseStmtStr(
1163 1159
        "instance Read for Value { unsafe fn (value: &Value) get() {} }"
1164 1160
    );
1165 1161
    let case ast::NodeValue::InstanceDecl { methods, .. } = instanceNode.value
1166 1162
        else throw testing::TestError::Failed;
lib/std/lang/resolver.rad +11 -26
625 625
    InvalidRefPosition,
626 626
    /// A reference cannot be bound to a local.
627 627
    RefBinding,
628 628
    /// Call arguments contain overlapping incompatible loans.
629 629
    BorrowConflict(*[u8]),
630 -
    /// Unsafe pointer operation outside an `unsafe` declaration.
630 +
    /// Unsafe pointer operation outside an `unsafe` function.
631 631
    UnsafeOperation,
632 632
    /// Safe code cannot call an `unsafe` function.
633 633
    UnsafeCall,
634 634
    /// Internal error.
635 635
    Internal,
850 850
    loopDepth: u32,
851 851
    /// Signature of the function currently being analyzed.
852 852
    currentFn: ?*FnType,
853 853
    /// Current module being analyzed.
854 854
    currentMod: u16,
855 -
    /// Nesting depth of unsafe modules and function bodies.
856 -
    unsafeDepth: u32,
855 +
    /// Whether the current function permits unsafe operations.
856 +
    inUnsafeFn: bool,
857 857
    /// Configuration for semantic analysis.
858 858
    config: Config,
859 859
    /// Unified arena for symbols, scopes, and nominal type.
860 860
    arena: alloc::Arena,
861 861
    /// Combined semantic metadata table indexed by node ID.
1009 1009
        pkgScope: storage.pkgScope,
1010 1010
        loopStack: undefined,
1011 1011
        loopDepth: 0,
1012 1012
        currentFn: nil,
1013 1013
        currentMod: 0,
1014 -
        unsafeDepth: 0,
1014 +
        inUnsafeFn: false,
1015 1015
        config,
1016 1016
        arena,
1017 1017
        nodeData: NodeDataTable { entries: storage.nodeData },
1018 1018
        types: nil,
1019 1019
        errors: @sliceOf(storage.errors.ptr, 0, storage.errors.len),
2711 2711
            // Ignore non-declaration nodes.
2712 2712
        }
2713 2713
    }
2714 2714
}
2715 2715
2716 -
/// Require the current declaration to be unsafe.
2716 +
/// Require the current function to be unsafe.
2717 2717
fn requireUnsafe(self: *mut Resolver, node: *ast::Node) throws (ResolveError) {
2718 -
    if self.unsafeDepth == 0 {
2718 +
    if not self.inUnsafeFn {
2719 2719
        throw emitError(self, node, ErrorKind::UnsafeOperation);
2720 2720
    }
2721 2721
}
2722 2722
2723 2723
/// Reject calls from safe code through unsafe function types.
2724 2724
fn checkUnsafeCall(self: *mut Resolver, node: *ast::Node, info: *FnType)
2725 2725
    throws (ResolveError)
2726 2726
{
2727 -
    if info.isUnsafe and self.unsafeDepth == 0 {
2727 +
    if info.isUnsafe and not self.inUnsafeFn {
2728 2728
        throw emitError(self, node, ErrorKind::UnsafeCall);
2729 2729
    }
2730 2730
}
2731 2731
2732 2732
/// Visit a top-level definition, recursing into sub-modules.
2743 2743
            }
2744 2744
            let modName = try nodeName(self, decl.name);
2745 2745
            let submod = try enterSubModule(self, modName, node);
2746 2746
            let case ast::NodeValue::Block(block) = submod.root.value
2747 2747
                else panic "visitDef: expected block for module root";
2748 -
            let mut isUnsafe = false;
2749 -
            if let attrs = decl.attrs {
2750 -
                set isUnsafe = ast::attributesContains(&attrs, ast::Attribute::Unsafe);
2751 -
            }
2752 -
            if isUnsafe {
2753 -
                set self.unsafeDepth += 1;
2754 -
            }
2755 2748
            try resolveModuleDefs(self, &block) catch e {
2756 -
                if isUnsafe { set self.unsafeDepth -= 1; }
2757 2749
                exitModuleScope(self, submod);
2758 2750
                throw e;
2759 2751
            };
2760 -
            if isUnsafe {
2761 -
                set self.unsafeDepth -= 1;
2762 -
            }
2763 2752
            exitModuleScope(self, submod);
2764 2753
        }
2765 2754
        case ast::NodeValue::RecordDecl(_),
2766 2755
             ast::NodeValue::UnionDecl(_),
2767 2756
             ast::NodeValue::Use(_),
3443 3432
    fnType: *FnType,
3444 3433
    receiverName: ?*ast::Node,
3445 3434
    params: *mut [*ast::Node],
3446 3435
    body: *ast::Node,
3447 3436
) throws (ResolveError) {
3448 -
    let isUnsafe = fnType.isUnsafe;
3449 -
    if isUnsafe {
3450 -
        set self.unsafeDepth += 1;
3451 -
    }
3437 +
    let wasUnsafe = self.inUnsafeFn;
3438 +
    set self.inUnsafeFn = fnType.isUnsafe;
3452 3439
    // Enter function scope.
3453 3440
    enterFn(self, node, fnType); // Enter function scope for body analysis.
3454 3441
3455 3442
    let missingReturn = try checkExecutableBody(self, fnType, receiverName, params, body) catch e {
3456 3443
        exitFn(self);
3457 -
        if isUnsafe { set self.unsafeDepth -= 1; }
3444 +
        set self.inUnsafeFn = wasUnsafe;
3458 3445
        throw e;
3459 3446
    };
3460 3447
    exitFn(self);
3461 -
    if isUnsafe {
3462 -
        set self.unsafeDepth -= 1;
3463 -
    }
3448 +
    set self.inUnsafeFn = wasUnsafe;
3464 3449
    if missingReturn {
3465 3450
        throw emitError(self, body, ErrorKind::FnMissingReturn);
3466 3451
    }
3467 3452
}
3468 3453
lib/std/lang/resolver/printer.rad +2 -2
537 537
        }
538 538
        case super::ErrorKind::BorrowConflict(name) => {
539 539
            printQuoted("conflicting call-scoped loans of '", name);
540 540
        }
541 541
        case super::ErrorKind::UnsafeOperation => {
542 -
            io::print("unsafe pointer operation requires an unsafe declaration");
542 +
            io::print("unsafe pointer operation requires an unsafe function");
543 543
        }
544 544
        case super::ErrorKind::UnsafeCall => {
545 -
            io::print("calling an unsafe function requires an unsafe declaration");
545 +
            io::print("calling an unsafe function requires an unsafe function");
546 546
        }
547 547
        case super::ErrorKind::Internal => {
548 548
            io::print("internal compiler error");
549 549
        }
550 550
        case super::ErrorKind::RecordFieldOutOfOrder { .. } => {