'Copyright Luke Ceddia
'SPDX-License-Identifier: Apache-2.0
'if.bm - Parse rules for IF statement

'Expects: IF
'Results: newline
function ps_if
    $if DEBUG_PARSE_TRACE then
    debuginfo "Start conditional"
    $end if
    root = ast_add_node(AST_IF)
    ps_consume TOK_IF
    ps_add_nested_structure root

    condition = ps_expr
    if not type_is_number(type_of_expr(condition)) then ps_error "Condition must be a numeric expression"
    root->attach(condition)
    ps_consume TOK_THEN

    'A REM after THEN acts as a command; we remain in single-line if mode
    if ucase$(tok_content$) = "REM" then
        block = ast_add_node(AST_BLOCK)
        root->attach(block)
        ps_remove_nested_structure
        ps_if = root
        $if DEBUG_PARSE_TRACE then
        debuginfo "Completed conditional (single-line REM)"
        $end if
        exit function
    end if

    if tok_token <> TOK_NEWLINE or ps_is_linejoin then
        $if DEBUG_PARSE_TRACE then
        debuginfo "Single-line IF"
        $end if
        root->attach(ps_if_stmts)
        if tok_token = TOK_ELSE then
            ps_consume TOK_ELSE
            root->attach(ps_if_stmts)
        end if
    else
        $if DEBUG_PARSE_TRACE then
        debuginfo "Multi-line IF"
        $end if
        root->attach(ps_block)
        do while tok_token = TOK_ELSEIF
            ps_consume TOK_ELSEIF
            condition = ps_expr
            if not type_is_number(type_of_expr(condition)) then ps_error "Condition must be a numeric expression"
            root->attach(condition)
            ps_consume TOK_THEN
            root->attach(ps_block)
        loop
        if tok_token = TOK_ELSE then
            ps_consume TOK_ELSE
            root->attach(ps_block)
        end if
        ps_consume TOK_END
        ps_consume TOK_IF
    end if

    ps_remove_nested_structure
    ps_if = root
    $if DEBUG_PARSE_TRACE then
    debuginfo "Completed conditional"
    $end if
end function

'Expects: Start of a statement or :
'Results: ELSE or NEWLINE
'Note: This handles one or more statements joined by : and terminated by ELSE/NEWLINE, or an implicit GOTO
function ps_if_stmts
    $if DEBUG_PARSE_TRACE then
    debuginfo "Start if stmts"
    $end if
    block = ast_add_node(AST_BLOCK)
    if tok_token = TOK_NUMINT then
        block->attach(ps_goto_p)
    else
        do
            while ps_is_linejoin
                ps_consume TOK_NEWLINE
            wend
            stmt = ps_stmt
            block->attach(stmt)
            while ps_is_linejoin
                ps_consume TOK_NEWLINE
            wend
        loop until ps_is_terminator(tok_token)
    end if
    ps_if_stmts = block
    $if DEBUG_PARSE_TRACE then
    debuginfo "Completed if stmts"
    $end if
end function
