This describes the steps involved in the implementation and use of an aParse parser.
| Write Grammar | Use the ABNF metalanguage to define the syntax of a protocol. |
| Generate Parser | Use aParse to generate the parser source code. |
| Test Parser | Use the parser to parse instances of the protocol and verify whether the grammar correctly describes the protocol. |
| Produce Visitor | Produce a visitor for instances of the protocol that performs the desired conversion or translation. |
| Employ Parser | Make use of the parser and visitor in a program. |
Write Grammar
Using the ABNF metalanguage, define the syntax of a protocol in a text file.
For example, the definition of a 24 hour clock in clock.abnf.
Generate Parser
Use aParse to generate the Clock parser source code.
java -cp aparse.jar com.parse2.aparse.Parser clock.abnf
Any syntax errors or inconsistencies in the grammar will be highlighted at this point. For example, if the "Separator" rule was not declared then aParse would generate the following errors.
Once the grammar compiles cleanly, six Java source files will have been produced.
| Parser.java | The parser of instances of Clock. |
| Rule.java | The abstract Java class that represents a rule. |
| Visitor.java | The Java interface that must be implemented by classes that want to traverse a Parser generated rule tree. |
| Displayer.java | A Java class that implements the Visitor interface and displays the terminal values of a Parser generated rule tree. |
| XmlDisplayer.java | A Java class that implements the Visitor interface and displays the contents of a Parser generated parse tree in XML. |
| Exception.java | The Java exception that is raised by the Parser when it attempts to parse an instance of Clock that does not conform to the specified grammar. |
Compile these source files.
javac *.java
Test Parser
To test the Parser, create a file, for example clock.txt, containing an instance of Clock.
15:26:37
Parse it and display the contents of the parse tree using the Parser and Displayer.
java Parser -visitor Displayer -file clock.txt
Alternatively, parse it and display the contents of the parse tree in XML using the XmlDisplayer visitor.
java Parser -visitor XmlDisplayer -file clock.txt
See Clock Parser for a working example.
Produce Visitor
Rather than use the following automatically generated XmlDisplayer it is possible to produce and use an alternative Visitor.
For example, the following Clock2Xml visitor is identical to the XmlDisplayer except it does not output the ":" separators.
See Clock Parser for a working example.
Similarly, the following Clock24To12 visitor converts the 24 hour clock values to their 12 hour clock equivalents.
See Clock Parser for a working example.
Employ Parser
Having verified the operation of the parser and visitor, they may be built into a program. The following code segment shows how the Parser and Clock24To12 visitor might be used to parse and process the contents of the file clock.txt.