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

随声附和 提交于 2019-12-12 08:55:23

问题


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 ?


回答1:


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



回答2:


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:

  • 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"));
    


来源:https://stackoverflow.com/questions/33273414/how-can-i-get-lexer-and-parser-with-antlr-for-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!