simplification
Download
507 lines 17.2 KiBNomsuModified 2026-11-10 raw
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
#!/usr/bin/env nomsu -V8.0.0
###
    This file contains compile-time actions that define basic control flow structures
    like "if" statements and loops.
    
use "core/metaprogramming"
use "core/operators"

### No-Op
test:
    do nothing

public:
    (do nothing) compiles to ""

    ### Conditionals
    test:
        if (no):
            fail "conditional fail"

    (if $condition $if_body) compiles to ("
        if \($condition as lua expr) then
            \($if_body as lua)
        end
    ")

    test:
        unless (yes):
            fail "conditional fail"

    (unless $condition $unless_body) parses as (if (not $condition) $unless_body)
    {
        if $condition $if_body else $else_body, unless $condition $else_body else $if_body
    } all compile to ("
        if \($condition as lua expr) then
            \($if_body as lua)
        else
            \($else_body as lua)
        end
    ")

    (else $) compiles to:
        at (this tree) fail ("
            Compile error: This 'else' is not connected to any 'if' or 'unless' condition.
            Hint: You should probably have a ".." in front of the "else", to indicate that it's attached
        .... to the previous condition.
        ")

    ### Conditional expression (ternary operator)
    ###   Note: this uses a function instead of "(condition and if_expr or else_expr)"
        because that breaks if $if_expr is falsey, e.g. "x < 5 and false or 99"
    test:
        assume ((1 if (yes) else 2) == 1)
        assume ((1 if (no) else 2) == 2)

    {
        $when_true_expr if $condition else $when_false_expr
        $when_false_expr unless $condition else $when_true_expr
    } all compile to:
        ###   If $when_true_expr is guaranteed to be truthy, we can use Lua's idiomatic
            equivalent of a conditional expression: (cond and if_true or if_false)
        if {.Text, .Table, .Number}.($when_true_expr.type):
            return Lua ("
                (\($condition as lua expr) and \($when_true_expr as lua expr) or
            .... \($when_false_expr as lua expr))
            ")
        ..else:
            ###   Otherwise, need to do an anonymous inline function (yuck, too bad lua 
                doesn't have a proper ternary operator!)
                To see why this is necessary consider: (random()<.5 and false or 99)
            return Lua ("
                ((function()
                    if \($condition as lua expr) then
                        return \($when_true_expr as lua expr)
                    else
                        return \($when_false_expr as lua expr)
                    end
                end)())
            ")

    ### GOTOs
    test:
        $i = 0
        --- $loop ---
        $i += 1
        unless ($i == 10):
            go to $loop
        assume ($i == 10)
        --- (Loop) ---
        $i -= 1
        unless ($i == 0):
            go to (Loop)
        assume ($i == 0)

    (--- $label ---) compiles to ("
        ::label_\(
            ($label.stub, as lua id) if ($label.type == "Action") else
                $label as lua id
        )::
    ")

    (go to $label) compiles to ("
        goto label_\(
            ($label.stub, as lua id) if ($label.type == "Action") else
                $label as lua id
        )
    ")

    ### Basic loop control
    ### (break) is wrapped in a block, since Lua only allows it at the end of one
    (stop $var) compiles to:
        if $var:
            return Lua "goto stop_\($var as lua id)"
        ..else:
            return Lua "do break end"

    (do next $var) compiles to:
        if $var:
            return Lua "goto continue_\($var as lua id)"
        ..else:
            return Lua "goto continue"

### The end of a loop's Lua code: labels at the end of each pass for (do next) and
    after the loop for (stop), when the loop's body uses them. This can't use loops,
    since they use it.
at compile time:
    (end of loop $body for $var and $other_var) means:
        $lua = (Lua "")
        if ($body, contains \(do next)):
            $lua, add "\n    ::continue::"
        
        if ($var and ($body, contains \(do next \$var))):
            $lua, add "\n    ::continue_\($var as lua id)::"
        
        if ($other_var and ($body, contains \(do next \$other_var))):
            $lua, add "\n    ::continue_\($other_var as lua id)::"
        
        $lua, add "\nend"
        if ($var and ($body, contains \(stop \$var))):
            $lua, add "\n::stop_\($var as lua id)::"
        
        if ($other_var and ($body, contains \(stop \$other_var))):
            $lua, add "\n::stop_\($other_var as lua id)::"
        
        return $lua

public:
    ### While loops
    test:
        $x = 0
        repeat while ($x < 10): $x += 1
        assume ($x == 10)
        repeat while ($x < 20): stop
        assume ($x == 10)
        repeat while ($x < 20):
            $x += 1
            if (yes):
                do next
            fail "Failed to 'do next'"
        assume ($x == 20)

    (repeat while $condition $body) compiles to:
        $lua = (Lua "while \($condition as lua expr) do\n    ")
        $lua, add ($body as lua) (end of loop $body for (nil) and (nil))
        return $lua
    (while $condition $body) parses as (repeat while $condition $body)

    (repeat $body) parses as (repeat while (yes) $body)
    (repeat until $condition $body) parses as (repeat while (not $condition) $body)
    (until $condition $body) parses as (repeat while (not $condition) $body)
    
    ### For-each loop: (for $ in $list) uses Lua's ipairs() and (for ($k = $v) in $table)
        uses Lua's pairs(). (for $ in ($a to $b)) is a numeric for loop, and
        (for $ in (values yielded by $coroutine)) resumes the coroutine for each value.
    (for $var in $iterable $body) compiles to:
        unless $var:
            at (this tree) fail "No var here"
        
        ### This uses Lua's approach of only allowing loop-scoped variables in a loop
        if (($var.type == "Action") and ($var.stub == "1 =")):
            {$key, $value} = {$var.1, $var.3}
        ..else:
            {$key, $value} = {nil, $var}
        
        unless $value:
            at (this tree) fail "No value here"
        
        ### Numeric loop:
        if (($iterable.type == "Action") and (($iterable, get stub) == "1 to")):
            {$start, $stop} = {$iterable.1, $iterable.3}
            $loop =
                Lua ("
                    local _start = \($start as lua expr)
                    for \($value as lua id)=_start,\($stop as lua expr) do
                ")
            
            if $key:
                $loop, add "\n    local \($key as lua id) = \($value as lua id) - _start + 1;"
            
            go to (loop set)
        
        ### Numeric loop with step:
        if (($iterable.type == "Action") and (($iterable, get stub) == "1 to 2 by")):
            {$start, $stop, $step} = {$iterable.1, $iterable.3, $iterable.5}
            $loop =
                Lua ("
                    local _start, _step = \($start as lua expr), \($step as lua expr);
                    for \($value as lua id)=_start,\($stop as lua expr),_step do
                ")
            
            if $key:
                $loop, add
                    "\n    local \($key as lua id) = (\($value as lua id) - _start)/_step + 1"
            
            go to (loop set)
        
        ### Coroutine loop:
        if (($iterable.type == "Action") and (($iterable, get stub) == "values yielded by")):
            $index = (($key as lua id) if $key else (Lua "_i"))
            $loop =
                Lua ("
                    for \$index,\($value as lua id) in coroutine_values(\($iterable.4 as lua expr)) do
                ")
            go to (loop set)
        
        ### for $ in (...):
        if $key:
            $loop =
                Lua ("
                    for \($key as lua id),\($value as lua id) in pairs(
                ....\($iterable as lua expr)) do
                ")
        ..else:
            $loop =
                Lua "for _i,\($value as lua id) in ipairs(\($iterable as lua expr)) do"
        
        --- (loop set) ---
        
        ### The loop is wrapped in a block, so its labels and locals are its own
        $lua = (Lua "do -- for-loop\n")
        $lua, add $loop "\n    " ($body as lua)
        $lua, add (end of loop $body for $key and $value)
        $lua, add "\nend -- for-loop"
        $lua, remove free vars
            {($value as lua id, text), $key and ($key as lua id, text)}
        return $lua

    (for $k = $v in $iter $block) parses as (for ($k = $v) in $iter $block)

    test:
        $d = {.a = 10, .b = 20, .c = 30, .d = 40, .e = 50}
        $result = {}
        for ($k = $v) in $d:
            if ($k == "a"):
                do next $k
            
            if ($v == 20):
                do next $v
            
            add "\$k = \$v" to $result
        assume (($result sorted) deeply equals {"c = 30", "d = 40", "e = 50"})

    ### Numeric range for loops
    test:
        $nums = {}
        for $outer in (1 to 100):
            for $inner in ($outer to ($outer + 2)):
                if ($inner == 2):
                    add -2 to $nums
                    do next $inner
                add $inner to $nums
                if ($inner == 5):
                    stop $outer
        
        assume ($nums deeply equals {1, -2, 3, -2, 3, 4, 3, 4, 5})

    ### repeat $n times is a shorthand:
    test:
        $x = 0
        repeat 5 times:
            $x += 1
        assume ($x == 5)
    
    ### ($i is renamed in the expansion, so it doesn't conflict with variables in $body)
    (repeat $n times $body) parses as (for $i in (1 to $n by 1) $body)

    ### Multi-branch conditional (if..elseif..else)
    test:
        when:
            (1 == 2) (100 < 0):
                fail "bad conditional"
            (1 == 0) (1 == 1) $not_a_variable.x: do nothing
            (1 == 1):
                fail "bad conditional"
            
            (1 == 2):
                fail "bad conditional"
            
            else:
                fail "bad conditional"

    (when $body) compiles to:
        $code = (Lua "")
        $clause = "if"
        $else_allowed = (yes)
        unless ($body.type == "Block"):
            at $body fail ("
                Compile error: 'if' expected a Block, but got a \($body.type).
                Hint: Perhaps you forgot to put a ':' after 'if'?
            ")
        
        for $line in $body:
            unless
                (($line.type == "Action") and (#$line >= 2)) and
                    $line.(#$line) is "Block" syntax tree
            ..:
                at $line fail ("
                    Compile error: Invalid line for the body of an 'if' block.
                    Hint: Each line should contain one or more conditional expressions followed by a block,
                .... or "else" followed by a block.
                ")
            $action = $line.(#$line)
            if (($line.1 == "else") and (#$line == 2)):
                unless $else_allowed:
                    at $line fail ("
                        Compile error: You can't have two 'else' blocks.
                        Hint: Merge all of the 'else' blocks together.
                    ")
                
                unless (#"\$code" > 0):
                    at $line fail ("
                        Compile error: You can't have an 'else' block without a preceding condition.
                        Hint: If you want the code in this block to always execute, you don't need a conditional
                    .... block around it. Otherwise, make sure the 'else' block comes last.
                    ")
                
                $code, add "\nelse\n    " ($action as lua)
                $else_allowed = (no)
            ..else:
                $code, add $clause " "
                for $i in (1 to (#$line - 1)):
                    if ($i > 1):
                        $code, add " or "
                    $code, add ($line.$i as lua expr)
                $code, add " then\n    " ($action as lua)
                $clause = "\nelseif"
        
        if (#"\$code" == 0):
            at $body fail ("
                Compile error: 'if' block has an empty body.
                Hint: This means nothing would happen, so the 'if' block should be deleted.
            ")
        
        $code, add "\nend --when"
        return $code

    test:
        when 5 is:
            1 2 3:
                fail "bad switch statement"
            
            4 5:
                do nothing
            
            5 6:
                fail "bad switch statement"
            
            else:
                fail "bad switch statement"

        when 5 is:
            5:
                $assigned_in_branch = 1
        
        assume ($assigned_in_branch == 1)

    ### Switch statement: (when $x is: 1 2: ...) works like (when: ($x == 1) ($x == 2): ...)
    (when $branch_value is $body) compiles to:
        unless ($body.type == "Block"):
            at $body fail ("
                Compile error: 'when' expected a Block, but got a \($body.type).
                Hint: Perhaps you forgot to put a ':' after the 'is'?
            ")
        define mangler
        $value = ("Var" tree from $branch_value.source with (mangle "branch value"))
        $branches = ("Block" tree from $body.source)
        for $line in $body:
            if (($line.type == "Action") and (#$line >= 2) and ($line.1 != "else")):
                $new_line = ("Action" tree from $line.source)
                for $i in (1 to (#$line - 1)):
                    $option = $line.$i
                    $new_line, add \(\$value == \$option)
                $new_line, add $line.(#$line)
                $line = $new_line
            $branches, add $line
        
        ### (Not a (do) block, since that would make the branches' variables local to it)
        return Lua ("
            do --when $ is
                local \($value as lua) = \($branch_value as lua expr)
                \(\(when \$branches) as lua)
            end --when $ is
        ")

    ### Like functions, (do) blocks are scopes for the variables that are made in them
    test:
        $x = 1
        do:
            local $x = 2
            $y = 3
            assume ($x == 2)
        assume ($x == 1)
        assume ($y == (nil))
        
        ### (local:) in a block that isn't a scope still makes a new variable
        if (yes):
            local $x = 3
            assume ($x == 3)
        assume ($x == 1)
    
    (do $action) compiles to:
        $body = ($action as lua)
        $body.is_scope = (yes)
        return Lua ("
            do
                \$body
            end -- do
        ")

    test:
        assume ((result of: return 99) == 99)

    ### Inline thunk:
    (result of $body) compiles to "\(\(->(\$body)) as lua)()"
    test:
        $t = {1, {2, {{3}, 4}, 5, {{{6}}}}}
        $flat = {}
        for $ in recursive $t:
            if ((lua type of $) == "table"):
                for $2 in $:
                    recurse $ on $2
            ..else:
                add $ to $flat
        
        assume (($flat sorted) deeply equals {1, 2, 3, 4, 5, 6})

    ### Recurion control flow
    (recurse $v on $x) compiles to
        Lua "table.insert(_stack_\($v as lua expr), \($x as lua expr))"

    (for $var in recursive $structure $body) compiles to:
        $stack = "_stack_\($var as lua id)"
        $lua =
            Lua ("
                do -- recursive loop
                local \$stack = {\($structure as lua expr)}
                while #\$stack > 0 do
                    local \($var as lua expr) = table.remove(\$stack, 1)
                \("    ")
            ")
        $lua, add ($body as lua) (end of loop $body for $var and (nil))
        $lua, add "\nend -- recursive loop"
        return $lua

    ### Comprehensions
    test:
        assume ((($x * 2) for $x in {1, 2, 3}) deeply equals {2, 4, 6})
        assume (($ for $ in (1 to 5)) deeply equals {1, 2, 3, 4, 5})
        assume (($ for $ in (1 to 5 by 2)) deeply equals {1, 3, 5})
        assume (($ for $ in (5 to 1)) deeply equals {})
        assume (($k for ($k = $v) in {10, 20}) deeply equals {1, 2})
        assume (($ for $ in {1, 2, 3, 4} if ($ > 2)) deeply equals {3, 4})
        assume (($ = ($ * $) for $ in {1, 2, 3}) deeply equals {.1 = 1, .2 = 4, .3 = 9})
        assume
            ($v = $k for ($k = $v) in {.x = 1, .y = 2} if ($v > 1)) deeply equals {.2 = "y"}

    ($expr for $var in $iterable) parses as
        result of:
            $comprehension = {}
            for $var in $iterable:
                $comprehension.(#$comprehension + 1) = $expr
            return $comprehension

    ($expr for $var in $iterable if $condition) parses as
        result of:
            $comprehension = {}
            for $var in $iterable:
                if $condition:
                    $comprehension.(#$comprehension + 1) = $expr
            
            return $comprehension

    ($key = $value for $var in $iterable) parses as
        result of:
            $comprehension = {}
            for $var in $iterable:
                $comprehension.$key = $value
            return $comprehension

    ($key = $value for $var in $iterable if $condition) parses as
        result of:
            $comprehension = {}
            for $var in $iterable:
                if $condition:
                    $comprehension.$key = $value
            
            return $comprehension