Embedding a Dynamic Language in C++
There are a number of C/C++ interpreters that support a subset of C++, but the new C++Script language by Calum Grant, does something a little different. It enhances C++ with a garbage collector, closures, and dynamic typing, while using existing C++ compilers.
There are a number of interpreters that support a subset of C++:
- Ch - described in this DDJ article
These languages for the most part try to support as much of C and/or C++ in a dynamically interpreted environment. In contrast the language C++Script, aims to provide features found in dynamic languages in C++, and supporting compilation in any C++ compiler. Looked at another way, it is just a library, but once there exist a formal semantics and interpreter for C++Script it will be a viable scripting language.
For a long time, I was scornful of so-called "dynamic languages" like Python, and JavaScript, because as a hard-core C++ coder, I knew everything they did could be done in C++ and more efficiently. The only problem was that in practice, who really has time to implement dynamic language facilities in C++? In the real world you end up using whatever the STL and Boost gives you, maybe you write a few wrappers, and you get your job done.
I played around with dynamic types (like boost::any my own cdiggins::any) but I never really had the time to do anything further with it. It is so nice to see that someone else has taken the job to do it properly.
The idea of working with a restricted subset of C++ which uses dynamic typing appeals to me for the following reasons:
- C++ becomes a more viable language to teach to beginners
- Prototyping in C++ becomes more effective (we can refine a proof of concept that was prototyped in C++Script by incrementally adding features in C++)
- We gain the advantages of many functional programming languages like closures, garbage collection, memory safety, and reflection
The C++Script language is a bit like JavaScript:
#include <br /> <br />var create_a_tree(var species, var height) // Constructor function<br />{<br /> var tree = object(); <br /> tree["species"] = species;<br /> tree["height"] = height;<br /> return tree;<br />}var script_main(var args)<br />{<br /> var oak = create_a_tree("oak", 12.2);<br /> var maple = create_a_tree("maple", 15.0);<br /> writeln( "The height of the oak is " + oak["height"] );<br /> return 0;<br />}I think that there is a lot of potential in this kind of language. If the syntax and semantics become more formally pinned down, then perhaps I might write an interpreter or compiler for the language, so that it can be used outside of C++.
I am also thinking that it might be interesting to write some meta-programming facilities (e.g. reflection, AOP) for this language. It might turn out that writing code in C++Script could be a really good idea. You know that there will be C++ compilers for virtually every platform for a long time to come.

