const { Parser, pure, many, many1 } = Schach.Parsing;
const { number } = Schach.Parsing.Arithmetic;
const { char, predicate, spaces, string } = Schach.Parsing.Text;
const ESCAPE = {
'b': "\b",
'f': "\f",
'n': "\n",
'r': "\r",
't': "\t",
'v': "\v",
"'": "'",
'"': '"',
'\\': '\\'
};
const escapeSequence = char("\\")
.dropThen(
predicate(c => String.fromCodePoint(c) in ESCAPE, 'valid escape character')
.map(String.fromCodePoint)
.map(c => ESCAPE[c]));
const stringValue = char('"')
.dropThen(
many(
escapeSequence
.or(
predicate(c => c != '"'.codePointAt(0) && c != '\\'.codePointAt(0), 'not " or \\')
.map(String.fromCodePoint))))
.thenDrop(char('"'))
.map(l => l.join(''));
const value = stringValue.or(number())
.mapError(({ actual }) => ({ actual, expected: "string or number" }));
const property = () =>
many1(
predicate(c => c != 32 && c != '='.codePointAt(0), 'neither space or =')
.map(String.fromCodePoint))
.map(l => l.join(''))
.thenDrop(spaces())
.thenDrop(char('='))
.thenDrop(spaces())
.zip(value)
.map(([name, value]) => ({ name, value }));
const openTag =
char('<')
.dropThen(
many1(
predicate(
c => c != 32 && c != '>'.codePointAt(0), 'neither space or >')
.map(String.fromCodePoint))
.map(l => l.join('')))
.thenDrop(spaces())
.zip(many(property().thenDrop(spaces())))
.thenDrop(char('>'))
.map(([tag, props]) => ({ tag, props }));
const closeTag = (tag) => string(`</${tag}>`);
const myXML = Parser.of(() => {
const tag =
openTag.flatMap(({ tag, props }) =>
myXML().or(pure(undefined))
.map(content => ({ tag, props, content }))
.thenDrop(closeTag(tag)));
return many1(tag.or(value));
});