Can Luabind property getters and setters yield? - lua

Is it possible to create a Luabind property with getters and setters that yield while they wait for the query to be performed in a different thread? The following syntax compiles but doesn't seem to work:
luabind::class_<Foo>("Foo")
.property("bar", &Foo::getBar, &Foo::setBar, luabind::yield)
Wrapping the object on the Lua side and adding property wrappers around regular functions is not a good option, as I need to define these properties on base classes and this would require much duplication of wrapper code for each derived class.

The following syntax compiles but doesn't seem to work:
Of course it doesn't work; luabind::yield solves a different problem. yield tells the system to yield after the function completes, not before, and certainly not in the middle of it.
You can't yield in the middle of C/C++ functions. Lua 5.2 adds the ability to set a "resume" function, but even then, there is significant danger in yielding within C++ code, since Lua generally won't clean up the stack.
What you want to do is yield before calling the function. It would be the equivalent of this Lua code:
function myGet(...)
local tester = StartAsyncAction(...);
while(~tester:IsFinished()) do
coroutine.yield();
end
return tester:Get(...);
end
You cannot really mimic that in C/C++; not with Lua 5.2. And Luabind doesn't fully support the new 5.2 features.

Related

A more standard __attribute__((warning("msg"))

In my C++ library I have a function that is still there, 1) for debugging 2) for small operations.
The function is basically a very slow fallback of more efficient versions.
(think of a loop of individual assigments vs memcpy for example)>
For this reason I would like to emit a warning as soon the function is invoked instantiated directly or indirectly. Without a warning it is not easy to test if the function is being invoked instantiated, because the function might be called instantiated trough several layers of template code.
I found that GCC's __attribute__((warning("slow function!"))) does the job quite well.
template<class T>
__attribute__((warning("careful this fun is very slow, redesign your algorithm")))
void slow_function(T){...}
However it is not standard or compatible with clang.
Is there a better alternative for this kind of compile time warning?
It looks like there is a standard [[deprecated("msg")]] attribute that also does the job, the problem is that it is confusing because there is nothing deprecated about this function, it is there for convenience.
There is also, I found recently a #pragma poison that might be applicable here, but I don't understand how it is used, besides the function is actually a member function of a template class, the examples do not consider this case. https://www.fluentcpp.com/2018/09/04/function-poisoning-in-cpp/

When are module level "constant" arrays being initialized in F#

The question came up while I was trying to write a lookup table and during debugging I had the impression, that the array might not be initialized at compile or load time, but rather in a lazy way... Unfortunately I could not find the answer in the MSDN chapter about arrays.
Lets look at some sample code first. The code is in a compiled application, not a script, btw.
module Foo =
let bar = [| for i in 0..9 -> yield (i*i) |]
When does Foo.bar get initialized?
At compile time?
At load time?
Lazy, when first accessed?
Never? (Stays an IEnumerator based sequence despite its array type?)
On a side note, my sequence expression is more complicated than the example above and also uses other functions within scope.
Are there cases which are handled in different ways, such as trivial vs complex eypression or long vs short array etc?
Foo.bar gets initialized at load time - or, when your application starts.
There are slight differences between how this is done for libraries and for applications. For applications, the compiler inserts appropriate initialization into the Main method. For libraries, the initialization check is inserted into static constructors of (I believe) all types, so when you access any type from a library, the initialization is done (this may be sometime after Main, but still before you run any code from the library).
It does not really depend on what the code is - if it is a value, it will be initialized. There are some values like Lazy<T> or IEnumerable<T> that do not immediately fully evaluate, but the value is initialized nevertheless.

Dynamically modify symbol table at runtime (in C)

Is it possible to dynamically modify symbol table at runtime in C (in elf format on Linux)?
My eventual goal is the following:
Inside certain function say foo, I want to override malloc function to my custom handler my_malloc. But outside foo, any malloc should still call to malloc as in glibc.
Note: this is different from LD_PRELOAD which would override malloc during the entire program execution.
Is it possible to dynamically modify symbol table at runtime in C (in elf format on Linux)?
In theory this is possible, but in practice it's too hard to do.
Inside certain function say foo, I want to override malloc function to my custom handler my_malloc. But outside foo, any malloc should still call to malloc as in glibc.
Modifying symbol table (even if it were possible) would not get you to your desired goal.
All calls from anywhere inside your ELF binary (let's assume foo is in the main executable), resolve to the same PLT import slot malloc#plt. That slot is resolved to glibc malloc on the first call (from anywhere in your program, assuming you are not using LD_BIND_NOW=1 or similar). After that slot has been resolved, any further modification to the symbol table will have no effect.
You didn't say how much control over foo you have.
If you can recompile it, the problem becomes trivial:
#define malloc my_malloc
int foo() {
// same code as before
}
#undef malloc
If you are handed a precompiled foo.o, you are linking it with my_malloc.o, and you want to redirect all calls from inside foo.o from malloc to my_malloc, that's actually quite simple to do at the object level (i.e. before final link).
All you have to do is go through foo.o relocation records, and change the ones that say "put address of external malloc here" to "put address of external my_malloc here".
If foo.o contains additional functions besides foo, it's quite simple to limit the relocation rewrite to just the relocations inside foo.
Is it possible to dynamically modify symbol table at runtime in C (in elf format on Linux)?
Yes, it is not easy, but the functionality can be packaged into a library, so at the end of the day, it can be made practical.
Typemock Isolator++
(https://www.typemock.com/isolatorpp-product-page/isolate-pp/)
This is free-to-use, but closed source solution. The usage example from documentation should be instructive
TEST_F(IsolatorPPTests, IsExpired_YearIs2018_ReturnTrue) {
Product product;
// Prepare a future time construct
tm* fakeTime = new tm();
fakeTime->tm_year = 2018;
// Fake the localtime method
FAKE_GLOBAL(localtime);
// Replace the returned value when the method is called
// with the fake value.
WHEN_CALLED(localtime(_)).Return(fakeTime);
ASSERT_TRUE(product.IsExpired());
}
Other libraries of this kind
Mimick, from Q: Function mocking in C?
cpp-stub, from Q: Creating stub functionality in C++
Elfspy, for C++, but sometimes it's OK to test C code from C++ unittests, from Q: C++ mock framework capable of mocking non-virtual methods and C functions
HippoMocks, from Q: Mocking C functions in MSVC (Visual Studio)
the subprojects in https://github.com/coolxv/cpp-stub/tree/master/other
... there is still more, feel free to append ...
Alternate approaches
ld's --wrap option and linker scripts, https://gitlab.com/hedayat/powerfake
various approaches described in answers for Q: Advice on Mocking System Calls
and in answers to Q: How to mock library calls?
Rewrite code to make it testable
This is easier in other languages than C, but still doable even in C. Structure code into small functions without side-effects that can be unit-tested without resorting to trickery, and so on. I like this blog Modularity. Details. Pick One. about the tradeoffs this brings. Personally, I guturally dislike the "sea of small functions and tons of dependency injection" style of code, but I realize that that's the easiest to work with, all things considered.
Excursion to other languages
What you are asking for is trivial to do in Python, with the unittest.mock.patch, or possibly by just assigning the mock into the original function directly, and undoing that at the end of the test.
In Java, there is Mockito/PowerMock, which can be used to replace static methods for the duration of a test. Static methods in Java approximately correspond to regular functions in C.
In Go, there is Mockey, which works similarly to what needs to be done in C. It has similar limitations in that inlining can break this kind of runtime mocking. I am not sure if in C you can hit the issue that very short methods are unmockable because there is not enough space to inject the redirection code; I think more likely not, if all calls go through the Procedure Linkage Table.

Using Dart as a DSL

I am trying to use Dart to tersely define entities in an application, following the idiom of code = configuration. Since I will be defining many entities, I'd like to keep the code as trim and concise and readable as possible.
In an effort to keep boilerplate as close to 0 lines as possible, I recently wrote some code like this:
// man.dart
part of entity_component_framework;
var _man = entity('man', (entityBuilder) {
entityBuilder.add([TopHat, CrookedTeeth]);
})
// test.dart
part of entity_component_framework;
var man = EntityBuilder.entities['man']; // null, since _man wasn't ever accessed.
The entity method associates the entityBuilder passed into the function with a name ('man' in this case). var _man exists because only variable assignments can be top-level in Dart. This seems to be the most concise way possible to use Dart as a DSL.
One thing I wasn't counting on, though, is lazy initialization. If I never access _man -- and I had no intention to, since the entity function neatly stored all the relevant information I required in another data structure -- then the entity function is never run. This is a feature, not a bug.
So, what's the cleanest way of using Dart as a DSL given the lazy initialization restriction?
So, as you point out, it's a feature that Dart doesn't run any code until it's told to. So if you want something to happen, you need to do it in code that runs. Some possibilities
Put your calls to entity() inside the main() function. I assume you don't want to do that, and probably that you want people to be able to add more of these in additional files without modifying the originals.
If you're willing to incur the overhead of mirrors, which is probably not that much if they're confined to this library, use them to find all the top-level variables in that library and access them. Or define them as functions or getters. But I assume that you like the property that variables are automatically one-shot. You'd want to use a MirrorsUsed annotation.
A variation on that would be to use annotations to mark the things you want to be initialized. Though this is similar in that you'd have to iterate over the annotated things, which I think would also require mirrors.

Usage of inline closures / function delegates in Actionscript

Why are inline closures so rarely used in Actionscript? They are very powerful and I think quite readable. I hardly ever see anyone using them so maybe I'm just looking at the wrong code. Google uses them in their Google Maps API for Flash samples, but I think thats the only place I've seen them.
I favor them because you have access to local variables in the scope that defines them and you keep the logic in one method and dont end up with lots of functions for which you have to come up with a name.
Are there any catches of using them? Do they work pretty much the same way as in C#.
I actually only just discovered that AS3 supports them, and I'm quite annoyed becasue I had thought I read that they were deprecated in AS#. So I'm back to using them!
private function showPanel(index:int):void {
_timer = new Timer(1000, 1);
_timer.addEventListener(TimerEvent.TIMER, function(event:Event):void
{
// show the next panel
showPanel(index++);
});
The biggest gotcha to watch out for is that often 'this' is not defined in the inline closure. Sometimes you can set a 'this', but it's not always the right 'this' that you would have available to set, depending on how you're using them.
But I'd say most of the Flex code I've worked on has had inline closures rampantly throughout the code--since callbacks are the only way to get work done, and often you don't need the bring out a whole separate function.
Sometimes when the function nested is getting to be too much, I'll break it out slightly with Function variables in the function; this helps me organize a bit by giving labels to the functions but keeping some of the characteristics of inline closures (access to the local variables, for example).
Hope this helps.
One additional problem is that garbage collection is broken when it comes to closures (at least in Flash 9). The first instance of a given closure (from a lexical standpoint) will never be garbage collected - along with anything else referenced by the closure in the scope chain.
I found what originally made me NOT want to do this, but I had forgotten the details:
http://livedocs.adobe.com/flex/3/html/16_Event_handling_6.html#119539
(This is what Mitch mentioned - as far as the 'this' keyword being out of scope)
So thats Adobe's answer, however I am much more likely to need to refer to local variables than 'this'.
How do others interpret Adobe's recommendation ?

Resources