Version 1.0
Copyright © 2022 Lowell D. Thomas
Python APG
 … an ABNF Parser Generator
A Quick Start Parser from the pip Installation

The Project Structure

Throughout this example we will assume the project structure:

|my_project_folder
|---|my_project
    |---__init__.py
    |---dynamic.py
    |---grammar.abnf
    |---static.py

All commands will be executed from the my_project_folder directory. The content of the files will be presented and explained as we go.

Installation

Make sure apg-py is installed and working.

> pip install apg-py
> apg-py --version

(Note that the stand-alone generator, apg-py, comes as a CLI application with the pip installation.)

A Dynamic Generator with Parsing

In this example, the ABNF grammar and the generation of the grammar object will be done dynamically within the parser program. The dynamic.py file should look like this.

from apg_py.lib import utilities as util
from apg_py.lib.parser import Parser
from apg_py.api.api import Api
abnf = 'S = "a" S / "y"\n'
input = 'aaay'
api = Api()
grammar = api.generate(abnf)
if(api.errors):
    print('\n1) Grammar Errors')
    print(api.display_errors())
    exit()
parser = Parser(grammar)
result = parser.parse(utils.string_to_tuple(input))
print('\n1) Parser Result')
print(result)

Execute the command:

> python3 my_project/dynamic.py

You should see the results of a successful parse.

1) Parser Result
            success: True
              state: 101
              STATE: MATCH
       input_length: 4
          sub_begin: 0
            sub_end: 4
         sub_length: 4
      phrase_length: 4
  max_phrase_length: 4
          node_hits: 17
     max_tree_depth: 13

A Parsing from a Pre-Generated Grammar

Let's now do the same project except that we will generate the grammar object in advance and import it into the parser. The ABNF syntax is now in the file grammar.abnf:

S = "a" S / "y"

(Make sure the line ends with a line feed.)

Now execute the command:

> apg-py --input my_project/grammar.abnf

You should see the output:

grammar object written to file my_project/grammar.py

The static.py file should look like,

from apg_py.lib import utilities as utils
from apg_py.lib.parser import Parser
import grammar
print('The ABNF Syntax')
print(grammar.to_string())
input = 'aaay'
parser = Parser(grammar)
result = parser.parse(utils.string_to_tuple(input))
print('\n1) Parser Result')
print(result)

Now execute the static parser with,

> python3 my_project/static.py

The output should look like,

The ABNF Syntax
S = "a" S / "y"

1. Parser Result
   success: True
   state: 101
   STATE: MATCH
   input_length: 4
   sub_begin: 0
   sub_end: 4
   sub_length: 4
   phrase_length: 4
   max_phrase_length: 4
   node_hits: 17
   max_tree_depth: 13
      
Python APG, Version 1.0, is licensed under the 2-Clause BSD License,
an Open Source Initiative Approved License.