diff --git a/semen.scm b/semen.scm index 9e1831b..3a8dde1 100644 --- a/semen.scm +++ b/semen.scm @@ -1422,6 +1422,12 @@ ;; a shift is the promoted left operand, not a join: ;; (<< l b), l : long -> long; (>> c b), c : char -> int ((<< >>) (promoted-type (expression-type (second expr) env))) + ;; a value if is the join of its values, as an operator is of its + ;; operands -- and nothing when one of them says nothing + ((if) (let ((types (map (cut expression-type <> env) + (if-values (remove comment-form? (cdr expr)))))) + (and (every identity types) + (fold (lambda (t joined) (arith-join joined t)) #f types)))) ;; a complement is the operand promoted, as a negation is ((~ bit-not bitwise-not) (promoted-type (expression-type (second expr) env))) ;; ...and an increment is the operand unpromoted: @@ -1482,6 +1488,12 @@ (let ((type (underlying (parse-type written)))) (or (ptr-type? type) (array-type? type))))) +;;; (if t1 v1 t2 v2 e) -> (v1 v2 e) +(define (if-values parts) + (if (and (pair? parts) (pair? (cdr parts)) (pair? (cddr parts))) + (cons (cadr parts) (if-values (cddr parts))) + parts)) + (define (arith-join left right) (cond ((not left) right) diff --git a/tests/codegen.scm b/tests/codegen.scm index 5841b71..0a5a2f5 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -846,6 +846,16 @@ whitespace aside, THEN?" "a function's types are written out")) ;; a call was typed by asking the global table what a function of ;; that name returns, which a local pointer is not + ;; a value if had no rule either: it is the join of its values + (test-assert "a value if joins its branches" + (emits? (in-fn "(var x _ (if a 1 2.5))") "double x = a ? 1 : 2.5")) + (test-assert "every one of a chain" + (emits? (in-fn "(var x _ (if a 1 b 2 3.5f))") "float x")) + (test-assert "an aggregate as itself" + (emits? "(struct pt ((x int))) (fn f ((a int) (p (struct pt))) void (var q _ (if a p p)))" + "struct pt q = a ? p : p")) + (test-assert "and none when a branch says nothing" + (reports? (in-fn "(var x _ (if a (unheard-of) 1))") "infer")) ;; none of these had a rule (test-assert "#t is a bool, as true is" (emits? (in-fn "(var t _ #t)") "bool t = 1"))