简体   繁体   中英

How can I get Lexer and Parser with ANTLR for C#?

Seems ANTLR support C# language but I dont know how I can generate related class.

I searched and saw exists an Extention for Visual Studio but I does not support 2015

so How I can generate Lexer and Parser for C# with ANTLR manually ?

The VS extension mainly serves for syntax highlighting and editor niceties. It's quite useful but you can still live without it (IIRC a change in VS2015 prevents a compatible release).

What you should do is use the Antlr4 NuGet package , which will automate the generation of parsers. It will run ANTLR at compile-time.

If you do have the VS extension (in VS2013 for instance), just add a new ANTLR grammar file to your project and you're done.

But if you don't have the extension, you'll have to set up the project manually. Here are the steps to make it work:

  • Install the NuGet package:

NuGet安装

  • Add a new text file to the project, name it with a .g4 extension

新文本文件

  • Save, and then unload the project from the project's context menu in the solution explorer:

上下文菜单

  • Reload it:

在此输入图像描述

  • Select your .g4 file in the solution explorer, go to the Properties window, and set the Build Action to Antlr4 :

建立行动

  • Edit your file, for instance:

     grammar MyLanguage; compileUnit: 'Hello' EOF; 
  • Go to File -> Advanced Save Options and choose UTF8 without signature or the ISO-8859-1 encoding (ANTLR just doesn't handle UTF8 with BOM):

编码

  • Build your project, your new classes will be available

  • You can now write some code:

     var lexer = new MyLanguageLexer(new AntlrInputStream("Hello")); 

No need for integration with visual studio.

Download the jar file here: http://www.antlr.org/download/antlr-runtime-4.5.1.jar

Save it to C:\\Test

Add the jar to your classpath:

Using System Properties dialog > Environment variables > Create or append to CLASSPATH variable

In the variable, put C:\\Test\\antlr-runtime-4.5.1.jar If values already exist for this variable, insert a ; before your new entry

Copy in your grammar file to C:\\Test

Go to the command line, navigate to C:\\Test

Create your 'outputdirectory' folder, and run this (remember to replace {outputdirectory} and {input}:

java org.antlr.v4.Tool -o -visitor -no-listener -Werror -o {outputdirectory} -Dlanguage=CSharp {input}.g4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM