JavaCC for C++
© 2004 Jean-Marc Vanel

e-mail: Send your comments - My home page

Last update:  11 avr 2004

Introduction

Ultimately I want to make a C++ --> Java translator, because I'm not happy with the code of Alma .

Parsing C++ (only)

I found that the C++ grammar hyperlinked from the JavaCC site was not enough, some classes where missing. So, after some googling, I found what I needed in the (excellent) PDM code checker (that has not officially C++ features!).

Here is what I did :
# put the necessary sources from PMD 1.7 in parse-cpp/ == $d
$ cd /home/jmv/src/pmd-1.7
$ cd src/net/sourceforge/pmd/cpd/cppast
$ export d=/home/jmv/src/javacc-3.2/parse-cpp
$ mkdir $d
$ cp ClassScope.java Declaration.java Scope.java SymtabManager.java $d
$ cp /home/jmv/src/pmd-1.7/etc/grammar/cpp.jj $d

# generate code with JJTree and JavaCC, then compile
$ cd $d
$ export PATH=$PATH:/home/jmv/src/javacc-3.2/bin
$ jjtree cpp.jj
$ javacc cpp.jj.jj
$ gvim CPPParser.java
$ grep -n jmv CPPParser.java
58: static String GetFullyScopedName() throws RuntimeException // jmv ParseException
93: static boolean IsCtor() throws RuntimeException // jmv ParseException
$ mkdir classes
$ jikes -d classes *.java

# test one C++ file from OOQP, a numerical library; note that all includes must be concatenated in the right order:
$ cd /home/jmv/contrats/mullon/OOQP
$ cat \
> src/Abstract/Solver.h \
> src/Abstract/Variables.h src/Abstract/Residuals.h src/Abstract/LinearSystem.h src/Abstract/Status.h src/Abstract/Data.h src/Abstract/ProblemFormulation.h \
> src/QpSolvers/GondzioSolver.h \
> src/QpSolvers/GondzioSolver.C > GondzioSolver.inline.C

$ java -cp classes net/sourceforge/pmd/cpd/cppast/CPPParser \
/home/jmv/contrats/mullon/OOQP/GondzioSolver.inline.C
C++ Parser Version 0.1: Reading from file /home/jmv/contrats/mullon/OOQP/GondzioSolver.inline.C . . .
C++ Parser Version 0.1: Program parsed successfully.

Generating an AST

Next step is to understand the AST (Abstract Syntatic Tree) API of JJTree, and output some Java statements.
After that I can also generate some graph views of the code, using e.g. JGraph .

Click here to get to the JJTree documentation.