【问题标题】:fslex learning: Lexer not advancingfslex 学习:Lexer 没有进步
【发布时间】:2014-08-29 13:51:50
【问题描述】:

我目前正在学习基于解析一个简单计算的词法分析和解析(基于 F# 工具集),我被困在我的词法分析器没有推进以消耗整个字符串:

let lexeme = LexBuffer<_>.LexemeString
// ...
rule test = parse
  | digit+  { Console.WriteLine("1_" + (lexeme lexbuf)); test lexbuf; }
  | '+'     { Console.WriteLine("2_" + (lexeme lexbuf)); test lexbuf; }
  | '-'     { Console.WriteLine("3_" + (lexeme lexbuf)); test lexbuf; }
  | '*'     { Console.WriteLine("4_" + (lexeme lexbuf)); test lexbuf; }
  | '/'     { Console.WriteLine("5_" + (lexeme lexbuf)); test lexbuf; }
  | '('     { Console.WriteLine("6_" + (lexeme lexbuf)); test lexbuf; }
  | ')'     { Console.WriteLine("7_" + (lexeme lexbuf)); test lexbuf; }
  | eof     { () }

注意这里例如最后的'test lexbuf' 是我必须写的,以确保我提供的整个字符串都被使用

由于我在实际实现中没有这样做我只是阅读例如第一个数字,这就是我得到的全部

rule calculator = parse
  | digit+  { NUMBER (Convert.ToInt32(lexeme lexbuf)) }
  | '+'     { PLUS }
  | '-'     { MINUS }
  | '*'     { TIMES }
  | '/'     { DIV }
  | '('     { LPAREN }
  | ')'     { RPAREN }
  | eof     { EOF }

我见过许多结构非常相似的例子。我错过了什么。

【问题讨论】:

    标签: f# lexer fslex


    【解决方案1】:

    我猜你的文本输入中可能有空格和/或换行符,因此需要规则来处理这些(即通过推进 lexbuf 而不是生成令牌来丢弃它们)。比如:

    let whitespace = [' ' '\t' ]
    let newline = ('\n' | '\r' '\n')
    
    ...
    
    | whitespace { calculator lexbuf }
    | newline    { lexbuf.EndPos <- lexbuf.EndPos.NextLine; calculator lexbuf }
    

    【讨论】:

      【解决方案2】:

      问题在于,您根本无法期望词法分析器自行推进。对我来说,将其视为流有助于理解正在发生的事情。

      推进只能与解析器结合使用。解析器将不断要求词法分析器返回标记。

      【讨论】:

        猜你喜欢
        • 2012-07-06
        • 2021-03-07
        • 2018-10-25
        • 2020-02-11
        • 2017-03-02
        • 2016-02-13
        • 2020-07-09
        • 2020-07-17
        • 1970-01-01
        相关资源
        最近更新 更多