Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.46.0

0.46.0 / src / sema / check / declarations.lucb

#==============================================================================================
#
#   check/declarations - Declarations
#
#   DESCRIPTION:
#       Functions, types, constants, and globals, their signatures and attributes.
#
#==============================================================================================
extend Checker:
    # mark: Declarations =======================================================================

    ## Give every top-level declaration a binding and, for types, a nominal id, so
    ## signatures can refer to each other in any order.
    func collect(tree: ast.Node*) -> !:
        var cursor = tree.body
        while let d = cursor:
            # a top-level declaration remembers its module, for the backend's names
            d.resolved = tree
            match d.kind:
                .struct_, .extern_struct, .extern_type:
                    d.type_id = try self.table.nominal(types.Kind.struct_, d, try self.generic_ids(d))
                    try self.bind(d, d.text, d.type_id, d, false)
                .enum_:
                    d.type_id = try self.table.nominal(types.Kind.enum_, d, try self.generic_ids(d))
                    try self.bind(d, d.text, d.type_id, d, false)
                .union_, .extern_union:
                    d.type_id = try self.table.nominal(types.Kind.union_, d, try types.no_args())
                    try self.bind(d, d.text, d.type_id, d, false)
                .interface_:
                    d.type_id = try self.table.nominal(types.Kind.interface_, d, try self.generic_ids(d))
                    try self.bind(d, d.text, d.type_id, d, false)
                .type_alias, .func_, .extern_func, .constant:
                    try self.bind(d, d.text, types.none_id, d, false)
                .global, .extern_var:
                    try self.bind(d, d.text, types.none_id, d, true)
                _:
                    _ = 0
            cursor = d.next

    ## The generic parameters of a declaration, registered as param types.
    func generic_ids(d: ast.Node*) -> u32[]!:
        let params = generic_params_of(d)
        let n = ast.count(params)
        if n == 0:
            return try types.no_args()
        var ids = try new u32[n] ---
        var i: usize = 0
        var cursor = params
        while let g = cursor:
            g.type_id = try self.table.parameter(d, g.text)
            ids[i] = g.type_id
            i += 1
            cursor = g.next
        return ids

    ## Bind a declaration's generic parameters and resolve their constraints.
    func bind_generics(d: ast.Node*) -> !:
        if ast.count(generic_params_of(d)) > types.max_type_arguments:
            let first = generic_params_of(d) else return
            var text: u8[96]
            return try self.fail(first, try strings.format(text, f"a declaration has at most {types.max_type_arguments} type parameters"))
        var cursor = generic_params_of(d)
        while let g = cursor:
            if let existing = self.lookup(g.text):
                if let ed = existing.decl:
                    if (is_type_decl(ed) or ed.kind == ast.Kind.type_alias) and ed != d:
                        try self.fail(g, "a type parameter may not take the name of a type in scope")
            if g.type_id == types.none_id:
                g.type_id = try self.table.parameter(d, g.text)
            try self.bind(g, g.text, g.type_id, g, false)
            var bound = g.body
            while let constraint = bound:
                let id = try self.resolve_type(constraint)
                if self.table.kind(id) != types.Kind.interface_:
                    try self.fail(constraint, "a constraint must be an interface")
                bound = constraint.next
            cursor = g.next

    func resolve_signatures(tree: ast.Node*) -> !:
        var cursor = tree.body
        while let d = cursor:
            try self.resolve_declaration(d)
            cursor = d.next

    func resolve_declaration(d: ast.Node*) -> !:
        match d.kind:
            .type_alias:
                let t = d.ty else return try self.fail(d, "an alias needs a type")
                if d.type_id == types.none_id:
                    try self.resolving.push((usize)d)
                    d.type_id = try self.resolve_type(t)
                    self.resolving.count -= 1
                try self.rebind(d.text, d.type_id)
            .constant:
                if let t = d.ty:
                    d.type_id = try self.resolve_type(t)
                    try self.rebind(d.text, d.type_id)
            .global, .extern_var:
                let t = d.ty else return try self.fail(d, "a global needs a type")
                d.type_id = try self.resolve_type(t)
                try self.storable(d.type_id, t)
                try self.rebind(d.text, d.type_id)
            .func_, .extern_func:
                try self.resolve_function(d, none)
                try self.rebind(d.text, d.type_id)
            .extern_type:
                if let t = d.ty:
                    _ = try self.resolve_type(t)
            .struct_, .extern_struct, .union_, .extern_union, .enum_, .interface_:
                try self.resolve_members(d)
            _:
                _ = 0

    ## A struct, union or enum cannot contain itself by value, an enum through a case's
    ## payload; a pointer, span, or optional pointer breaks the cycle (§10.1, §10.2). The
    ## offending field or payload loses its type so no layout recurses.
    func check_containment(d: ast.Node*) -> !:
        var cursor = d.body
        while let m = cursor:
            if m.kind == ast.Kind.field and self.contains_by_value(m.type_id, d, 0):
                try self.fail(m, "this struct contains itself; use a pointer (§10.1)")
                m.type_id = types.error_id
            if m.kind == ast.Kind.enum_case:
                var payload = m.body
                while let p = payload:
                    if self.contains_by_value(p.type_id, d, 0):
                        try self.fail(p, "this enum contains itself; use a pointer (§10.2)")
                        p.type_id = types.error_id
                    payload = p.next
            cursor = m.next

    func contains_by_value(id: u32, d: ast.Node*, depth: u32) -> bool:
        if depth > 32:
            return false
        let t = self.table.get(id)
        match t.kind:
            .array, .atomic:
                return self.contains_by_value(t.elem, d, depth + 1)
            .optional:
                let inner = self.table.get(t.elem)
                if inner.kind == types.Kind.pointer or inner.kind == types.Kind.func_:
                    return false
                return self.contains_by_value(t.elem, d, depth + 1)
            .tuple:
                for a in t.args:
                    if self.contains_by_value(a, d, depth + 1):
                        return true
                return false
            .struct_, .union_, .enum_:
                let decl = t.decl else return false
                if decl == d:
                    return true
                var cursor = decl.body
                while let m = cursor:
                    if m.kind == ast.Kind.field and self.contains_by_value(m.type_id, d, depth + 1):
                        return true
                    if m.kind == ast.Kind.enum_case:
                        var payload = m.body
                        while let p = payload:
                            if self.contains_by_value(p.type_id, d, depth + 1):
                                return true
                            payload = p.next
                    cursor = m.next
                return false
            _:
                return false

    ## An `extern` or `export` signature crosses the C boundary: no generic, no `str`, no
    ## `fmt`, no array by value, no span outside a parameter, no tagged optional, no view
    ## (§17.1, §17.6); an export's symbol is unique in the program.
    func check_foreign_signature(f: ast.Node*, owner: ast.Node*?) -> !:
        let exported = f.has(ast.flag_export)
        if exported and f.kind == ast.Kind.extern_func:
            return try self.fail(f, "an `extern` declaration is not exported (§17.6)")
        let which = "an `export`" if exported else "an `extern`"
        if generic_params_of(f) != none:
            var text: u8[128]
            return try self.fail(f, try strings.format(text, f"{which} cannot be generic (§17.6)"))
        var cursor = f.right
        while let p = cursor:
            if not p.has(ast.flag_variadic) and not self.c_representable(p.type_id, true):
                var text: u8[160]
                return try self.fail(p, try strings.format(text, f"this type is not C-representable in {which} signature; C text is `c.str` (§17.6)"))
            if exported and p.has(ast.flag_out):
                return try self.fail(p, "an `export` cannot have `out` parameters")
            cursor = p.next
        let ft = self.table.get(f.type_id)
        var result = ft.elem
        if self.table.kind(result) == types.Kind.fallible:
            if not exported:
                return try self.fail(f, "an `extern` cannot be fallible; C reports failure through its result (§17.1)")
            result = self.table.get(result).elem
        if self.table.kind(result) == types.Kind.tuple:
            for m in self.table.get(result).args:
                if not self.c_representable(m, false):
                    return try self.fail(f, "an `out` result is not C-representable (§17.1)")
        elif result != types.unit_id and not self.c_representable(result, false):
            var text: u8[160]
            return try self.fail(f, try strings.format(text, f"the result is not C-representable in {which} signature (§17.6)"))
        if exported:
            var symbol_bytes = try new u8[f.text.length + 128] ---
            var symbol = f.text
            if let o = owner:
                symbol = try strings.format(symbol_bytes, f"{o.text}_{f.text}")
            for known in self.export_symbols.span():
                if known == symbol:
                    return try self.fail(f, "two exports share this symbol (§17.6)")
            try self.export_symbols.push(symbol)

    ## C-representable (§17.6): scalars, the `c` types, pointers, `c.str`, spans in
    ## parameter position, records of representable fields, integer-backed enums, and
    ## function pointers with representable signatures.
    func c_representable(id: u32, parameter: bool) -> bool:
        var seen: u32[64] = ---
        return self.c_representable_in(id, parameter, seen, 0)

    ## The check with the records on the way down: a record reached again through a
    ## pointer is being decided already, and is representable if its other members are.
    func c_representable_in(id: u32, parameter: bool, seen: u32[], depth: usize) -> bool:
        let t = self.table.get(id)
        if self.table.is_numeric(id) or id == types.bool_id or id == types.char_id or id == types.cstr_id or id == types.void_id or id == types.unit_id or id == types.never_id:
            return true
        match t.kind:
            .pointer:
                return t.elem == types.void_id or self.c_representable_in(t.elem, false, seen, depth) or self.table.kind(t.elem) == types.Kind.struct_ or self.table.kind(t.elem) == types.Kind.union_
            .span:
                return parameter and self.c_representable_in(t.elem, false, seen, depth)
            .optional:
                return self.table.has_null_niche(t.elem) and self.c_representable_in(t.elem, false, seen, depth)
            .array:
                # a C array in a record; never a parameter, which C passes as a pointer
                return not parameter and self.c_representable_in(t.elem, false, seen, depth)
            .struct_, .union_:
                if self.table.is_opaque_handle(id):
                    return true
                var k: usize = 0
                while k < depth:
                    if seen[k] == id:
                        return true
                    k += 1
                if depth >= seen.length:
                    return false
                seen[depth] = id
                let d = t.decl else return false
                var member = d.body
                while let m = member:
                    if m.kind == ast.Kind.field and not self.c_representable_in(m.type_id, false, seen, depth + 1):
                        return false
                    member = m.next
                return true
            .enum_:
                return self.is_backed_enum(id)
            .func_:
                # spans are representable as a function's own parameters, through the
                # wrapper, never inside a function pointer's signature (§17.6)
                for a in t.args:
                    if not self.c_representable_in(a, false, seen, depth):
                        return false
                return t.elem == types.unit_id or self.c_representable_in(t.elem, false, seen, depth)
            _:
                return false

    ## `T!` is a result effect, not a storable type: no parameter, field, element, or local
    ## holds one (§11.2).
    func storable(id: u32, at: ast.Node*) -> !:
        if self.table.kind(id) == types.Kind.fallible:
            return try self.fail(at, "`T!` is a result, not a storable type; declare an enum to hold one (§11.2)")

    ## The fields, cases, and method signatures of a type declaration.
    func resolve_members(d: ast.Node*) -> !:
        self.push_scope()
        try self.bind_generics(d)
        if let twice = duplicate_member(d):
            var text: u8[160]
            return try self.fail(twice, try strings.format(text, f"`{twice.text}` is already a member of this type"))
        if d.has(ast.flag_packed) and d.kind != ast.Kind.struct_ and d.kind != ast.Kind.extern_struct:
            return try self.fail(d, "`packed` lays out a struct (§5.11)")
        if (d.kind == ast.Kind.extern_struct or d.kind == ast.Kind.extern_union) and generic_params_of(d) != none:
            return try self.fail(d, "an `extern` record is not generic (§17.6)")
        if d.kind == ast.Kind.struct_:
            try self.check_align(d.right, d)
        if d.kind == ast.Kind.enum_:
            if let backing = d.ty:
                let bt = try self.resolve_type(backing)
                if not self.table.is_integer(bt):
                    try self.fail(backing, "an enum is backed by an integer type")
        var implemented = d.ty if d.kind != ast.Kind.enum_ else d.right
        while let i = implemented:
            let id = try self.resolve_type(i)
            if self.table.kind(id) != types.Kind.interface_:
                try self.fail(i, "a conformance names an interface")
            implemented = i.next
        var cursor = d.body
        while let m = cursor:
            match m.kind:
                .field:
                    let t = m.ty else return try self.fail(m, "a field needs a type")
                    m.type_id = try self.resolve_type(t)
                    try self.storable(m.type_id, t)
                    try self.check_align(m.right, m)
                    if m.type_id == types.fmt_id:
                        return try self.fail(t, "`fmt` is a parameter type only (§9.1)")
                .enum_case:
                    var pcursor = m.body
                    while let p = pcursor:
                        let t = p.ty else return try self.fail(p, "a payload needs a type")
                        p.type_id = try self.resolve_type(t)
                        pcursor = p.next
                    m.type_id = d.type_id
                .func_:
                    if d.kind == ast.Kind.interface_ and generic_params_of(m) != none:
                        try self.fail(m, "an interface has no generic methods (§14.1)")
                    try self.resolve_function(m, d)
                _:
                    _ = 0
            cursor = m.next
        self.pop_scope()

    ## An `extern` variable, handle, or record names only C-representable types (§17.1,
    ## §17.6); checked once every type is resolved, since a field may name a later record.
    func check_foreign_declaration(d: ast.Node*) -> !:
        if d.kind == ast.Kind.extern_var and not self.c_representable(d.type_id, false):
            return try self.fail(d, "an `extern` variable has a C-representable type (§17.6)")
        if d.kind == ast.Kind.extern_type:
            let shape = d.ty else return
            if not self.c_representable(shape.type_id, false):
                return try self.fail(shape, "an `extern` handle is shaped like a C integer or pointer (§17.1)")
        var cursor = d.body
        while let m = cursor:
            if m.kind == ast.Kind.field and not self.c_representable(m.type_id, false):
                return try self.fail(m, "an `extern` record's field has a C-representable type (§17.6)")
            cursor = m.next

    ## `align(N)` (§5.11) names a power of two.
    func check_align(attribute: ast.Node*?, at: ast.Node*) -> !:
        let n = types.explicit_align(attribute)
        if n != 0 and (n & (n - 1)) != 0:
            return try self.fail(at, "`align(N)` takes a power of two (§5.11)")

    ## A handle's `destroy` is a `pub` function of the module taking the handle and
    ## returning nothing, never failing (§17.7): full Luce calls it at the last reference.
    func check_handle(d: ast.Node*) -> !:
        let name = d.right else return
        let b = self.lookup(name.text) else return try self.fail(name, "a handle's `destroy` names a function of this module (§17.7)")
        let f = b.decl else return try self.fail(name, "a handle's `destroy` names a function of this module (§17.7)")
        if f.kind != ast.Kind.func_:
            return try self.fail(name, "a handle's `destroy` names a function of this module (§17.7)")
        if not f.has(ast.flag_pub):
            return try self.fail(name, "a handle's `destroy` function is `pub` (§17.7)")
        let t = self.table.get(f.type_id)
        if t.kind != types.Kind.func_ or t.args.length != 1 or t.args[0] != d.type_id or t.elem != types.unit_id:
            return try self.fail(name, "a handle's `destroy` takes the handle and returns nothing, without failing (§17.7)")
        name.resolved = f

    ## The function type of `f`. A method's receiver is implicit and not part of it, and so
    ## is an extern's `out` parameter, which the call answers instead (§17.1).
    func resolve_function(f: ast.Node*, owner: ast.Node*?) -> !:
        self.push_scope()
        try self.bind_generics(f)
        let n = ast.count(f.right)
        var params = try types.no_args()
        if n > 0:
            params = try new u32[n] ---
        var i: usize = 0
        var outs: usize = 0
        var cursor = f.right
        while let p = cursor:
            let t = p.ty else return try self.fail(p, "a parameter needs a type")
            p.type_id = try self.resolve_type(t)
            try self.storable(p.type_id, t)
            if p.has(ast.flag_out):
                if f.kind != ast.Kind.extern_func:
                    return try self.fail(p, "only an extern function has `out` parameters")
                outs += 1
            else:
                params[i] = p.type_id
                i += 1
            cursor = p.next
        var result = types.unit_id
        if let r = f.ty:
            result = try self.resolve_type(r)
            r.type_id = result  # the declared result, which the backends need beside `out` values
            # `-> T!` spells the failure on the type; `-> !` on the flag. One flag serves both.
            if self.table.kind(result) == types.Kind.fallible:
                f.flags |= ast.flag_fallible
        elif f.has(ast.flag_fallible):
            result = try self.table.fallible(result)
        if outs > 0:
            result = try self.extern_result(f, result)
        f.type_id = try self.table.function(params[..<i], result, f.has(ast.flag_variadic))
        if f.kind == ast.Kind.extern_func or f.has(ast.flag_export):
            try self.check_foreign_signature(f, owner)
        self.pop_scope()

    ## What a call of extern `f` answers: `declared`, then every `out` parameter, as a tuple
    ## when there is more than one value (§17.1).
    func extern_result(f: ast.Node*, declared: u32) -> u32!:
        var parts = try new u32[ast.count(f.right) + 1] ---
        var n: usize = 0
        if declared != types.unit_id:
            parts[n] = declared
            n += 1
        var cursor = f.right
        while let p = cursor:
            if p.has(ast.flag_out):
                parts[n] = p.type_id
                n += 1
            cursor = p.next
        if n == 1:
            return parts[0]
        return try self.table.tuple(parts[..<n])