adam-mcdaniel / oakc

A portable programming language with a compact intermediate representation
Apache License 2.0
725 stars 21 forks source link

Added the `? :` operator for conditional expressions #65

Closed adam-mcdaniel closed 4 years ago

adam-mcdaniel commented 4 years ago

This PR adds constant and non-constant conditional expressions. This allows the user to use conditions more expressively. Here's an example of it's usage.

#[std]

fn yes_or_no(prompt: &char) -> bool {
    putstr(prompt);
    let input = get_char();
    while input == '\r' || input == '\n' {
        input = get_char();
    }
    return input == 'y' ||
           input == 'Y';
}

const C = 1;
const GO = 2;
const TYPESCRIPT = 3;
const UNKNOWN = 4;

// If TARGET == 'c', then set BACKEND to C, else if TARGET == 'g', ...
const BACKEND = TARGET == 'c'?
    C
    : TARGET == 'g'?
        GO
        : TARGET == 't'?
            TYPESCRIPT
            : UNKNOWN;

fn main() {
    putnumln(BACKEND);

    // If the user likes apples, print that they like apples!
    // If not, print that they do not like apples.
    putstrln(
        yes_or_no("Do you like apples (y/n)? ")?
            "You like apples!"
            : "You don't like apples!"
    )
}

This is basically an exact rip-off of C's conditional expressions.