What does "##" after variable mean? - ocaml

Js.coerce_opt (Dom_html.document##getElementById id)
I'm new to OCaml, and I'm dealing with Js_of_Ocaml recently. I've seen code as above that includes two pounds after between variable and function. What do they mean?

Ordinary method calls for OCaml objects are written as obj#meth.
In order to handle Js objects, js_of_ocaml adds a (ppx) syntax extension that uses obj##meth for invoking methods for Js objects: https://ocsigen.org/js_of_ocaml/4.0.0/manual/ppx .

Related

C++ function slash operator lambda expression

in fact I don't know how to be very precise.
Today, I browsed the following page:
http://siliconframework.org/docs/hello_world.html
I found the following syntax:
GET / _hello = [] () { return D(_message = "Hello world."); }
I found "GET" can be a function by lambda expression, but I cannot figure out what does "/" and "_hello" mean here, and how they connect to something meaningful.
Also, what is that "_message = "?
BTW, my primary C++ knowledge is before C++11.
I googled quite a bit.
Could any one kindly give an explanation?
This library uses what is known as an embedded Domain Specific Language, where it warps C++ and preprocessor syntax in ways that allow a seemingly different language to be just another part of a C++ program.
In short, magic.
The first bit of magic lies in:
iod_define_symbol(hello)
which is a macro that generates the identifier _hello of type _hello_t.
It also creates a _hello_t type which inherites from a CRTP helper called iod::symbol<_hello_t>.
_hello_t overrides various operators (including operator= and operator/) in ways that they don't do what you'd normally expect C++ objects to behave.
GET / _hello = [] () { return D(_message = "Hello world."); }
so this calls
operator=(
operator/( GET, _hello ),
/* lambda_goes_here */
);
similarly in the lambda:
D(_message = "Hello world.");
is
D( operator=(_message, "Hello world.") );
operator/ and operator= can do nearly anything.
In the D case, = doesn't do any assigning -- instead, it builds a structure that basically says "the field called "message" is assigned the value "Hello world.".
_message knows it is called "message" because it was generated by a macro iod_define_symbol(message) where they took the string message and stored it with the type _message_t, and created the variable _message which is an instance of that type.
D takes an number of such key/value pairs and bundles them together.
The lambda returns this bundle.
So [] () { return D(_message = "Hello world."); } is a lambda that returns a bundle of key-value pair attachments, written in a strange way.
We then invoke operator= with GET/_hello on the left hand side.
GET is another global object with operator/ overloaded on it. I haven't tracked it down. Suppose it is of type iod::get_t (I made up that name: again, I haven't looked up what type it is, and it doesn't really matter)
Then iod::get_t::operator/(iod::symbol<T> const&) is overloaded to generate yet another helper type. This type gets the T's name (in this case "hello"), and waits for it to be assigned to by a lambda.
When assigned to, it doesn't do what you expect. Instead, it goes off and builds an association between "hello" and invoking that lambda, where that lambda is expected to return a set of key-value pairs generated by D.
We then pass one or more such associations to http_api, which gathers up those bundles and builds the data required to run a web server with those queries and those responses, possibly including flags saying "I am going to be an http server".
sl::mhd_json_serve then takes that data, and a port number, and actually runs a web server.
All of this is a bunch of layers of abstraction to make some reflection easier. The structures generated both have C++ identifiers, and similar strings. The similar strings are exposed in them, and when the json serialization (or deserialization) code is generated, those strings are used to read/write the json values.
The macros merely exist to make writing the boilerplate easier.
Techniques that might be helpful to read on further include "expression templates", "reflection", "CRTP", embedded "Domain Specific Language"s if you want to learn about what is going on here.
Some of the above contains minor "lies told to children" -- in particular, the operator syntax doesn't work quite like I implied. (a/b is not equivalent to operator/(a,b), in that the second won't call member operator /. Understanding that they are just functions is what I intend, not that the syntax is the same.)
#mattheiuG (the author of this framework) has shared these slides in a comment below this post that further explains D and the _message tokens and the framework.
It's not standard C++ syntax, it's framework specific instead. The elements prefixed with an underscore (_hello, _message etc) are used with a symbol definition generator that runs and creates the necessary definitions prior to compilation.
There's some more information on it on the end of this page: http://siliconframework.org/docs/symbols.html. Qt does a similar thing with its moc tool.

Is it possible to use two or more different yylex() functions in same C/C++ program? [duplicate]

This question already has answers here:
Is it possible to have two or more Lex/Yacc parsers in the same application
(4 answers)
Closed 7 years ago.
I'm making a lexical analyzer for C language, a less-powered version.
I want to process different kinds of regular expressions at different times for example, for the first time the input character stream from the source program and then the second time, an intermediate representation form of the program generated after first processing.
So is it possible to create 2 or more yylex() functions using FLEX and use it in a same C/C++ program, the lexical analyzer?
You can use the %prefix declaration to change the yy in yylex (and a variety of other global names) to something different, which allows you to have multiple scanners in the same project. You will probably also want to use the -o option to set the name of the generated file; otherwise, the build procedure gets ugly.
But they will be completely separate scanners, each with their own input stream. That might not be what you want.
If you want a scanner whose lexical definitions can be changed to another set, you need to use start conditions. That will let you change scanner behaviour in different contexts, and has the advantage that you can share common lexical features.
flex has a similar parameter:
‘-PPREFIX, --prefix=PREFIX, %option prefix="PREFIX"’changes the
default ‘yy’ prefix used by flex for all globally-visible variable and
function names to instead be ‘PREFIX’. For example, ‘--prefix=foo’
changes the name of yytext to footext. It also changes the name of the
default output file from lex.yy.c to lex.foo.c.
So you can rename the second function and its variables.
Unfortunately POSIX lex has not such parameter.

How to implement Python function exec() in C++?

The Python function exec() is a very good tool for programming.
For example:
/******************************************************
* we have array names={"ali","hamed"}
* goal is declare string ali="ali" and hamed="hamed"
******************************************************/
Python code:
# used for command
# below line is a syntax python
# in python we dont declare variable
list=["ali","hamed"] #python syntax
#in python we dont wite {
#python work with tab insteed of {}
for i in list:
temp = i + ' = "' + i + '"' #temp is a string
exec(temp)
My question: Is there a similar function exists in C++? If not, how to implement it in C++?
Python's exec, and similar features in other languages (i.e. eval in JavaScript) only work because those are interpreted languages where variables are defined at run time.
You can't do what you're asking in directly C++ because it's a compiled language that requires that all variables and their names are known at compile time.
You can do it, but it's not trivial, and it will only work on
systems where a C++ compiler is installed. Basically, C++ is
compiled, so if you want to execute some string which is C++,
you'll have to compile it: write it to a file (probably with
additional boilerplate like some includes), invoke the compiler
(with system) to build a DLL, and then load the DLL.
In practice, even if you went to all that effort, you'd probably
find it less useful than you think. Because C++ requires static
declarations for just about everything, it's much harder to
write small snippets like that and have them usable. (You
would, for example, have to wrap it in a function, and generate
extern for all of the variables it uses.) C++ doesn't support
this sort of thing for software engineering reasons; the very
features which make languages like Python so flexible for small,
quickly written programs, cause severe maintenance problems when
used in large scale robust software. Different languages are
designed for different purposes. It's very easy to create
a mixed language system using Python for the top level glue
(where you would want a facility such as you describe), and
calling into C++ for the heavy work (where such a facility would
allow the user to trigger core dumps at will).
Alternatively, you can implement a small language in C++. For
keeping user defined variables, for example, use std::map,
rather than declaring the variables. (That is, after all, what
Python does under the hood.)
If you are planning to use strings as parameters,it is NOT a good idea!
you can simply use an id generator function and give an id to every string that you are gonna use ,or if you are using a class you can put that function in the constructor.
no need to that exec() at all!!

let the user use a function in c++ [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Dynamic source code in C++
is it possible to let the user type in a function and then run that function without using a lot of if's or a huge switch?
It is not possible to execute arbitrary c++ code in your program, since you than need a c++ compiler inside your program. But you could try to embed Python to your program. Boost python makes this relatively easy. The user can than write a python function that is executed and can interact with the classes and functions of your program. You need to make your functions explicitely visible to python.
What ever a user types in will be text, or a string. The only way I know to have it get mapped to a function is to use if/else or switch statements. That or the cringe inducing option of mapping each of your functions to a UI widget.
The end of the story, is it's your code. You have to write, and live with it. Just be careful, your program may be wildly successful, and you may not write code anymore, and then someone else will have to maintain your code. So be nice to the maintenance programmer who may follow you, and write code that isn't too tricky to figure out.
I assume you want something like eval from php.
You can try to play with command design pattern, but I doubt it will be an easy task. Basically you need to write simple C++ interpreter.
What type of function do you mean? A C++ function? If so, then you will have to either (1)interpret it or (2)compile and execute it. Interpretation would be the more likely choice here. I'm not sure if there are libraries out there already to do this but I'd assume there are.
If you don't like mega-if's or huge switches, you may be SoL on any solution for anything ever, but then again there is seldom one perfect way to do things. Consider looking in to various logic structures and algorithms to see how to do something that would normally be the job of a 23-case switch could be done another way. Like I said initially, however, sometimes you really do just need a million nested if's to do what you want to.
No, in C++ this is not possible. C++ is a compiled language. When the program runs, the compiler doesn't need to be accessible, or even installed on the machine that runs the program.
If you want to do this in C++, you need to write your own interpreter that parses whatever the user enters.
Here is my best idea, but it is a tad memory intensive.
First, create a class, lets call it MyFuncPtr to store a union of several different types of pointers to functions and an integer to tell which type it is. Overload the () operator to call the function stored with a variable length argument list. Make sure to include some sort of run-time argument checking.
Finally create a map of strings to MyFuncPtrs. Store your functions in this map along with their names. Then all you need to do is feed the name into the [] command to get a function that can be easily called. Templates could probably be used to aid in the making of MyFuncPtr instances.
This would be the easiest if it were plain C functions and no name mangling is performed on the symbols (use extern "C" { ... })
With some platform-specific code you can get the address of a function by its name. Then you cast the address as a function pointer which you can use to call the function.
On windows you must be using GetProcAddress and dlsym on Posix compliant platforms.

Interpreter in C++: Function table storage problem

In my interpreter I have built-in functions available in the language like print exit input, etc.
These functions can obviously be accessed from inside the language. The interpreter then looks for the corresponding function with the right name in a vector and calls it via a pointer stored with its name.
So I gather all these functions in files like io.cpp, string.cpp, arithmetic.cpp. But I have to add every function to the function list in the interpreter in order for it to be found.
So in these function files I have things like:
void print( arg )
{
cout << arg.ToString;
}
I'd add this print function to the interpreter function list with:
interpreter.AddFunc( "print", print );
But where should I call the interpreter.AddFunc?
I can't just put it there below the print function as it has to be in a function according to the C++ syntax.
Where and how should all the functions be added to the list?
In each module (io, string, etc.), define a method that registers the module with the interpreter, e.g.:
void IOModule::Register(Interpreter &interpreter) {
interpreter.AddFunc( "print", print );
//...
}
This can also be a normal function if your module is not implemented in a class.
Then in your application's main initialization, call the register method of all modules.
This approach helps keep things modular: The main application initialization needs to know which modules exist, but the details of which functions are exported are left to the module itself.
The simplest is to keep a map of function names to function pointers and load that at program startup. You already have the functions linked into the interpreter executable, so they are accessible at the time main() is called.
You can also come up with a scheme where functions are defiled in the dynamic libraries (.dll or .so depending on the platform) and some configuration file maps function names to libraries/entry points.
Is everything included in every interpreter? If so, I would recommend adding it either in a constructor (assuming the interpreter is an object) or an init method.
If not, you may want to consider adding an "include" type directive in your language. Then you do it when you encounter the include directive.