Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.44.0

0.44.0 / src / back / target.lucb

#==============================================================================================
#
#   target - The target a build is for
#
#   DESCRIPTION:
#       base.md §19.5 names the targets: an operating system and a processor. Everything
#       the compiler and the standard library decide by target is decided here, once: the
#       assembler's symbol prefix, the C library's names for the standard streams, the
#       linker and its arguments, and the constants the `platform` standard module hands the
#       library and `os` hands a program, so that `if os.linux and os.x86_64:` prunes
#       (§19.6). The host is the target this compiler was itself built for, read from its
#       own `platform` module; the native backend emits that target only, and the C
#       backend emits C for any of them with `--emit=c`.
#
#==============================================================================================

import memory
import platform
import strings

# mark: Platform description ==================================================================

## The operating system a target runs on.
pub enum Os as u8:
    macos = 1
    linux = 2
    windows = 3

## The processor architecture a target runs on.
pub enum Arch as u8:
    arm64 = 1
    x86_64 = 2

## How a target's executable is linked from the assembled object: Apple's `ld` against the
## SDK `xcrun` finds; the C driver, which knows the start files, the C library and the
## dynamic loader of its system; or the compiler itself, which assembles COFF objects
## (`back.assemble`) and links them into a PE image (`back.link`) with no tool beside it.
pub enum Linker as u8:
    macho = 1
    c_driver = 2
    pe = 3

## The architecture's name, as `asm ARCH` blocks (§8.9) and `--target` (§19.5) spell it.
pub func arch_name(arch: Arch) -> str:
    if arch == Arch.arm64:
        return "arm64"
    return "x86_64"

let macos_libraries: str[1] = ["-lSystem"]
let linux_libraries: str[2] = ["-lm", "-lpthread"]
let windows_libraries: str[2] = ["-lsynchronization", "-lbcrypt"]

# mark: Targets ===============================================================================

## A compilation target: its name, system, architecture, level, and how it links (§19.5).
pub struct Target:
    ## The target's name, as `--target` spells it.
    pub var name: str
    ## The target's operating system.
    pub var os: Os
    ## The target's architecture.
    pub var arch: Arch
    ## The instruction-set level (§19.5): what the processor is promised to have beyond the
    ## family's baseline, chosen with `--cpu`. x86-64: 1 is x86-64-v1 (SSE2), 2 is v2
    ## (SSE4.2, POPCNT), 3 is v3 (AVX2, FMA, BMI2), 4 is v4 (AVX-512). arm64: 1 is NEON, 2
    ## is SVE, which implies ARMv8.2-A and its half-precision arithmetic; Apple's arm64 has
    ## that arithmetic at level 1 as well. A generator emits the forms of its level and the
    ## levels below.
    pub var level: u32
    ## The width of a pointer in bits.
    pub var pointer_bits: u32
    ## What the assembler and the linker put before a C symbol: `_` on macOS, nothing on
    ## Linux and 64-bit Windows.
    pub var symbol_prefix: str
    ## The C library's variables holding the standard streams (§5.2).
    pub var stdin_symbol: str
    ## The C library variable holding standard output.
    pub var stdout_symbol: str
    ## The C library variable holding standard error.
    pub var stderr_symbol: str
    ## The linker of the target, and the libraries every program links, as linker arguments.
    pub var linker: Linker
    ## The libraries every program on this target links, as linker arguments.
    pub var system_libraries: const str[]

    ## The target this compiler runs on and emits natively: the one it was built for, which
    ## its own `platform` module names (§19.5).
    pub static func host() -> Target:
        let host = Target.named(platform.name) else trap("the compiler's own target is not one of §19.5")
        return host

    ## The target `name` of §19.5 spells, or none.
    pub static func named(name: str) -> Target?:
        if name == "arm64-macos":
            return Target(name = name, os = Os.macos, arch = Arch.arm64, level = 1, pointer_bits = 64, symbol_prefix = "_",
                          stdin_symbol = "__stdinp", stdout_symbol = "__stdoutp", stderr_symbol = "__stderrp", linker = Linker.macho, system_libraries = macos_libraries)
        if name == "x86_64-linux":
            return Target(name = name, os = Os.linux, arch = Arch.x86_64, level = 1, pointer_bits = 64, symbol_prefix = "",
                          stdin_symbol = "stdin", stdout_symbol = "stdout", stderr_symbol = "stderr", linker = Linker.c_driver, system_libraries = linux_libraries)
        if name == "x86_64-windows":
            return Target(name = name, os = Os.windows, arch = Arch.x86_64, level = 1, pointer_bits = 64, symbol_prefix = "",
                          stdin_symbol = "__acrt_iob_func", stdout_symbol = "__acrt_iob_func", stderr_symbol = "__acrt_iob_func", linker = Linker.pe, system_libraries = windows_libraries)
        return none

    ## Whether this target is the one the compiler is running on.
    pub func is_host() -> bool:
        return self.name == platform.name

    ## The level `--cpu NAME` spells for this architecture, or none: `v1` to `v4` on
    ## x86-64, `neon` or `sve` on arm64.
    pub func level_named(name: str) -> u32?:
        if self.arch == Arch.x86_64:
            if name == "v1":
                return 1
            if name == "v2":
                return 2
            if name == "v3":
                return 3
            if name == "v4":
                return 4
            return none
        if name == "neon":
            return 1
        if name == "sve":
            return 2
        return none

    ## The architecture's name (§8.9).
    pub func arch_name() -> str:
        return arch_name(self.arch)

    ## The `platform` standard module for this target: constants the standard library and,
    ## through `os`, a program branch on. A top-level `let` is a constant (§6.4), so the
    ## branches prune (§19.6). `program` and `version` name the package the program is
    ## built from, as its manifest spells them.
    pub func module_text(buffer: u8[], program: str = "app", version: str = "") -> str!:
        let socket_type = "isize" if self.os == Os.windows else "i32"
        var program_room: u8[96]
        var version_room: u8[96]
        let named = literal_safe(program, program_room)
        let versioned = literal_safe(version, version_room)
        return try strings.format(buffer, f"## The target this program is compiled for (§19.5), decided by `--target`.\npub let name: str = \"{self.name}\"\npub let macos: bool = {self.os == Os.macos}\npub let linux: bool = {self.os == Os.linux}\npub let windows: bool = {self.os == Os.windows}\npub let posix: bool = {self.os != Os.windows}\npub let arm64: bool = {self.arch == Arch.arm64}\npub let x86_64: bool = {self.arch == Arch.x86_64}\npub let pointer_bits: u32 = {self.pointer_bits}\npub let cpu_level: u32 = {self.level}\npub type SocketDescriptor = {socket_type}\n## The package this program is built from, as its manifest names it; `app` outside any package.\npub let program: str = \"{named}\"\n## That package's version, empty when its manifest gives none.\npub let program_version: str = \"{versioned}\"\n")

## `text` as it may stand inside a string literal: printable ASCII but quotes and
## backslashes, cut to fit `buffer`.
func literal_safe(text: str, buffer: u8[]) -> str:
    var used: usize = 0
    for byte in text.bytes:
        if used == buffer.length:
            break
        if byte >= 32 and byte < 127 and byte != '"' and byte != '\\':
            buffer[used] = byte
            used += 1
    return (str)buffer[..<used]

# mark: Sections and names ====================================================================

## The section a `section("name")` attribute places its declaration in, for the object
## format of `os` (§9.8): the name as written, except that Mach-O sections live in segments,
## so a name without a comma goes to `__DATA` (a variable) or `__TEXT` (a function) under
## that name with its leading dot dropped. Storage comes from the current allocator.
pub func section_name(name: str, is_func: bool, os: Os) -> str:
    if os != Os.macos:
        return name
    var k: usize = 0
    while k < name.length:
        if name.bytes[k] == ',':
            return name
        k += 1
    let bare = (str)name.bytes[1..] if name.length > 0 and name.bytes[0] == '.' else name
    var room: u8[64]
    let joined = strings.format(room, f"{"__TEXT," if is_func else "__DATA,"}{bare}") catch failure:
        return name
    let copy = new u8[joined.length] --- catch failure:
        return name
    memory.copy(copy, joined.bytes, joined.length)
    return (str)copy

## Every target name, for `--target` with no argument (§19.6).
pub let names: str[3] = ["x86_64-linux", "x86_64-windows", "arm64-macos"]