Is it possible that a string variable can be parsed as an actual line of code in C++? For example, can this string, "x=0", be parsed as actual code and set the value of x (some random variable in the program) to zero? What I plan to do with this is that I want to make a simple plotter in C++. The user enters the function (The function will be in terms of x and y and will have the value zero) to plot as a string (like 2*y+x), which then will be converted to a code object and then evaluated accordingly using a loop.
Because C++ is a compiled and linked language it is not suitable for on-the-fly evaluation.
But I've achieved something similar to your aims in the past with C++ by embedding a Python interpretter to evaluate Python code as strings on the fly and pass the results to the C++ code.
Some other popular scripting languages that can be embedded in a C++ program are Lua and Squirrel.
In Java I've done the same by embedding a Groovy interpretter.
You need to integrate the scripting language interpretter into your code by "embedding" it and then pass values from the scripting language code to your C++ code by a process of "marshaling"
If you really want C++ syntax that can be interpretted, it is theoretically possible to develop a dynamic parser and interpretter for a subset of the language, but C++ is a complex language and such a task would be an enormous undertaking fraught with difficulty and essentially a case of using the wrong tool for the job.
The short answer is "No". You can't compile C/C++ "on the fly" like that, as it's a compiled language, not an interpreted one.
But here's an idea: you could embed a JavaScript interpreter, using the SpiderMonkey API, which can interpret all your example code snippets, as JavaScript syntax is very similar to C/C++ in this regard.
The short answer is "Yes". Compiling C++ on the fly works just fine using a C++ JIT. From llvm.org
A Just-In-Time (JIT) code generation system, which currently supports X86, X86-64, ARM, AArch64, Mips, SystemZ, PowerPC, and PowerPC-64.
The assumption is that you're willing to link most of a compiler into your program in order to achieve this. With concerted effort you should be able to write "eval" on top of the existing API.
Related
I've started long ago to work on a dynamic graph visualizer, editor and algorithm testing platform (graphs with nodes and arcs, not the other kinds).
For the algorithm testing platform i need to let the user write a script or call a script from a file, which will interact with the graph currently loaded. The visualizer would do things like light up nodes while they're being visited by the script algorithm, adding some artificial delay, in order to visualize the algorithm navigating and doing stuff.
Scripts would also be secondly used to add third party features that i could either make available as pre-existing scripts in the program folder OR just integrate inside the program in c++ once they're tested and working.
All my searches for an interpreter to embed in my program sent me to lua;
then i started handwriting my own recursive descent parser for my own C-like syntax scripting language (which i planned to use a subset of C++ grammar so that any code written in my scripting language can be copy-pasted in any C++ code.
It was an interesting crazy idea which i don't regret at all, I have scopes, functions, cycles, gotos, typesafe variables, expressions.
But now that i'm approaching the addition of classes, class methods, inheritance (some default classes would be necessary to interface scripts to the program), i realized it's going to take A LOT of time and effort. A bit too much for a personal project of an ungraduated student with exams to study for… but still i whish to complete this project.
The self-imposed requirement of the scripts being 100% compatible with C++ was all but necessary, it would have been just a little nice extra thing, which i can do without.
Now the question is, is there an alternative to lua with a c-like syntax that supports all i've already done plus classes and inheritance? (being able to add custom "classes" that interface scripts to the program is mandatory)
(i can't assume the user to have a full c++ compiler installed so i cant just compile their "script" at runtime as a dll to load and call it, although i whish i could)
Just-in-time compilation of C++
Parsing C++ is hard. Heck, parsing C is hard. It's difficult to get it right, and there are a lot of edge cases. Thankfully, there are a few libraries out there which can take code and even compile it for you.
libclang
libclang provides a lot of facilities for parsing c++. It's a good, clean library, and it'll parse anything the clang compiler itself will parse. This article here is a good starter
libclang provides a JIT compilation tool that allows you to write and compile C++ at runtime. See this blog post here for a overview of what it does and how to use it. It's very general, very powerful, and user-written code should be fast.
GCC also provides a library called libgccjit for just-in-time compilation during the runtime of a program. libgccjit is a C library, but there's also a C++ wrapper provided by the library maintainers. It can compile abstract syntax trees and link them at runtime, although it's still in Alpha mode.
cppast
If you don't want to use libclang, there's also a library under development called cppast, which is a C++ parser which will give you an abstract syntax tree representation of your c++ code. Unfortunately, it won't parse function bodies.
Other tools
If anyone knows any other libraries for compiling or interpreting C++ at runtime, I encourage them to update this post, or comment them so I can update it!
Here is something that lets you embed a C-like scripting language in your application (and a bunch of other cool things):
http://chaiscript.com/
There is lots of documentation:
https://codedocs.xyz/ChaiScript/ChaiScript/
So Python has a sort of command line thing, and so does Linux bash (obviously), and I'm sure other programming languages do, but does C++? If not, why do C++ scripts have to be compiled first and then run?
If not, why do C++ scripts have to be compiled first and then run?
C++ code does not need to be compiled to be run. There are interpreters.
The reason most of us prefer compiled C++ is that the resulting executable is 'faster'.
Interpreted computer languages can do extra things to achieve similar performance (i.e. just-in-time compile), but generally, 'scripts' are not in the same league of fast.
Some developers think not having to edit, compile, link is a good thing ... just type in code and see what it does.
Anyway, the answer is, there is no reason that C++ "has to" be compiled. It is just the preferred tool for most C++ developers.
Should you want to try out C++ interpreters, search the net for CINT, Ch, and others.
Indeed there are interpreters for C++ that do what you want. Check out
Cling.
To the commenters saying C++ can't have interpreters because it's a compiled language: yes, typically you use a compiler with C++. But that doesn't mean it's impossible to write an interpreter for it.
There is no command lines to run C++ instructions. It is compiled first and then target machine code generated (intermediate obj code, and linked) to run.
The reason is, It is matter of language design for various considerations like performance, error recovery etc. Compiled code generate target machine code directly and run faster than interpreted languages. Compiled code take program as whole and generate the target machine code vs interpreted code take few instruction at once. Interpreted language require intermediate programs to target the final machine code, so it may be slow.
In nutshell, it is language design evolution. When first computers appeared programming is done directly in machine language. Those programs run instruction by instruction. Later high level language appeared, where machine language is abstracted with human friendly instructions and compilers designed to generate equivalent machine code.
Later Computer program design advanced, and CPU instruction cycle speed increased, we could afford intermediate interpreters for writing safer programs.
Choice is wider now, earlier performance centric apps demanded compiled code. Now even interpreted code equally faster in common use cases.
While there are interpreters for C++-like languages, that is not really the point; C++ is a compiled language that is translated to native machine code. Conversely scripting languages are (typically) interpreted (albeit that there are also compilers for scripting languages to translate them to native code).
C++ is a systems-level capable language. You have to ask yourself - if all languages ran in a shell with a command line and were interpreted, what language is that shell or interpreter, or even the OS they are running on written in?
Ultimately you need a systems level language, and those are most often C, C++ and assembler.
Moreover because it is translated to machine level code at compilation, that code runs directly and stand-alone without the presence of any interpreter, and consequently can be simpler to deploy, and will execute faster.
My company develops a API for engineering programs. It is developed in C++ but we create wrappers to it for the following languages:
a proprietary language that resembles VB
MATLAB
and Python.
Currently the documentation is generated by a bunch of scripts and it is starting to get time consuming to keep it 100%. I was wondering if there is a way to get doxygen/sphinx or another program to generate the documentation for C/C++, VB and MATLAB in one go. The Python part is done by SWIG. Currently the output is something like:
NameOfFunction
VB:
Function NameOfFunction(ByVal a As Long , ByRef b() As Long, ByVal c As Long) As Long
MATLAB:
value = NameOfFunction(a,b(),c)
C/C++:
value *NameOfFunction(objtype1 *a, objecttype2 *b[], int c)
+Description
+Examples
doxygen supports multiple languages,
to use this on multiple projects or folders and languages you just point doxygen to every folder you want checked in the config.
My favorite programming language is X. Can I still use doxygen?
No, not as such; doxygen needs to understand the structure of what it reads. If you don't mind spending some time on it, there are several options:
Is language X supported?
If the grammar of X is close to C or C++, then it is probably not too
hard to tweak src/scanner.l a bit so the language is supported. This
is done for all other languages directly supported by doxygen (i.e.
Java, IDL, C#, PHP). If the grammar of X is somewhat different than
you can write an input filter that translates X into something similar
enough to C/C++ for doxygen to understand (this approach is taken for
VB, Object Pascal, and Javascript, see
http://www.doxygen.nl/download.html#helpers). If the
grammar is completely different one could write a parser for X and
write a backend that produces a similar syntax tree as is done by
src/scanner.l (and also by src/tagreader.cpp while reading tag files).
however since your using a VB like proprietary , it might pick this language up if you simply just change the file extensions to that of .vb
here is how to use it with matlab
python and c++ are already supported
have a look at the FAQ page
I was wondering if there is a way to get doxygen/sphinx or another program to generate the documentation for c/c++, VB and matlab on one go.
The Zeus editor has a doxygen feature that allows you to create doxygen documentation for all items in the Zeus workspace.
The Doxygen site has a page with links to 3rd-party helpers for various languages, that you may be able to adapt:
http://www.doxygen.nl/helpers.html
VB and MatLab filters are mentioned there.
I would like to tak emy existing AS3 or Flex project and compile it to run on native C++ code. Is there a way to do this? What sort of solutions exist? I do not want to change my AS3 code.
AS3 is a framework operating on prebuilt libraries you would have to replace somehow in your "translated" code. For example, what would you imagine the native code to do, when you do new Sprite()?
Haxe doesn't try to find a replacement. It takes different approach in that it lets you reuse bits of the code that would translate easily, but those that don't translate are marked as specific to certain environment. There is, however, an effort in Haxe to come up with API similar to those of Flash display list by using NME graphic engine.
Given your example with the iOS compiler - it, again, compiles against the existing library of native code that provides the functionality of display list, video and audio players and so on.
If you can convert it to Haxe (Haxe has extremely AS3 like syntax, only libraries and some language constructs differ) it should provide you with an option of compiling for "native". I've heard it even provides a C++ sourcecode or so I've been told by folks at IRC Haxe room. I could have been trolled for the code part, though he didn't seem like he was trolling...
I'ts not perfect and definitely lacks some more advanced capabilities but it's worth looking at probably.
No, because of
absense of dynamic features in C++ (you don't have Object and describeType equivalent there)
absense of Flash native types in C++ (String (std::string is not equivalent), display objects and many others)
absense of language features (event listeners, garbage collection)
absense of Flex framework equivalent in C++ (there are other good GUI frameworks in C++, but none looks like Flex - because of the reasons above.)
In short, it's much easier to write similar program in C++ (using Qt or whatever framework of comparable strength) than write convertor for that.
If I have some c++ code as a string quantity (data) in a c++ program, can I execute the contents of that string?
As using the CodeDOM in C# or the eval function present in perl, python, etc..
Short answer: you can't.
Slightly longer answer: c++ has no reflection, and is generally compiled, so there so is no support for this kind of thing, and it can not be easily added..
Work arounds:
Use an embeddable dynamic language like [python|tcl|ruby|...] in concert with your c++ code. Now you need to have the dynamic language (rather then c++) in the data.
Use a c++ interpreter like cint or ch. This binds you to the interpreter.
Use the system c++ compiler to construct a dynamic library from your code and link to it on the fly. Risky and system dependent.
Use a different language.
No. As C++ is a static language, you can not dynamically eval arbitrary code.
You could interpret it or even compile and run it seperately as Keith suggested
if you mean compile C++ code on the fly and run it? sure if you have a compiler available to you
Non of the mainstream C++ implementations have that feature, as C++ is not reflective.
However, take a look at Ch, it might be what you are looking for:
http://www.softintegration.com/
http://en.wikipedia.org/wiki/Ch_interpreter
You can embed Ch interpreter into your C++ application and run dynamic C++ code inside it.
C++ cannot do this - the compiled program has no knowledge of the source language syntax, identifier names etc.
Even if you go to the effort of writing the string out to a file, calling a c++ compiler to generate a dynamic library and loading and calling it, that call won't have any knowledge of your program - it won't be able to reference your variables etc.
The most common reason to want to do this is to be able to evaluate expressions from within strings. Writing the code to do this from scratch is definitely non-trivial, but depending on your specific requirements, you should be able to find a library or embeddable scripting language to do roughly what you need.
After a quick Google, I found this - C rather than C++, and I don't know how good it is. It's written as a demo of a parser generator that I haven't heard of. You might find alternatives as demos of better known parser generators such as yacc, bison, yacc++ or antlr.