-
Notifications
You must be signed in to change notification settings - Fork 3
Open
Description
1 解析器的返回值是一组状态,包括:
- success: 是否解析成功
- index: 如解析成功,解析到的位置,失败为-1
- value 如解析成功,解析到的值,失败为undefined
- lastIndex 如解析失败,本次解析的最后位置,成功为-1
- expected 如解析失败,期望的值,成功为undefined
2 解析器的基本构造方式为:
- combinator.string(str) 基于string,创建一个匹配该string的解析器。
- combinator.regex(re, grp) 基于一个正则表达式,创建一个匹配该RE的解析器,返回grp指定的RE中第几个捕获组,grp默认为0;
- combinator.success(value) 直接返回一个解析器,这个解析器直接基于当前输入流匹配位置返回成功状态,成功的值由value指定。
- combinator.fail(expected) 直接返回一个解析器,该解析器直接基于当前匹配位置返回一个失败状态。
- combinator.chr(chr) 基于chr创建向前看一个字符的解析器,如成功则index前进一个字符,如失败则不动
- combinator.inStr(str) 基于str创建一个向前看一个字符的解析器,如前面的字符在str中,则成功
- combinator.noInStr(str) inStr的相反
- combinator.until(fun) 基于fun创建一个向前看解析器,如下一个字符符合fun函数的断言,则一直继续。
- combinator.lazy(fun) 基于fun创建一个解析器,该解析器的解析规则,是解析时,执行fun后获取的。
3 解析器的基本组合构造方式为:
- 顺序结构 seq_parser = combinator.seq(parser1, parser2, parser3, ...); 依次在输入流上执行parser1..N
- 选择结构 or_parser = combinator.or(parser1, parser2, parser3, ...); 在输入流上直到某个parserN成功,则返回。
- 匹配指定次数 parser3time = combinator.times(parser, 3); //连续运用parser3次
- 匹配0到3次 paser0to3time = combinator.times(parser, 0, 3); //在输入流应用0到3次则返回
- 匹配0到任意次 parserInfinity = combinator.times(parser, 0, Infinity); //在输入流应用到无法匹配则返回
4 P-Combinator预置解析器
- letter = combinator.regex(/[a-z]/i) 匹配单个字母的解析器
- letters = combinator.regex(/a-z]*/i) 匹配多个连续的字母的解析器
- digit = combinator.regex(/0-9/) 匹配单个数字的解析器
- digits = combinator.regex(/0-9/*) 匹配数字串
- whitespace = combinator.regex(/\s+/) 匹配空白字符
- whitespaceOpt = combinator.regex(/\s*/) 匹配可选的空白字符
- any = combinator.regex(/./) 匹配任何字符
- all 直接返回输入流的所有剩余字符为value,index为输入流的总长度
- eof 如index === stream.length,则返回成功状态
Metadata
Metadata
Assignees
Labels
No labels