Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.42.0

0.42.0 / src / back / c / emit / operators.lucb

#==============================================================================================
#
#   emit/operators - Operators
#
#   DESCRIPTION:
#       Unary operators, binary operators through the runtime's checked helpers, long
#       left-leaning chains as sequences, vector lanes, and equality over every type that
#       has it.
#
#==============================================================================================
extend Emitter:
    # mark: Operators ==========================================================================

    func unary(e: ast.Node*) -> !:
        let inner = e.left else return
        if e.text == "try":
            try self.try_expr(e)
            return
        if e.text == "not":
            try self.put("(!")
            try self.value(inner, types.bool_id)
            try self.put(")")
            return
        if e.text == "&":
            try self.address(inner)
            return
        if e.text == "*":
            try self.put("(*(")
            try self.expr(inner)
            try self.put("))")
            return
        if e.text == "+":
            try self.expr(inner)
            return
        let t = try self.ty(e)
        if self.is_vector(t):
            try self.vector_unary(e, inner, t)
            return
        if self.is_float(t):
            try self.put("(-(")
            try self.expr(inner)
            try self.put("))")
            return
        if e.text == "~":
            if self.is_int(t) and not self.is_signed(t):
                try self.put("((")
                try self.put_type(t)
                try self.put(")lb_not_u((uint64_t)(")
                try self.expr(inner)
                try self.put("), ")
                try self.put_u64((u64)self.bits(t))
                try self.put("))")
                return
            try self.put("((")
            try self.put_type(t)
            try self.put(")~(")
            try self.expr(inner)
            try self.put("))")
            return
        if e.text == "-%":
            try self.put("((")
            try self.put_type(t)
            try self.put(")")
            try self.put("lb_negw_s(" if self.signed_of(t) else "lb_negw_u(")
            try self.word(t, inner)
            try self.put(", ")
            try self.put_u64((u64)self.bits(t))
            try self.put("))")
            return
        # `-literal` is one constant, not a checked negation: `-128` is a valid `i8`
        if inner.kind == ast.Kind.literal and self.c.table.is_integer(t):
            let v = literals.decode_integer(inner.text) catch failure:
                recover 0
            if v == 9223372036854775808:
                try self.put("((int64_t)(1ULL << 63))")
                return
            if v <= 9223372036854775807:
                try self.put("((")
                try self.put_type(t)
                try self.put(")(-")
                try self.put_u64(v)
                try self.put("LL))")
                return
        if self.folding:
            try self.put("(-(")
            try self.expr(inner)
            try self.put("))")
            return
        try self.put("((")
        try self.put_type(t)
        try self.put(")lb_neg_s((int64_t)(")
        try self.expr(inner)
        try self.put("), ")
        try self.put_u64((u64)self.bits(t))
        try self.put("))")

    ## `l op r` for a binary operator: logical, comparison, pointer, float, bitwise,
    ## optional, or checked integer arithmetic, with its operands sequenced first when
    ## either has an effect.
    func binary(e: ast.Node*) -> !:
        let l = e.left else return
        let r = e.right else return
        let op = e.text
        if self.chain_left == none and try self.chain_length(e) >= chain_limit:
            try self.chain(e)
            return
        if op == "and" or op == "or":
            try self.put("(")
            try self.value(l, types.bool_id)
            try self.put(" && " if op == "and" else " || ")
            try self.value(r, types.bool_id)
            try self.put(")")
            return
        # a plain read of an `@T` operand is a load of the `T` (§15.1)
        var lt = try self.ty(l)
        if self.is_atomic(lt):
            lt = self.elem(lt)
        var rt = try self.ty(r)
        if self.is_atomic(rt):
            rt = self.elem(rt)
        let t = try self.ty(e)
        # C arithmetic operators and helper-call arguments have no evaluation
        # order. Snapshot both operands before an effect can change either value.
        if self.sequenced_id(l) == none and self.sequenced_id(r) == none and (may_have_effect(l) or may_have_effect(r)):
            try self.put("({ ")
            var ordered: usize = 0
            if lt != types.none_id:
                ordered += try self.hoist(l, types.i64_id if lt == types.untyped_int_id else types.f64_id if lt == types.untyped_float_id else lt)
            if rt != types.none_id:
                ordered += try self.hoist(r, types.i64_id if rt == types.untyped_int_id else types.f64_id if rt == types.untyped_float_id else rt)
            try self.binary(e)
            try self.end_sequence(ordered)
            return
        if self.is_vector(t):
            try self.vector_binary(e, l, lt, r, rt, t)
            return
        var ot = operand_type(lt, rt)
        # an array beside a span compares as a span: lengths, then elements (§7.4)
        if self.kind(lt) == types.Kind.array and self.kind(rt) == types.Kind.span:
            ot = rt
        if op == "==" or op == "!=":
            try self.equality(l, lt, r, rt, ot, op == "!=")
        elif op == "<" or op == "<=" or op == ">" or op == ">=":
            try self.ordering(l, r, op, ot)
        elif self.is_ptr(ot):
            try self.pointer_arithmetic(l, r, rt, op)
        elif self.is_float(ot):
            try self.put("(")
            try self.value(l, ot)
            try self.put(" ")
            try self.put(op)
            try self.put(" ")
            try self.value(r, ot)
            try self.put(")")
        elif op == "&" or op == "|" or op == "^":
            try self.put("((")
            try self.put_type(ot)
            try self.put(")(")
            try self.value(l, ot)
            try self.put(" ")
            try self.put(op)
            try self.put(" ")
            try self.value(r, ot)
            try self.put("))")
        elif op == "+?" or op == "-?" or op == "*?":
            try self.optional_arithmetic(l, r, op, t)
        else:
            try self.checked_op(helper_name(op), ot, l, r)

    ## `l < r` and the other orderings at the operand type `ot`; text compares by its
    ## bytes.
    func ordering(l: ast.Node*, r: ast.Node*, op: str, ot: u32) -> !:
        if ot == types.str_id:
            try self.put("(lb_str_compare(")
            try self.expr(l)
            try self.put(", ")
            try self.expr(r)
            try self.put(") ")
            try self.put(op)
            try self.put(" 0)")
            return
        try self.put("(((")
        try self.put_type(ot)
        try self.put(")(")
        try self.value(l, ot)
        try self.put(")) ")
        try self.put(op)
        try self.put(" ((")
        try self.put_type(ot)
        try self.put(")(")
        try self.value(r, ot)
        try self.put(")))")

    ## `p + n`, `p - n`, and `p - q`: C's own pointer arithmetic, the count widened to
    ## `ptrdiff_t`.
    func pointer_arithmetic(l: ast.Node*, r: ast.Node*, rt: u32, op: str) -> !:
        try self.put("(")
        try self.expr(l)
        if op == "-" and self.is_ptr(rt):
            try self.put(" - ")
            try self.expr(r)
            try self.put(")")
            return
        try self.put(" ")
        try self.put(op)
        try self.put(" (ptrdiff_t)(")
        try self.expr(r)
        try self.put("))")

    ## `l +? r`, `-?`, `*?`: the overflow helper's flag is the optional's presence and its
    ## result the value, of the optional type `t`.
    func optional_arithmetic(l: ast.Node*, r: ast.Node*, op: str, t: u32) -> !:
        let n = self.tmp()
        let et = self.elem(t)
        try self.put("({ ")
        try self.put("int64_t " if self.signed_of(et) else "uint64_t ")
        try self.put_tmp("qo", n)
        try self.put("; ")
        try self.put_type(t)
        try self.put(" ")
        try self.put_tmp("qr", n)
        try self.put("; ")
        try self.put_tmp("qr", n)
        try self.put(".present = lb_")
        try self.put("qadd" if op == "+?" else ("qsub" if op == "-?" else "qmul"))
        try self.put("_s(" if self.signed_of(et) else "_u(")
        try self.word(et, l)
        try self.put(", ")
        try self.word(et, r)
        try self.put(", ")
        try self.put_u64((u64)self.bits(et))
        try self.put(", &")
        try self.put_tmp("qo", n)
        try self.put("); ")
        try self.put_tmp("qr", n)
        try self.put(".value = (")
        try self.put_type(et)
        try self.put(")(")
        try self.put_tmp("qo", n)
        try self.put("); ")
        try self.put_tmp("qr", n)
        try self.put("; })")

    ## Whether `e` is a link of a chain of type `t`: `a + b + c + ...` leans left, and C
    ## nests a call for every link, which the C compiler bounds (clang stops at 256). A
    ## link is one of the operators whose result has its left operand's type.
    func is_link(e: ast.Node*, t: u32) -> bool!:
        if e.kind != ast.Kind.binary:
            return false
        let op = e.text
        if not (op == "+" or op == "-" or op == "*" or op == "&" or op == "|" or op == "^" or op == "and" or op == "or"):
            return false
        return try self.ty(e) == t

    ## The links from `e` down its left side: the run of the same type, exactly, so an
    ## untyped literal chain is one run and the typed node above it another.
    func chain_length(e: ast.Node*) -> usize!:
        let t = try self.ty(e)
        if self.is_vector(t) or self.is_ptr(t):
            return 0
        var count: usize = 0
        var cursor: ast.Node*? = e
        while let node = cursor:
            if not try self.is_link(node, t):
                break
            count += 1
            cursor = node.left
        return count

    ## A long chain as a sequence: the leaf into a temporary, then each link applied to it
    ## in order, so the C nests no deeper for a chain of any length.
    func chain(e: ast.Node*) -> !:
        let t = try self.ty(e)
        # an untyped chain computes in the word the nested form would, `int64_t` or `double`
        let held = types.i64_id if t == types.untyped_int_id else types.f64_id if t == types.untyped_float_id else t
        let n = self.tmp()
        try self.put("({ ")
        try self.put_type(held)
        try self.put(" ")
        try self.put_tmp("ch", n)
        try self.put("; ")
        try self.chain_links(e, t, held, n)
        try self.put_tmp("ch", n)
        try self.put("; })")

    func chain_links(node: ast.Node*, t: u32, held: u32, n: u32) -> !:
        let l = node.left else return
        if try self.is_link(l, t):
            try self.chain_links(l, t, held, n)
        else:
            try self.put_tmp("ch", n)
            try self.put(" = ")
            try self.value(l, held)
            try self.put("; ")
        try self.put_tmp("ch", n)
        try self.put(" = ")
        self.chain_left = l
        self.chain_temp = n
        try self.binary(node)
        self.chain_left = none
        try self.put("; ")

    ## Lane-wise arithmetic (§5.12): the operands bound once, each lane of the result the
    ## scalar operation on the operands' lanes; a scalar operand stands for every lane.
    func vector_binary(e: ast.Node*, l: ast.Node*, lt: u32, r: ast.Node*, rt: u32, t: u32) -> !:
        let et = self.elem(t)
        let n = self.tmp()
        let lv = self.kind(lt) == types.Kind.array
        let rv = self.kind(rt) == types.Kind.array
        try self.put("({ ")
        try self.put_type(lt if lv else et)
        try self.put(" ")
        try self.put_tmp("va", n)
        try self.put(" = ")
        try self.value(l, lt if lv else et)
        try self.put("; ")
        try self.put_type(rt if rv else et)
        try self.put(" ")
        try self.put_tmp("vb", n)
        try self.put(" = ")
        try self.value(r, rt if rv else et)
        try self.put("; ")
        try self.put_type(t)
        try self.put(" ")
        try self.put_tmp("vr", n)
        try self.put("; ")
        let count = self.c.table.get(t).length
        var i: u64 = 0
        while i < count:
            try self.put_tmp("vr", n)
            try self.put(".d[")
            try self.put_u64(i)
            try self.put("] = ")
            try self.lane_op(e.text, et, "va", n, i if lv else no_lane, "vb", n, i if rv else no_lane)
            try self.put("; ")
            i += 1
        try self.put_tmp("vr", n)
        try self.put("; })")

    ## Every lane of a vector under `~`, `-`, or `-%` (§5.12).
    func vector_unary(e: ast.Node*, inner: ast.Node*, t: u32) -> !:
        let et = self.elem(t)
        let n = self.tmp()
        try self.put("({ ")
        try self.put_type(t)
        try self.put(" ")
        try self.put_tmp("va", n)
        try self.put(" = ")
        try self.value(inner, t)
        try self.put("; ")
        try self.put_type(t)
        try self.put(" ")
        try self.put_tmp("vr", n)
        try self.put("; ")
        let count = self.c.table.get(t).length
        var i: u64 = 0
        while i < count:
            try self.put_tmp("vr", n)
            try self.put(".d[")
            try self.put_u64(i)
            try self.put("] = ")
            try self.lane_unary(e.text, et, "va", n, i)
            try self.put("; ")
            i += 1
        try self.put_tmp("vr", n)
        try self.put("; })")

    ## `T[N](x)`: every lane is `x`, computed once (§5.12); in a global's initialiser `x` is
    ## a constant and the lanes are a compound literal.
    func splat(e: ast.Node*, t: u32) -> !:
        let first = e.body else return
        let v = first.left else return
        let et = self.elem(t)
        let count = self.c.table.get(t).length
        if self.folding:
            # a static initialiser: braces alone, never a compound literal
            try self.put("{{")
            var k: u64 = 0
            while k < count:
                if k > 0:
                    try self.put(", ")
                try self.value(v, et)
                k += 1
            try self.put("}}")
            return
        let n = self.tmp()
        try self.put("({ ")
        try self.put_type(et)
        try self.put(" ")
        try self.put_tmp("va", n)
        try self.put(" = ")
        try self.value(v, et)
        try self.put("; ")
        try self.put_type(t)
        try self.put(" ")
        try self.put_tmp("vr", n)
        try self.put("; ")
        var i: u64 = 0
        while i < count:
            try self.put_tmp("vr", n)
            try self.put(".d[")
            try self.put_u64(i)
            try self.put("] = ")
            try self.put_tmp("va", n)
            try self.put("; ")
            i += 1
        try self.put_tmp("vr", n)
        try self.put("; })")

    ## `v.sum()`, `v.min()`, `v.max()`: the lanes folded in order (§5.12); a float `min` or
    ## `max` skips a NaN lane when another lane compares.
    func vector_fold(e: ast.Node*, callee: ast.Node*, receiver: ast.Node*, rt: u32) -> !:
        let et = self.elem(rt)
        let n = self.tmp()
        try self.put("({ ")
        try self.put_type(rt)
        try self.put(" ")
        try self.put_tmp("va", n)
        try self.put(" = ")
        try self.receiver_value(receiver, rt)
        try self.put("; ")
        try self.put_type(et)
        try self.put(" ")
        try self.put_tmp("vf", n)
        try self.put(" = ")
        try self.put_tmp("va", n)
        try self.put(".d[0]; ")
        let count = self.c.table.get(rt).length
        var i: u64 = 1
        while i < count:
            if callee.text == "sum":
                try self.put_tmp("vf", n)
                try self.put(" = ")
                try self.lane_op("+", et, "vf", n, no_lane, "va", n, i)
                try self.put("; ")
            else:
                try self.put("if (")
                if self.is_float(et):
                    try self.put_tmp("vf", n)
                    try self.put(" != ")
                    try self.put_tmp("vf", n)
                    try self.put(" || ")
                try self.lane("va", n, i)
                try self.put(" < " if callee.text == "min" else " > ")
                try self.put_tmp("vf", n)
                try self.put(") ")
                try self.put_tmp("vf", n)
                try self.put(" = ")
                try self.lane("va", n, i)
                try self.put("; ")
            i += 1
        try self.put_tmp("vf", n)
        try self.put("; })")

    ## Temporary `name<n>`, or its lane `i` when it is a vector.
    func lane(name: str, n: u32, i: u64) -> !:
        try self.put_tmp(name, n)
        if i != no_lane:
            try self.put(".d[")
            try self.put_u64(i)
            try self.put("]")

    ## One scalar operation of §7.2 or §7.3 on two temporaries' lanes, of type `t`: C's
    ## operator for floats and bits, the runtime's helper for the integer forms.
    func lane_op(op: str, t: u32, a: str, an: u32, ai: u64, b: str, bn: u32, bi: u64) -> !:
        if self.is_float(t) or op == "&" or op == "|" or op == "^":
            try self.put("((")
            try self.put_type(t)
            try self.put(")(")
            try self.lane(a, an, ai)
            try self.put(" ")
            try self.put(op)
            try self.put(" ")
            try self.lane(b, bn, bi)
            try self.put("))")
            return
        try self.put("(")
        try self.put_type(t)
        try self.put(")(lb_")
        try self.put(helper_name(op))
        try self.put("_s(" if self.signed_of(t) else "_u(")
        try self.put("(int64_t)(" if self.signed_of(t) else "(uint64_t)(")
        try self.lane(a, an, ai)
        try self.put("), ")
        try self.put("(int64_t)(" if self.signed_of(t) else "(uint64_t)(")
        try self.lane(b, bn, bi)
        try self.put("), ")
        try self.put_u64((u64)self.bits(t))
        try self.put("))")

    ## `~`, `-`, or `-%` on one temporary's lane, of type `t`.
    func lane_unary(op: str, t: u32, a: str, an: u32, ai: u64) -> !:
        if self.is_float(t):
            try self.put("(-(")
            try self.lane(a, an, ai)
            try self.put("))")
            return
        try self.put("((")
        try self.put_type(t)
        try self.put(")")
        if op == "~":
            if self.signed_of(t):
                try self.put("~(")
                try self.lane(a, an, ai)
                try self.put("))")
                return
            try self.put("lb_not_u((uint64_t)(")
        elif op == "-%":
            try self.put("lb_negw_s((int64_t)(" if self.signed_of(t) else "lb_negw_u((uint64_t)(")
        else:
            try self.put("lb_neg_s((int64_t)(")
        try self.lane(a, an, ai)
        try self.put("), ")
        try self.put_u64((u64)self.bits(t))
        try self.put("))")

    ## `==` and `!=` over scalars, text, pointers, tagged optionals, and composite values.
    func equality(l: ast.Node*, lt: u32, r: ast.Node*, rt: u32, ot: u32, negate: bool) -> !:
        let l_none = l.kind == ast.Kind.literal and l.text == "none"
        let r_none = r.kind == ast.Kind.literal and r.text == "none"
        let tagged = self.is_tagged_opt(lt) or self.is_tagged_opt(rt)
        let view = (self.is_nullable_view(lt) or self.is_nullable_view(rt)) and (l_none or r_none)
        if negate:
            try self.put("(!")
        if view:
            # `view == none`: the data word (§14.3)
            try self.put("((")
            try self.expr(r if l_none else l)
            try self.put(").data == ((void*)0))")
        elif tagged and (l_none or r_none):
            let n = self.tmp()
            let side = r if l_none else l
            try self.put("({ ")
            try self.put_type(rt if l_none else lt)
            try self.put(" ")
            try self.put_tmp("on", n)
            try self.put(" = ")
            try self.expr(side)
            try self.put("; !")
            try self.put_tmp("on", n)
            try self.put(".present; })")
        elif tagged:
            try self.optional_equality(l, r, lt if self.is_tagged_opt(lt) else rt)
        elif ot == types.str_id or ot == types.fmt_id:
            let n = self.tmp()
            try self.put("({ lb_str ")
            try self.put_tmp("sa", n)
            try self.put(" = ")
            try self.expr(l)
            try self.put("; lb_str ")
            try self.put_tmp("sb", n)
            try self.put(" = ")
            try self.expr(r)
            try self.put("; ")
            try self.same_text(try tmp_name("sa", n), try tmp_name("sb", n))
            try self.put("; })")
        elif self.is_record(ot) or self.is_tuple(ot) or self.is_array(ot) or self.kind(ot) == types.Kind.span:
            let n = self.tmp()
            try self.put("({ ")
            try self.put_type(ot)
            try self.put(" ")
            try self.put_tmp("ea", n)
            try self.put(" = ")
            try self.value(l, ot)
            try self.put("; ")
            try self.put_type(ot)
            try self.put(" ")
            try self.put_tmp("eb", n)
            try self.put(" = ")
            try self.value(r, ot)
            try self.put("; ")
            try self.same_value(ot, try tmp_name("ea", n), try tmp_name("eb", n))
            try self.put("; })")
        else:
            try self.put("(")
            if l_none:
                try self.put("((void*)0)")
            else:
                try self.value(l, ot)
            try self.put(" == ")
            if r_none:
                try self.put("((void*)0)")
            else:
                try self.value(r, ot)
            try self.put(")")
        if negate:
            try self.put(")")

    ## `a == b` for two values of the tagged optional type `vt`: both computed once, then
    ## equal when both are absent or both present with equal values.
    func optional_equality(l: ast.Node*, r: ast.Node*, vt: u32) -> !:
        let n = self.tmp()
        try self.put("({ ")
        try self.put_type(vt)
        try self.put(" ")
        try self.put_tmp("oa", n)
        try self.put(" = ")
        try self.value(l, vt)
        try self.put("; ")
        try self.put_type(vt)
        try self.put(" ")
        try self.put_tmp("ob", n)
        try self.put(" = ")
        try self.value(r, vt)
        try self.put("; (")
        try self.put_tmp("oa", n)
        try self.put(".present == ")
        try self.put_tmp("ob", n)
        try self.put(".present) && (!")
        try self.put_tmp("oa", n)
        try self.put(".present || ")
        let oa = try tmp_name("oa", n)
        let ob = try tmp_name("ob", n)
        var a_bytes = try new u8[oa.length + 8] ---
        var b_bytes = try new u8[ob.length + 8] ---
        try self.same_value(self.c.table.get(vt).elem, try strings.format(a_bytes, f"{oa}.value"), try strings.format(b_bytes, f"{ob}.value"))
        try self.put("); })")