ANTLR简介

ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files. It's widely used to build languages, tools, and frameworks. From a grammar, ANTLR generates a parser that can build parse trees and also generates a listener interface (or visitor) that makes it easy to respond to the recognition of phrases of interest.

ANTLR(ANother Tool for Language Recognition)是一个强大的生成Parser的工具,用来读取,处理,执行或者翻译结构文本或二进制文件。ANTLR将从grammar生成一个parser,可以构建parse tree 并且生成一个监听接口(或者visitor),并使你更简单的感受到短语识别的乐趣。

本例简介

本例将使用ANTLR生成CSharp parser代码,对减乘除数学表达式进行Parse并执行。源码直接下载吧,点这里

准备环境

1.ANTLR是一个JAVA程序,所以需要JAVA环境,本例使用的是java version "1.8.0_181"。

2.下载ANTLR https://www.antlr.org/download.html 本例使用Complete ANTLR 4.9.1 Java binaries jar

准备语法文件Simple.g4

grammar Simple;

calc: expr EOF;

expr
:BR_OPEN expr BR_CLOSE
|expr TIMES expr
|expr DIV expr
|expr PLUS expr
|expr MINUS expr
|number
; number: NUMBER; PLUS: 'plus' | '+';
MINUS: 'minus' | '-';
TIMES: 'times' | '*';
DIV: 'div' | '/';
![](https://img2020.cnblogs.com/blog/803166/202102/803166-20210227232628613-1602253693.jpg) NUMBER: '-'? [0-9]+;
BR_OPEN: '(';
BR_CLOSE: ')'; WS: [ \t\r\n]+ -> skip;

生成CSharp代码

命令行执行

java -jar antlr-4.9.1-complete.jar -Dlanguage=CSharp Simple.g4

将生成文件添加至CSharp Project

CSharp Project添加ANTLR runtime引用

Install-Package Antlr4.Runtime.Standard

执行读取到的数学表达式

        private static int visit(SimpleParser.ExprContext context)
{
if (context.number() != null)
{ //Just a number
return int.Parse(context.number().GetText());
}
else if (context.BR_CLOSE() != null)
{ //Expression between brackets
return visit(context.expr(0));
}
else if (context.TIMES() != null)
{ //Expression * expression
return visit(context.expr(0)) * visit(context.expr(1));
}
else if (context.DIV() != null)
{ //Expression / expression
return visit(context.expr(0)) / visit(context.expr(1));
}
else if (context.PLUS() != null)
{ //Expression + expression
return visit(context.expr(0)) + visit(context.expr(1));
}
else if (context.MINUS() != null)
{ //Expression - expression
return visit(context.expr(0)) - visit(context.expr(1));
}
else
{
throw new Exception();
}
}

读入输入测试

            var input = "2 * 3";
AntlrInputStream inputStream = new AntlrInputStream(input); SimpleLexer lexer = new SimpleLexer(inputStream);
CommonTokenStream commonTokenStream = new CommonTokenStream(lexer);
SimpleParser parser = new SimpleParser(commonTokenStream); var result = visit(parser.expr());
Console.WriteLine($"input:{input},output:{result}");

尾声

本例简单介绍在CSharp中如何使用ANTLR生成一个Parser,感受了一波短语识别的乐趣,You feel me? 后续ANTLR详细的玩法再给大家分享。

Reference

C# target for ANTLR 4

Antlr is Awesome

CSharp使用ANTLR4生成简单计算Parser的更多相关文章

  1. Pytorch基础——使用 RNN 生成简单序列

    一.介绍 内容 使用 RNN 进行序列预测 今天我们就从一个基本的使用 RNN 生成简单序列的例子中,来窥探神经网络生成符号序列的秘密. 我们首先让神经网络模型学习形如 0^n 1^n 形式的上下文无 ...

  2. 学习笔记:利用GDI+生成简单的验证码图片

    学习笔记:利用GDI+生成简单的验证码图片 /// <summary> /// 单击图片时切换图片 /// </summary> /// <param name=&quo ...

  3. 2018-02-18 Antlr4实现简单语言之条件语句

    本系列之前的文章: Antlr4的分析错误处理 Antlr4实现数学四则运算 Antlr4添加中文变量赋求值,括号,各种问题 Antlr4: 修改语法规则更接近普通BNF格式 Antlr4实现简单语言 ...

  4. python应用:生成简单二维码

    概述 \(\quad\)第一篇python的应用就打算写一写用python生成简单的二维码啦.因为二维码在日常生活中越来越常用了,部分博客也用二维码来用作打赏的工具.但是要提醒大家的是,千万不要乱扫街 ...

  5. 通过微软的HTML Help Workshop 利用.html文件 生成简单的chm帮助类的文件

    1.下载并安装Microsoft HTML Help Workshop 下载链接:http://www.microsoft.com/en-us/download/details.aspx?id=211 ...

  6. 使用Swagger生成简单接口文档

    使用swagger通过简单的配置可以生成简单的接口文档: 依赖包: // Swagger2 compile 'io.springfox:springfox-swagger2:2.8.0' compil ...

  7. java 生成简单word(利用Itext工具),生成简单Excel,以及下载笔记

    1.java 生成简单word(包含图片表格) pom中加入itext 相关依赖 <dependency> <groupId>com.lowagie</groupId&g ...

  8. SDUT OJ 2616 简单计算

    简单计算 Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^ 题目描述 某天,XX 给YY 出了一道题,题目是: 给出n 个十进制的数,找出这n ...

  9. Python简单计算数组元素平均值的方法示例

    Python简单计算数组元素平均值的方法示例 本文实例讲述了Python简单计算数组元素平均值的方法.分享给大家供大家参考,具体如下: Python 环境:Python 2.7.12 x64 IDE ...

随机推荐

  1. 牛客15334 Easygoing Single Tune Circulation(后缀自动机+字典树)

    传送门:Easygoing Single Tune Circulation 题意 给定n个字符串 s[i],再给出m个查询的字符串 t[i],问 t[i] 是否为某个 s[i] 循环无限次的子串. 题 ...

  2. codeforces #345 (Div. 1) D. Zip-line (线段树+最长上升子序列)

    Vasya has decided to build a zip-line on trees of a nearby forest. He wants the line to be as long a ...

  3. poj1821——Fence

    题意: 一个栅栏一共有n(从1--n)个木板,我们找k个工人去粉刷它,li表示每个人有限制粉刷木板数量,pi表示粉刷一个木板得到的钱,si表示他开始在那个木板前面 如果一个工人要粉刷,那么他必须粉刷s ...

  4. UVALive 7146

    Long long ago there is a strong tribe living on the earth. They always have wars and eonquer others. ...

  5. 大数据开发-Spark Join原理详解

    数据分析中将两个数据集进行 Join 操作是很常见的场景.在 Spark 的物理计划阶段,Spark 的 Join Selection 类会根 据 Join hints 策略.Join 表的大小. J ...

  6. bzoj5312 冒险(吉司机线段树)题解

    题意: 已知\(n\)个数字,进行以下操作: \(1.\)区间\([L,R]\) 按位与\(x\) \(2.\)区间\([L,R]\) 按位或\(x\) \(3.\)区间\([L,R]\) 询问最大值 ...

  7. Bootstrap巨幕

    这是一个轻量.灵活的组件,它能延伸至整个浏览器视口来展示网站上的关键内容. jumbotron修饰 <div class="jumbotron"> <h1> ...

  8. macOS & pbcopy

    macOS & pbcopy copy from command line pbcopy $ whoami | pbcopy # xgqfrms-mbp $ echo "hello, ...

  9. Markdown & Static Site Generator

    Markdown & Static Site Generator https://www.gitbook.com/ https://vuepress.vuejs.org/ https://ww ...

  10. flutter 使用Android studio编辑kt插件

    使用android studio打开/example/android 文件即可