Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.43.0

0.43.0 / src / back / declarations.lucb

#==============================================================================================
#
#   declarations - The interface of a module, as Base declarations
#
#   DESCRIPTION:
#       What a program that links a library built from a module needs to know about it,
#       written as Base source the checker reads like any other: every declaration, in
#       the module's own words and with its doc comments, where a function or global the
#       library defines is `linked` and carries no body or initialiser (§9.8). Generic
#       and `inline` functions keep their bodies, since they are compiled where they are
#       used; tests and module-level `asm` belong to the library alone. The text is cut
#       from the module's source rather than respelled, so nothing is lost in translation.
#
#==============================================================================================

import front.ast
import front.source
import sema.check
import sema.types
import support.buffer
import support.list

# mark: Writing declarations ==================================================================

## Write the interface of `module` to `out`; `table` tells which constants fold.
pub func write(out: buffer.Buffer*, module: check.Module, table: types.Table*) -> !:
    let text = module.src.bytes
    var w = Cutter(out = out, text = text, table = table)
    var first: usize = text.length
    if let d = module.tree.body:
        first = block_start(text, d)
    # the preamble: the module's comments before its first declaration
    try out.put((str)text[..<first])
    var cursor = module.tree.body
    while let d = cursor:
        let start = block_start(text, d)
        var end = text.length
        if let following = d.next:
            end = block_start(text, following)
        try w.declaration(d, start, end)
        cursor = d.next

struct Cutter:
    var out: buffer.Buffer*
    var text: const u8[]
    var table: types.Table*

    ## One top-level declaration, from its doc comment to the next declaration's.
    func declaration(d: ast.Node*, start: usize, end: usize) -> !:
        match d.kind:
            .test_, .asm_:
                return
            .global:
                if ast.is_linked(d):
                    try self.verbatim(start, end)
                else:
                    try self.linked_global(d, start, end)
            .constant:
                # a scalar constant folds wherever it is named; any other has storage,
                # which the library owns, and its value stays for what reads it
                if ast.is_linked(d) or self.folds(d.type_id):
                    try self.verbatim(start, end)
                else:
                    try self.linked_constant(d, start, end)
            .func_:
                if compiled_where_used(d, none) or ast.is_linked(d):
                    try self.verbatim(start, end)
                else:
                    try self.linked_function(d, start, end, "")
            .struct_, .union_, .enum_:
                if check.generic_params_of(d) != none:
                    try self.verbatim(start, end)
                else:
                    try self.record(d, start, end)
            _:
                try self.verbatim(start, end)

    ## Whether a constant of this type is a value the checker and the backends fold.
    func folds(id: u32) -> bool:
        if id == types.bool_id or id == types.char_id or id == types.str_id or id == types.cstr_id or id == types.error_code_id:
            return true
        return self.table.is_integer(id) or self.table.is_float(id)

    func verbatim(start: usize, end: usize) -> !:
        try self.out.put((str)self.text[start..<end])

    ## A record: its header and fields as written, its methods as `linked` signatures.
    func record(d: ast.Node*, start: usize, end: usize) -> !:
        var member = d.body
        let first = member else return try self.verbatim(start, end)
        try self.verbatim(start, block_start(self.text, first))
        while let m = member:
            let mstart = block_start(self.text, m)
            var mend = end
            if let following = m.next:
                mend = block_start(self.text, following)
            if m.kind == ast.Kind.func_ and not compiled_where_used(m, d) and not ast.is_linked(m):
                try self.linked_function(m, mstart, mend, d.text)
            else:
                try self.verbatim(mstart, mend)
            member = m.next

    ## A function's doc comment and its signature line, `linked`, without the `:` and body.
    ## A method of `owner` names its receiver, which its body showed (§9.8): `self: T*`
    ## when it changes it, `self: const T*` when it reads it; a `static` function names none.
    func linked_function(d: ast.Node*, start: usize, end: usize, owner: str) -> !:
        let line = line_start(self.text, d.start)
        try self.verbatim(start, line)
        let stop = header_end(self.text, line)
        var last = stop
        while last > line and (self.text[last - 1] == ' ' or self.text[last - 1] == ':'):
            last -= 1
        let at = word_start(self.text, line, last)
        try self.verbatim(line, at)
        try self.out.put("linked ")
        var open = at
        while open < last and self.text[open] != '(':
            open += 1
        if owner.length == 0 or d.has(ast.flag_static) or open == last:
            try self.verbatim(at, last)
        else:
            try self.verbatim(at, open + 1)
            try self.out.put("self: " if d.has(ast.flag_mutating) or d.text == "init" else "self: const ")
            try self.out.put(owner)
            try self.out.put("*" if self.text[open + 1] == ')' else "*, ")
            try self.verbatim(open + 1, last)
        try self.out.put("\n")
        try self.blank_after(end)

    ## The blank line a block ended with, kept so the spacing stays the module's.
    func blank_after(end: usize) -> !:
        if end >= 2 and self.text[end - 1] == '\n' and self.text[end - 2] == '\n':
            try self.out.put("\n")

    ## A constant's declaration as written, `linked`: the value stays, the storage is the
    ## library's.
    func linked_constant(d: ast.Node*, start: usize, end: usize) -> !:
        let line = line_start(self.text, d.start)
        try self.verbatim(start, line)
        let at = word_start(self.text, line, header_end(self.text, line))
        try self.verbatim(line, at)
        try self.out.put("linked ")
        try self.verbatim(at, end)

    ## A global's doc comment and its declaration, `linked`, without the initialiser.
    func linked_global(d: ast.Node*, start: usize, end: usize) -> !:
        let line = line_start(self.text, d.start)
        try self.verbatim(start, line)
        let stop = header_end(self.text, line)
        var last = initialiser_start(self.text, line, stop)
        while last > line and self.text[last - 1] == ' ':
            last -= 1
        let at = word_start(self.text, line, last)
        try self.verbatim(line, at)
        try self.out.put("linked ")
        try self.verbatim(at, last)
        try self.out.put("\n")
        try self.blank_after(end)

# mark: Reachable roots =======================================================================

## A function or method with the record it belongs to, for `compiled_where_used`.
struct Owned:
    var node: ast.Node*
    var owner: ast.Node*?

func owner_of(owners: Owned[], f: ast.Node*) -> ast.Node*?:
    for o in owners:
        if o.node == f:
            return o.owner
    return none

## A declaration as the closure starts: public ones are roots, and every function is
## reached whose body is compiled elsewhere.
func seed(roots: list.List[ast.Node*]*, work: list.List[ast.Node*]*, seen: list.List[ast.Node*]*, owners: list.List[Owned]*, d: ast.Node*, owner: ast.Node*?) -> !:
    let named = d.kind == ast.Kind.func_ or d.kind == ast.Kind.global or d.kind == ast.Kind.constant
    if not named:
        return
    if d.kind == ast.Kind.func_:
        try owners.push(Owned(node = d, owner = owner))
    let public = d.has(ast.flag_pub) or (d.kind == ast.Kind.func_ and compiled_where_used(d, owner))
    if public and not is_root(seen.span(), d):
        try seen.push(d)
        try work.push(d)
    if d.has(ast.flag_pub) and not is_root(roots.span(), d):
        try roots.push(d)

## Every declaration the expressions under `n` resolve to, siblings included, joins the
## closure; one outside `home`, or reached from a body compiled elsewhere, is a root.
func reached(roots: list.List[ast.Node*]*, work: list.List[ast.Node*]*, seen: list.List[ast.Node*]*, n: ast.Node*?, home: str, everywhere: bool, src: source.Source*) -> !:
    var cursor = n
    while let e = cursor:
        if let r = e.resolved:
            if r.kind == ast.Kind.func_ or r.kind == ast.Kind.global or r.kind == ast.Kind.constant:
                if not is_root(seen.span(), r):
                    try seen.push(r)
                    try work.push(r)
                if (everywhere or (home.length > 0 and fragment_at(src, r.start) != home)) and not is_root(roots.span(), r):
                    try roots.push(r)
        try reached(roots, work, seen, e.left, home, everywhere, src)
        try reached(roots, work, seen, e.right, home, everywhere, src)
        try reached(roots, work, seen, e.body, home, everywhere, src)
        cursor = e.next

# mark: Source fragments ======================================================================

## The fragment file the byte at `offset` came from.
pub func fragment_at(src: source.Source*, offset: usize) -> str:
    let (path, line, column) = src.located(offset)
    _ = line + column
    return path

## Whether declaration `d` is one of the program's roots.
pub func is_root(roots: ast.Node*[], d: ast.Node*) -> bool:
    for r in roots:
        if r == d:
            return true
    return false

## Whether a function is compiled in every program that uses it: generic, a generic
## record's method, or `inline`; such a body stays in the interface.
func compiled_where_used(f: ast.Node*, owner: ast.Node*?) -> bool:
    if check.generic_params_of(f) != none or ast.has_attribute(f, "inline"):
        return true
    let o = owner else return false
    return check.generic_params_of(o) != none

## Where the block of `d` begins: the start of its line, moved back over the `##` lines
## directly above it.
func block_start(text: const u8[], d: ast.Node*) -> usize:
    var at = line_start(text, d.start)
    while at > 0:
        let previous = line_start(text, at - 1)
        var i = previous
        while i < at and text[i] == ' ':
            i += 1
        if i + 1 < at and text[i] == '#' and text[i + 1] == '#':
            at = previous
        else:
            break
    return at

## The offset of the first byte of the line holding `offset`.
func line_start(text: const u8[], offset: usize) -> usize:
    var at = offset
    while at > 0 and text[at - 1] != '\n':
        at -= 1
    return at

## The offset of the newline ending the header that begins at `line`: the first one at
## bracket depth zero, so a parameter list may span lines.
func header_end(text: const u8[], line: usize) -> usize:
    var depth: i64 = 0
    var i = line
    while i < text.length:
        let b = text[i]
        if b == '(' or b == '[' or b == '{':
            depth += 1
        elif b == ')' or b == ']' or b == '}':
            depth -= 1
        elif b == '\n' and depth <= 0:
            return i
        i += 1
    return text.length

## Where the declaration's own words begin on its line: after the indentation and the
## visibility words `pub`, `export`, and `local`, which precede an attribute (§9.8).
func word_start(text: const u8[], line: usize, stop: usize) -> usize:
    var at = line
    while at < stop and text[at] == ' ':
        at += 1
    while true:
        let rest = (str)text[at..<stop]
        if starts_with(rest, "pub "):
            at += 4
        elif starts_with(rest, "export "):
            at += 7
        elif starts_with(rest, "local "):
            at += 6
        else:
            return at
        while at < stop and text[at] == ' ':
            at += 1

## Where a global's ` = initialiser` begins on its line, or the line's end without one.
func initialiser_start(text: const u8[], line: usize, stop: usize) -> usize:
    var depth: i64 = 0
    var i = line
    while i < stop:
        let b = text[i]
        if b == '(' or b == '[':
            depth += 1
        elif b == ')' or b == ']':
            depth -= 1
        elif b == '=' and depth == 0 and i > line and text[i - 1] == ' ':
            return i
        i += 1
    return stop

func starts_with(text: str, prefix: str) -> bool:
    if text.length < prefix.length:
        return false
    return (str)text.bytes[..<prefix.length] == prefix