A calculator Android app I’m writing needed an expression parser, so I researched how to build one. I started by reading a bit of Google’s Android Open Source Project Calculator source to get some ideas.
That project uses classes from Mihai Preda and Carlo Teubner’s open source calculator, which contains a hand-built parser for infix arithmetic expressions. After some false starts building my own parser, I decided to take the advice of several wise compiler builders: Use a compiler-compiler, because a hand-built parser for even a simple language can eventually grow into an unmanageable and buggy mess.
Probably the most well-known compiler-compiler is Linux Yacc: Yet Another Compiler Compiler. Yacc reads a specification for a custom computer language and generates C code that parses instances of that language and either generates output code (a compiler) or executes what its input specifies (an interpreter).
If you’re not familiar with compiler-compilers (compiler-generators) I recommend a Yacc/Lex tutorial such as Tom Neimann’s introduction to Yacc and Lex. That tutorial will give you the background necessary to make sense of any modern compiler-compiler, including JavaCC. There are also JavaCC tutorials on the web.
So I searched for a compiler-complier to use. My requirements:
- Generates Java code, so I can add it to my Android project.
- Ideally, Android Studio compatible, so I can put the compiler specification directly into my calculator project.
- Open Source for many reasons, one of which is that I can debug and fix the problems I run into.
- (optional) Able to integrate with a hand-built token generator, because my calculator already stores the input expression as a sequence of tokens rather than a sequence of characters.
I quickly settled on the popular Java Compiler-Compiler JavaCC, and a Gradle plugin for JavaCC which satisfies all my requirements. The beauty of the Gradle plugin is that the generation of the parser becomes part of the Android Studio build, so making changes to the grammar and testing the result is easy.
I’ve written a page that summarizes what I’ve learned: Integrating JavaCC with Android Studio. Enjoy!