import { Token } from '../Lexer' ; import { Parser , ParseResult , ParserOutput } from './ParserInterface' ; export function amb < TKind , TResult > ( p ) { return { parse ( token ) { const branches = p . parse ( token ) ; if ( ! branches . successful ) { return branches ; } const group = new Map < Token < TKind > | undefined , ParseResult < TKind , TResult > [ ] > ( ) ; for ( const r of branches . candidates ) { const rs = group . get ( r . nextToken ) ; if ( rs === undefined ) { group . set ( r . nextToken , [ r ] ) ; } else { rs . push ( r ) ; } } return { candidates : Array . from ( group . values ( ) ) . map ( ( rs ) => ( { firstToken : rs [ 0 ] . firstToken , nextToken : rs [ 0 ] . nextToken , result : rs . map ( ( r ) => r . result ) } ) ) , successful : true , error : branches . error } ; } } ; }