c# - 由方法调用组成的简单 DSL 的 Lexer/Parser

标签 c# parsing compiler-construction dsl lexer

我希望为我们使用内部工具的简单 DSL 创建词法分析器和解析器。将有几个内置符号(这是正确的术语吗?),它们将采用 1 到 10 个参数。例如:

foo(bar1;bar2)

在运行时还会添加始终具有零参数的符号。示例:

testy1()

这些将被串在一起并从 CSV 文件中读取。组装线会像:

foo(bar1:bar2)testy1()

我很难在网上找到可以轻松解释像这样的词法分析和解析函数调用的资源。有人可以指出我的好方向或提供建议吗?

最佳答案

我用 PegJS 编写了一个小型解析器,它能够解析函数调用中的简单表达式。 PEG 避免了歧义,并且在这方面效果很好。

Start
  = Expr

/* Expressions */

Expr
  = FuncCall
  / Literal

RestExpr
  = _ ( "," / ":" ) _ e:Expr {
    return e;
  }

/* Function call */

FuncCall
  = func:Ident _ "(" _ x:Expr? xs:RestExpr* _ ")" {
    return {
      type: "FuncCall",
      func: func.value,
      params: x ? [x].concat(xs) : []
    };
  }

/* Literals */

Literal
  = Number
  / Ident

Number
  = val:[0-9]+ {
    return {
      type: "Number",
      value: parseInt(val.join(""))
    };
  }

/* Identifier */

Ident
  = x:IdentStart xs:IdentRest* {
  return {
    type: "Ident",
    value: [x].concat(xs).join("")
  };
}

IdentStart
  = [a-z_]i

IdentRest
  = [a-z0-9_]i
_
  = [ \s\t\r\n]*

您可以在这里测试解析器:http://pegjs.org/online

输入示例是 foo(1, bar(2), baz(3)),其中输出是:

{
   "type": "FuncCall",
   "func": "foo",
   "params": [
      {
         "type": "Number",
         "value": 1
      },
      {
         "type": "FuncCall",
         "func": "bar",
         "params": [
            {
               "type": "Number",
               "value": 2
            }
         ]
      },
      {
         "type": "FuncCall",
         "func": "baz",
         "params": [
            {
               "type": "Number",
               "value": 3
            }
         ]
      }
   ]
}

这显然不是最好的方法,但我相信 peg-sharp 可以用 C# 做得很好:https://code.google.com/p/peg-sharp/ .

关于c# - 由方法调用组成的简单 DSL 的 Lexer/Parser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31679855/

相关文章:

c# - 从 Enterprise Architect 模型中提取数据

java - 什么是 Java 中的综合字段?

c++ - Debug模式下的内存泄漏

c# - 为什么重载方法在 ref only CLS compliant 方面有所不同

c# - WinRT中ListView的item插入动画

C#/.Net 变更日志

iphone - 如何为iPhone解析文件?我应该使用NSScanner吗?

java - 将字符串转换为 MAILTO 的 HTML 就绪文本 : URL

c - 我应该明确定义我的枚举常量的值吗

c# - ListView.ItemContainerStyle IsSelected 属性似乎不影响 WinRT 上的选择