我正在使用Sprache构建一个简单的命令样式语法。我正在尝试找出是否有一种方法可以在缺少结束字符时获得更好的错误报告(例如],),})。
如果缺少结束字符,我的语法正确地报告了一个错误。然而,消息传递导致难以理解真正的问题。给定以下要解析的字符串:
sum 10 [multiply 5 4
Sprache报告以下错误:
Sprache.ParseException : Parsing failure: unexpected '['; expected newline or end of input (Line 1, Column 8); recently consumed: sum 10
似乎发生的情况是,解析器试图在我的CommandSubstitution上匹配,但找不到结束的']'。这会导致解析器后退并尝试替代。由于它不能为该命令匹配更多的Things,因此它尝试在CommandTerminator上匹配。因为这不能匹配'[',它会报告错误,抱怨预期的newline或end of input,而不是说,“嘿,伙计,你没有匹配你的大括号!”
有什么变通方法或建议可以改进语法,使报告更好地使用一个解析库,如Sprache?
public static readonly Parser<Word> Word = Parse.Char(IsWordChar, "word character").AtLeastOnce().Text()
.Select(str => new Word(str));
public static readonly Parser<CommandSubstitution> CommandSubstitution = from open in Parse.Char('[').Once()
from body in Parse.Ref(() => Things)
from close in Parse.Char(']').Once()
select new CommandSubstitution(body.ToList());
public static readonly Parser<Thing> Thing = CommandSubstitution.Or<Thing>(Word);
public static readonly Parser<IEnumerable<Thing>> Things = (from ignoreBefore in WordSeparator.Optional()
from thing in Thing
from ignoreAfter in WordSeparator.Optional()
select thing).Many();
public static readonly Parser<IEnumerable<Thing>> Command = from things in Things
from terminator in CommandTerminator
select things;发布于 2016-08-18 10:27:21
听起来,总体问题是Sprache失败了,尝试了替代方案,然后又失败了,而它应该在第一次失败后放弃。
您正在使用Parse.Many扩展方法定义Things解析器。Parse.Many解析器的特点是,无论其内部解析器是成功还是失败,它都会成功。如果内部解析器失败,Parse.Many将简单地假定没有更多的输入需要使用。
这似乎就是这里正在发生的事情。首先,Parse.Many使用片段"sum 10 "。然后,它尝试解析更多的输入,但失败了。由于它无法解析更多的输入,因此它假定不再需要使用更多的输入。但是随后会产生一个错误,因为片段[multiply 5 4还没有被使用。
要解决此问题,请使用Parse.XMany而不是Parse.Many。如果Parse.XMany的内部解析器在使用至少一个字符后失败,那么Parse.XMany将立即放弃并报告失败。
https://stackoverflow.com/questions/37778472
复制相似问题