What frameworks/languages support run-time class creation? [closed] - reflection

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm trying to put together a list of frameworks/languages support run-time class creation. For example in .NET you can use the System.Reflection.Emit library to emit new classes at run time. If you could mention other frameworks/languages that support this (or some variation of it), that'd be really helpful.
Thanks :)

Dynamic languages like Python, Ruby, ...

Objective-C supports it (objc_allocateClassPair)

In JavaScript functions are objects. Thus given a function definition like:
function Foo(x, y, z)
{
this.X = x;
this.Y = y;
this.Z = z; var g = function()
}
you can create a new object like this:
var obj = new Foo(a,b,c);
But in JavaScript you can create functions at runtime.
function MakeFoo(x, y, z, f) //where parameter f is a function
{
var g = function()
{
this.X = x;
this.Y = y;
this.Z = z;
this.DoSomething = f;
}
return g;
}
var my_class = MakeFoo(a, b, c, function() { /* Do Stuff */ });
var obj = new my_class();
obj.DoSomething();

Depending on what you mean, any language can.
For example, C++ can. At first sight, this is absurd - C++ is a statically typed compiled language. So - what you do is include the LLVM library in your project. This is a compiler back-end, and you can use this to describe your classes, compile them, and run them using the LLVM JIT, all at run-time for your application.
IIRC, the gcc back end is written in C, so if you're willing to figure out that code, you could in principle define classes at run-time using a language that doesn't even have classes.
Either way, part of your job is to define what exactly a class is - that isn't built into the compiler back ends as they are supposed to support a range of different front-end languages with different type systems.
Of course I'm not recommending this approach - just pointing out that it's possible.

Related

Does each assignment mean that a copy is being made?

Recently I learned that in R there are no references, rather all object are immutable and each assignment makes a copy.
Uh-oh.
Copying large matrices over and over seems pretty horrible...
Now I'm in a paranoia, copypasting code all the time because I'm afraid of making helper functions (passing parameters = assignment? returning values = assignment?), I'm afraid of making helper variables if I'm not 100% sure an object would be copied anyway...
Example:
What I would love to make:
foo = function(someGivenLargeObject) {
returnedMatrix = someGivenLargeObject$someLargeMatrix # <- BAD?!?!?!?!
if(someCondition)
returnedMatrix = operateOn(returnedMatrix)
if(otherCondition)
returnedMatrix = operateOn(returnedMatrix)
returnedMatrix
}
What I'm making instead:
foo = function(someGivenLargeObject) { # <- still BAD?!?!?!
returnedMatrix = NULL # <- No copy of someLargeMatrix is made!
if(someCondition)
returnedMatrix = operateOn(someGivenLargeObject$someLargeMatrix)
if(otherCondition)
returnedMatrix = operateOn(
if(is.null(returnedMatrix))
someGivenLargeObject$someLargeMatrix
else
returnedMatrix
) # <- ^ Incredible clutter! Unreadable!
if(is.null(returnedMatrix))
return(someGivenLargeObject$someLargeMatrix)
else
return(returnedMatrix) # <- does return copy stuff?!?!?!?!
The readability loss in the second version of the function is pretty amazing IMO; yet - is this the price to avoid the unecessary copying of someLargeMatrix in case neither someCondition nor otherCondition holds? Because the line returnedMatrix = someGivenLargeObject$someLargeMatrix would necessite this copying?
Or am I in a paranoia, may I go safely with the more readable version of the function because making a reference to someLargeMatrix doesn't necessite copying? (BUT THERE ARE NO REFERENCES IN R!!!)
Also I hope that a function call / function return doesn't copy stuff either?
}
Side note: Just so that it is clear: I didn't yet run into an issue when I knew an object was copied unecessarily in a situation like that I described above. I'm just perplexed by having read that "there are no references in R", so this question is based on my worries from what might be the implication of this lack of references, rather than any empirical observation.
Donald Knuth famously said "Premature Optimization is the root of all evil",
http://wiki.c2.com/?PrematureOptimization
it is good to be aware about this, but code clarity is on most cases more important.
R is usually smart enough to figure out when copy is needed.
(not all assignments cause a copy only assignments that are later modified)

Scope of for loops in julia [duplicate]

This snippet of code is from JuliaBoxTutorials
myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]
i = 1;
while i <= length(myfriends)
friend = myfriends[i]
println("Hi $friend, it's great to see you!")
i += 1
end
giving this error when run with Julia v1.0
UndefVarError: i not defined
Stacktrace:
[1] top-level scope at ./In[12]:5 [inlined]
[2] top-level scope at ./none:0
But when i += 1 is replaced with global i += 1 it works. I guess this was still working in v0.6 and the tutorial will be adapted once the new Intro to Julia is published this Friday.
I was just wondering, is it possible, to make a while loop without stating a global variable?
As #Michael Paul and #crstnbr already replied in the comments, the scoping rules have been changed (Scope of variables in Julia). The for and while loop introduce a new scope and have no access to the outside (global) variables. You can get scope access using the global keyword but the recommended workflow is wrapping your code in functions.
One of the benefits of the new design is that the user is forced to avoid such global constructs which directly affect the performance of functions - which cannot be type stable when they access global variables.
One downside is the confusion when experimenting in the REPL and seeing such errors.
In my opinion the new behaviour is the cleaner one with respect to predictability. It was however a very tough and long-running discussion within the whole Julia community ;)
There is currently a discussion if the REPL will be changed to behave like the old one by making use of let-wraps: https://github.com/JuliaLang/julia/issues/28789
This is something which is not practical to be done manually (much more complicated then using the global keyword), see the example by Stefan Karpinski: https://github.com/JuliaLang/julia/issues/28789#issuecomment-414666648
Anyways, for the sake of completeness (although I would not recommend doing this) here is a version using global:
myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]
i = 1;
N = length(myfriends)
while i <= N # you cannot even call a function here
# with a global, like length(myfriends)
global i, myfriends
friend = myfriends[i]
println("Hi $friend, it's great to see you!")
i += 1
end
Note however that this is also completely valid:
myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]
greet(friend) = println("Hi $friend, it's great to see you!")
for friend in myfriends
greet(friend)
end
I found that this works in Julia v1.0:
let
myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]
i = 1;
while i <= length(myfriends) # this function here seems to work no problem
friend = myfriends[i]
println("Hi $friend, it's great to see you!")
i = i + 1 # gives syntax error when prefixed with global
end
end
In fact, it will give me a syntax error if I try to make i global :) within the while loop.

Closure compiler mixes variable names

I have a problem where the Closure Compiler renames a global variable something like x.sa.xa but in all function where that global variable is referenced the compiler renames it something else like H.sa.xa
When I view the HTML page I get a JavaScript TypeError: H.sa.xa is undefined.
// Top-level namespace for all the code
var nam = nam || {};
(function($, nam) {
goog.provide('nam.jsConfig');
nam.jsConfig.cookies = {"RECENT_ITEMS": "recentitems"};
})($, nam);
(function($, nam) {
goog.provide('nam.util.cookie');
nam.util.cookie.readMyCookie = function () {
var ritems_cookie = nam.util.cookie.JSONCookie.get(nam.jsConfig.cookies['RECENT_ITEMS']);
};
})($, nam);
Closure Compiled Code:
x.sa = {};
x.sa.xa = {RECENT_ITEMS:"recentitems"};
H.a = {};
H.a.cookie = {};
H.a.Tm = function() {
var a = H.a.cookie.ja.get(H.sa.xa.RECENT_ITEMS);
};
For some reason the Closure Compiler is referencing H.sa.xa.RECENT_ITEMS instead of x.sa.xa.RECENT_ITEMS
Any reason why the compiler is doing this this?
The only way I can interpret your question is that one of two things is happening:
There is an issue with the Closure Compiler's obfuscating and minimizing code, or
The error you are seeing is from JavaScript running outside of the code compiled by the Closure Compiler that is referencing a compiled variable directly.
If it is the former, you should isolate the case that is causing variable misalignment and submit it as a bug to Google. All of us using the Closure Compiler would greatly appreciate it.
If instead, as I suspect, it is the latter, you are most likely not exporting the global variable you wish to use outside of the compiled code. The easiest way to do this is to call goog.exportSymbol() function to make the global variable available outside of your code assembled by the Closure Compiler. For example, if you wished to access the property sandwich.meat.Ham in compiled mode from non-compiled code, you could do the following:
goog.exportSymbol('sandwich.meat.Ham', sandwich.meat.Ham);
Then you could have some code that exists outside of your compiled code that references the exported variable:
function() {
var meat = new sandwich.meat.Ham();
}
Let me guess what you are doing: compiling each file independently in ADVANCED mode. If so, this isn't how ADVANCED mode works. In advanced mode if you want to share variable and properties between compilations jobs you need to export them.
There are much more significant issues in the code example you provided. For one
goog.provide('nam.util.cookie');
was turned into
H.a = {};
H.a.cookie = {};
Yet later this code:
nam.util.cookie.readMyCookie = function () {...
was turned into
H.a.Tm = function() {...
Where one would expect it should be
H.a.cookie.Tm = function() {...
Additionally, the fact that you use nam as the base namespace for both halves of the uncompiled code and that it gets turned into separate x and H namespaces, respectively, also suggests more is at play. Some suggestions:
If you wish to use the module pattern, put the provide/require statements outside of the module
Don't manually create namespaces with stuff like var nam = nam || {} because provide does this for you already
As others have mentioned, both files containing nam.jsConfig and nam.util.cookie should be included in a single compilation
Make sure you goog.require('nam.jsConfig') in the file with nam.util.cookie.readMyCookie, to ensure the dependency requirements are met
FWIW, we use closure in an extensive application with hundreds of files, containing interdependencies like this. I would be highly suspect that the issue lies not with the tools, but instead with how they are being used.

Javascript: sync to async converter libs

1) What is better streamlinejs: https://github.com/Sage/streamlinejs
or narrative: http://www.neilmix.com/narrativejs/ ? any others libs?
2) How does any of those libraries even work?
(I read the docs, I am looking for a simplify explanation of what's going on behind the scene..)
As far as question #2....in general these things:
parse javascript into some abstract syntax tree (AST)
transform the AST
stringify the transformed tree back into javascript
I wrote a partial converter as a learning experience a while back. I used uglify.js to parse into an AST and then the tree walker that lib provides to do the transformations. The transformations were general purpose and produced code that looked like a state machine -- where each step started with a sequence of 0 or more sync actions and ended with an async action. E.g. this simple script:
var fs = require('fs');
console.log(fs.readFile('input.js', _).toString('utf-8'));
would get converted to this:
var fs, $v_0;
function s_0() {
fs = require("fs");
fs.readFile("input.js", function(err, res) {
if (err) s_err(err); else {
$v_0 = res;
s_1();
}
})
}
function s_1() {
console.log($v_0.toString("utf-8"));
}
s_0()
I imagine that streamline and the like do something very similar. Certain structures (loops, try/catch) need special handing but the general approach is the same -- convert into a state machine.
The issues with this approach that I found were:
1) it's not a local problem - i.e. any async behavior that needs to be handled infects everything all the way up the call stack.
2) you need function metadata so you either have to make assumptions or require people to annotate their functions in some manner.

How to reverse a QList?

I see qCopy, and qCopybackward but neither seems to let me make a copy in reverse order. qCopybackward only copies it in reverse order, but keeps the darn elements in the same order! All I want to do is return a copy of the list in reverse order. There has to be a function for that, right?
If you don't like the QTL, just use the STL. They might not have a Qt-ish API, but the STL API is rock-stable :) That said, qCopyBackward is just std::copy_backward, so at least they're consistent.
Answering your question:
template <typename T>
QList<T> reversed( const QList<T> & in ) {
QList<T> result;
result.reserve( in.size() ); // reserve is new in Qt 4.7
std::reverse_copy( in.begin(), in.end(), std::back_inserter( result ) );
return result;
}
EDIT 2015-07-21: Obviously (or maybe not), if you want a one-liner (and people seem to prefer that, looking at the relative upvotes of different answers after five years) and you have a non-const list the above collapses to
std::reverse(list.begin(), list.end());
But I guess the index fiddling stuff is better for job security :)
Reverse your QList with a single line:
for(int k = 0; k < (list.size()/2); k++) list.swap(k,list.size()-(1+k));
[Rewrite from original]
It's not clear if OP wants to know "How [do I] reverse a QList?" or actually wants a reversed copy. User mmutz gave the correct answer for a reversed copy, but if you just want to reverse the QList in place, there's this:
#include <algorithm>
And then
std::reverse(list.begin(), list.end());
Or in C++11:
std::reverse(std::begin(list), std::end(list));
The beauty of the C++ standard library (and templates in general) is that the algorithms and containers are separate. At first it may seem annoying that the standard containers (and to a lesser extent the Qt containers) don't have convenience functions like list.reverse(), but consider the alternatives: Which is more elegant: Provide reverse() methods for all containers, or define a standard interface for all containers that allow bidirectional iteration and provide one reverse() implementation that works for all containers that support bidirectional iteration?
To illustrate why this is an elegant approach, consider the answers to some similar questions:
"How do you reverse a std::vector<int>?":
std::reverse(std::begin(vec), std::end(vec));
"How do you reverse a std::deque<int>?":
std::reverse(std::begin(deq), std::end(deq));
What about portions of the container?
"How do you reverse the first seven elements of a QList?": Even if the QList authors had given us a convenience .reverse() method, they probably wouldn't have given us this functionality, but here it is:
if (list.size() >= 7) {
std::reverse(std::begin(list), std::next(std::begin(list), 7));
}
But it gets better: Because the iterator interface is the same as C pointer syntax, and because C++11 added the free std::begin() and std::end functions, you can do these:
"How do you reverse an array float x[10]?":
std::reverse(std::begin(x), std::end(x));
or pre C++11:
std::reverse(x, x + sizeof(x) / sizeof(x[0]));
(That is the ugliness that std::end() hides for us.)
Let's go on:
"How do you reverse a buffer float* x of size n?":
std::reverse(x, x + n);
"How do you reverse a null-terminated string char* s?":
std::reverse(s, s + strlen(s));
"How do you reverse a not-necessarily-null-terminated string char* s in a buffer of size n?":
std::reverse(s, std::find(s, s + n, '\0'));
Note that std::reverse uses swap() so even this will perform pretty much as well as it possibly could:
QList<QList<int> > bigListOfBigLists;
....
std::reverse(std::begin(bigListOfBigLists), std::end(bigListOfBigLists));
Also note that these should all perform as well as a hand-written loop since, when possible, the compiler will turn these into pointer arithmetic. Also, you can't cleanly write a reusable, generic, high-performance reverse function like this C.
#Marc Jentsch's answer is good. And if you want to get an additional 30% performance boost you can change his one-liner to:
for(int k=0, s=list.size(), max=(s/2); k<max; k++) list.swap(k,s-(1+k));
One a ThinkPad W520 with a QList of 10 million QTimers I got these numbers:
reversing list stack overflow took 194 ms
reversing list stack overflow with max and size took 136 ms
The boost is a result of
the expression (list.size()/2) being calculated only once when initializing the loop and not after every step
the expression list.size() in swap() is called only once when initializing the loop and not after every step
You can use the Java style iterator. Complete example here (http://doc.qt.digia.com/3.2/collection.html). Look for the word "reverse".
QList<int> list; // initial list
list << 1;
list << 2;
list << 3;
QList<int> rlist; // reverse list+
QListIterator<int> it(list);
while (it.hasPrevious()) {
rlist << it.previous();
}
Reversing a QList is going to be O(n) however you do it, since QList isn't guaranteed to have its data stored contiguously in memory (unlike QVector). You might consider just traversing the list in backwards order where you need to, or use something like a QStack which lets you retrieve the elements in the opposite order they were added.
For standard library lists it would look like this
std::list<X> result;
std::copy(list.rbegin(), list.rend(), std::back_inserter(result));
Unfortunately, Qt doesn't have rbegin and rend functions that return reverse iterators (the ones that go from the end of the container to its begnning). You may write them, or you can just write copying function on your own -- reversing a list is a nice excersize. Or you can note that QList is actually an array, what makes writing such a function trivial. Or you can convert the list to std::list, and use rbegin and rend. Choose whatever you like.
As of Qt 5.14 (circa 2020), QList provides a constructor that takes iterators, so you can just construct a reversed copy of the list with the reverse iterators of the source:
QList<int> backwards(forwards.rbegin(), forwards.rend());
Or if you want to be able to inline it, more generically (replace QList<I> with just I if you want to be super duper generic):
template <typename I> QList<I> reversed (const QList<I> &forwards) {
return QList<I>(forwards.rbegin(), forwards.rend());
}
Which lets you do fun one-liners with temporaries like:
QString badDay = "reporter covers whale exploding";
QString worseDay = reversed(badDay.split(' ')).join(' ');

Resources