4

For teaching purpose we are building a javascript step by step interpreter for (a subset of) C code.

Basically we have : int,float..., arrays, functions, for, while... no pointers. The javascript interpreter is done and allow us to explain how a boolean expression is evaluated, will show the variables stack...

For now, we are manually converting our C examples to some javascript that will run and build a stack of actions (affectation, function call...) that can later on be used to do the step by step stuff. Since we are limiting ourselves to a subset of C it's quite easy to do.

Now we would like to compile the C code to our javascript representation. All we need is a Abstract-syntax tree of the C code and the javascript generation is straightforward.

Do you know a good C-parser that could generate a such tree ? No need to be in javascript (but that would be perfect), any language is alright as this can be done offline.

I've looked at Emscripten ( https://github.com/kripken/emscripten ) but it's more a C=>javascript compiler and that's not what we want.

2 Answers 2

3

I've recently used Eli Bendersky's pycparser to mess with ASTs of C code. I think it'd work well for your purposes.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that's perfect. I can retrieve the line number of a definition with node.name.coord, but do you know if I can also get the position on the line ?
I don't think it exports it, but you should be able to get it with a few modifications.
0

I think that ANTLR has a full C parser.

To do your translation task, I suspect you will need full symbol table support; you have to know what the symbols mean. Here most "parsers" will fail you; they don't build a full symbol table. I think ANTLR does not, but I could be wrong.

Our DMS Software Reengineering Toolkit with its C Front End provides a full C arser, and builds complete symbol tables. (You may not need it for your application, but it includes a full C preprocessor, too). It also provide control flow, data flow, points-to-analysis and call graph construction, all of which can be useful in translating C to whatever your target virtual machine is.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.