Citron Parser Generator
Citron is an LALR parser generator for Swift. For a given input grammar, Citron creates a reentrant type-safe parser in Swift.
Citron encapsulates parsing-related data and functions into a parser class, and uses protocols and generics to provide a Swifty interface for parsing and lexing.
We can have different instances of a Citron-generated parser class in the same program, and the different instances can be used concurrently. We can also have different Citron-generated parser classes in the same program, and instances of those classes can be used concurrently.
However, we should not access the same instance of a parser class from multiple threads at the same time (i.e. Citron-generated parsers are not thread-safe).
The Citron-generated code enforces type checking on the inputs and outputs of every code block in the grammar file, ensuring that bugs are caught at build time rather than at runtime.
Human-grade (New in v2.0)
Human-grade parsers that are meant to be used directly by humans (rather than by another software) should be able to recover from errors intelligently so that multiple meaningful errors can be generated at one pass. Citron assists you in generating such parsers.
Citron is adapted from the Lemon parser generator by Richard Hipp, the creator of SQLite. Lemon is used to generate the parser that parses SQL statements in SQLite.
Using Citron requires Swift 4. The parser has no dependancies other than the Swift Standard Library. The lexer is dependant on Foundation for the use of regular expressions.
To make use of Citron, we should:
Create a grammar file
The grammar file contains the input grammar for which we’d like Citron to create a parser. It contains grammar rules, code blocks associated with the rules and Citron directives.
See The Citron Grammar File for information on how to write a grammar file.
Generate the parser
To generate a parser, we should compile Citron and then run Citron on the grammar file.
See Generating the parser for the commands that can accomplish this.
Use the parser
We can then use the parser class in our code, and provide it with inputs. We can optionally use Citron’s lexer to generate the inputs for the parser.
See The Parsing Interface for information on how we can use the parser in our code.
A few examples of how Citron is used for parsing can be found in the “examples” folder in the project repository.
- Introducing Citron: A quick overview of Citron and how to use it