【问题标题】:parser-ts: simple many parser goes into infinite loopparser-ts:简单的许多解析器进入无限循环
【发布时间】:2023-01-04 07:13:31
【问题描述】:
试图了解解析器如何在parser-ts 中工作,但遇到了一个非常意外的行为,一个简单的P.many 解析器在字符串上运行只是永远挂起,我做错了什么?
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));
这个解析器的最终目标是能够区分标记(看起来像 [123])和所有其他文本,无论它是什么
【问题讨论】:
标签:
typescript
fp-ts
io-ts-library
parser-ts
【解决方案1】:
您需要在 char.ts 中使用 many 函数而不是 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)
由于 S.spaces 匹配 0 个或多个空白字符,当您使用 Parser.many 时,我相信发生的事情是它一直匹配 0 个字符,返回一个新的解析器,然后继续匹配 0 个字符。