 : define-parser-word ( parser word -- )
     ! Return the body of the word that is the compiled version
     ! of the parser.
+
     2dup swap peg>> (compile) ( -- result ) define-declared
     swap id>> "peg-id" set-word-prop ;
 

    '[ @ calc-seq-result ] [ f ] if* ; inline

M: seq-parser (compile)
    [
        [ input-slice V{ } clone <parse-result> ] %
        [
            parsers>> unclip compile-parser-quot [ parse-seq-element ] curry ,
            [ compile-parser-quot [ merge-errors ] compose [ parse-seq-element ] curry , ] each
        ] { } make , \ 1&& ,
    ] [ ] make ;

TUPLE: choice-parser parsers ;

M: choice-parser (compile)
    [
        [
            parsers>> [ compile-parser-quot ] map
            unclip , [ [ merge-errors ] compose , ] each
        ] { } make , \ 0|| ,
    ] [ ] make ;

TUPLE: repeat0-parser parser ;

: (repeat) ( quot: ( -- result ) result -- result )
    over call [
        [ remaining>> swap remaining<< ] 2keep
        ast>> swap [ ast>> push ] keep
        (repeat)
    ] [
        nip
    ] if* ; inline recursive


: calc-seq-result ( prev-result current-result -- next-result )
    [
        [ remaining>> >>remaining ] [ ast>> ] bi
        dup ignore? [ drop ] [ over ast>> push ] if
    ] [
        drop f
    ] if* ;
