import Base import bundle_pack.bend as B # Experimental reversible constructor RESULT receipts, not a universal Raw->C # inverse or production Decode policy. Only the trusted author supplies undo. type Construction is Type: Constructed{cooked:Cooked,undo:Cooked -> Raw} Invalid{raw:Raw,error:Error} type Staged is Type: Valid{context:Context,cooked:Cooked,undo:Cooked -> Raw,positions:List<&2,Maybe<&2,Error>>} Failed{context:Context,raw:Raw,positions:List<&2,Maybe<&2,Error>>} def undo_pack(~HR:Type,~HC:Type,~TR:Type,~TC:Type,headUndo:HC -> HR,tailUndo:TC -> TR,cooked:B.Pack) -> B.Pack: match cooked: case B.Pack{head,tail}: B.Pack{headUndo(head),tailUndo(tail)} def constructed_tail(~Ctx:Type,~HR:Type,~HC:Type,~TR:Type,~TC:Type,~Error:Data,head:HC,headUndo:HC -> HR,tail:Staged) -> Staged,B.Pack,Error>: match tail: case Valid{ctx,cooked,undo,positions}: Valid{ctx,B.Pack{head,cooked},p => undo_pack(~HR,~HC,~TR,~TC,headUndo,undo,p),None{} <> positions} case Failed{ctx,raw,positions}: Failed{ctx,B.Pack{headUndo(head),raw},None{} <> positions} def invalid_tail(~Ctx:Type,~HR:Type,~HC:Type,~TR:Type,~TC:Type,~Error:Data,head:HR,error:Error,tail:Staged) -> Staged,B.Pack,Error>: match tail: case Valid{ctx,cooked,undo,positions}: Failed{ctx,B.Pack{head,undo(cooked)},Some{error} <> positions} case Failed{ctx,raw,positions}: Failed{ctx,B.Pack{head,raw},Some{error} <> positions} def constructed_head(~Ctx:Type,~HR:Type,~HC:Type,~TR:Type,~TC:Type,~Error:Data,~stageTail:Ctx -> TR -> Staged,tail:TR,observed:Ctx & Construction) -> Staged,B.Pack,Error>: match observed: case (ctx,Constructed{head,undo}): constructed_tail(~Ctx,~HR,~HC,~TR,~TC,~Error,head,undo,stageTail(ctx,tail)) case (ctx,Invalid{head,error}): invalid_tail(~Ctx,~HR,~HC,~TR,~TC,~Error,head,error,stageTail(ctx,tail)) def stage(~Ctx:Type,~HR:Type,~HC:Type,~TR:Type,~TC:Type,~Error:Data,~constructHead:Ctx -> HR -> Ctx & Construction,~stageTail:Ctx -> TR -> Staged,ctx:Ctx,raw:B.Pack) -> Staged,B.Pack,Error>: match raw: case B.Pack{head,tail}: constructed_head(~Ctx,~HR,~HC,~TR,~TC,~Error,~stageTail,tail,constructHead(ctx,head)) def terminal(~Ctx:Type,~Error:Data,ctx:Ctx,raw:Unit) -> Staged: Valid{ctx,Unit{},u => u,[]}