xoofx / Antlr4Ast

Antlr4Ast is a .NET library that provides a parser and abstract syntax tree (AST) for ANTLR4/g4 files.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Antlr4Ast ci Coverage Status NuGet

Antlr4Ast is a .NET library that provides a parser and abstract syntax tree (AST) for ANTLR4/g4 files.

This can be useful if you are looking for building code generation tools from ANTLR4/g4 files.

Features

  • Allow to parse and merge ANTLR4/g4 files to a simple AST.
    • Should support almost all grammar features of ANTLR4/g4 except actions.
  • Provides precise source location for most of the AST elements.
  • Provides access to comments attached to syntax nodes.
  • Provides visitor and transform.
  • Library with nullable annotations.
  • Compatible with netstandard2.0

Limitations

As this library is mainly for codegen scenarios, it does not preserve whitespaces or the position of some comments within elements. There is no plan to support high fidelity roundtrip ANTLR4 parser.

Usage

The entry point for parsing an ANTLR4/g4 grammar is to use the Grammar.Parse methods:

var input = @"grammar MyGrammar;
// Parser rules starting here!
expr_a_plus_b
    : TOKEN_A '+' TOKEN_B
    ;
// Lexer rules starting here!
TOKEN_A: 'a';
TOKEN_B: 'b';
";
// Parse the grammar
var grammar = Grammar.Parse(input);
// Print the grammar
Console.WriteLine(
    grammar.ToString(
        new AntlrFormattingOptions() { 
                    MultiLineWithComments = true 
        }
    )
);

will print the following:

grammar MyGrammar;

// Parser rules starting here!
expr_a_plus_b
  : TOKEN_A '+' TOKEN_B
  ;

// Lexer rules starting here!
TOKEN_A
  : 'a'
  ;

TOKEN_B
  : 'b'
  ;

Documentation

You will find more details about how to use Antlr4Ast in this user guide.

License

This software is released under the BSD-Clause 2 license.

Author

Alexandre Mutel aka xoofx.

About

Antlr4Ast is a .NET library that provides a parser and abstract syntax tree (AST) for ANTLR4/g4 files.

License:BSD 2-Clause "Simplified" License


Languages

Language:C# 85.4%Language:ANTLR 14.6%