简体   繁体   中英

parser-ts: simple many parser goes into infinite loop

Trying to understand how parsers work in parser-ts , but encountered a pretty unexpected behaviour, a simple P.many parser run on a string just hangs for ever, what am I doing wrong?

const everything = pipe(
  Ch.alphanum,
  P.alt(() => S.spaces)
);



const input1 = `hello  [123]`;
const res = run(P.many(everything), input1); // this never finishes, i expect "hello  "
const res = run(everything, input1); // this finishes, but only reads one char

console.log(JSON.stringify(res, null, 2));

The ultimate goal of this parser is to be able to distinguish tokens (that look like [123]) and all other text, whatever it may be

You need to use the many function inside char.ts instead of Parser.ts

import * as Ch from "parser-ts/lib/char"
import * as P from "parser-ts/lib/Parser"
import * as S from "parser-ts/lib/string"

import {run} from "parser-ts/lib/code-frame"


const everything = pipe(
  Ch.alphanum,
  P.alt(() => S.spaces)
);

const input1 = `hello  [123]`;
const res = run(Ch.many(everything), input1); // this never finishes, i expect "hello  "
// const res = run(everything, input1); // this finishes, but only reads one char

console.log(res)

Since S.spaces matches 0 or more whitespace characters, when you use Parser.many, I believe what is happening is that it keeps matching 0 characters, returning a new parser and then continuing to match 0 characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM