Can I copy a function with its *current* state? - state

Raku's state declarator can be used to give a subroutine or other block its own local state that persists across multiple invocations of the function:
sub f { state $n++ }
say f; # OUTPUT: «0»
say f; # OUTPUT: «1»
say f; # OUTPUT: «2»
I'm aware of two ways to "copy" a function that has internal state: First, I can assign it to a new &-sigiled variable with code like my &f1 = &f. This results in &f1 effectively being an alias to &f and means that they share state – anything that alters the state of &f or &f1 will also change the other function's state.
Second, I can make a clone of &f with code like my &f2 = &f.clone. This will create an independent function with state that is initialized to any default values in &f (that is, with $n being Any for the code above).
However, I'm hopping for a third way to copy &f that (like option 1) would preserve the current value of &f's state but that (like option 2) would make that state independent from &f's. In other words, I'd like to be able to use the commented-out lines below:
sub f { state $n++ }
say f; # OUTPUT: «0»
say f; # OUTPUT: «1»
say f; # OUTPUT: «2»
my &f1 = &f;
my &f2 = &f.clone;
# my &f3 = ???;
say f; # OUTPUT: «3»
say f; # OUTPUT: «4»
say f1; # OUTPUT: «5»
say f2; # OUTPUT: «0»
# say f3; # (desired) OUTPUT: «3»
Is there any way to save &f's state like that (maybe with something fancy with wrap or similar that I can't think of)? Or am I just asking to do something that isn't currently possible?

No, there's not a way - not even if one were willing to write a module that depends on unsupported Rakudo internals.
State variables are currently handled all the way down in the runtime (typically, MoarVM), where they are attached to a bytecode handle. Cloning a Block in turn clones the underlying bytecode handle, which explicitly does not clone the state variables.

Related

c++ check at compile time if a function is called

Possible duplicates I'll explain at the bottom.
I was wondering if it is possible to do a compile time check to see if a function is called before another function.
My use case looks something like this:
auto f = foo();
if(!f.isOk())
return f.getError();
auto v = f.value();
So in this case I would want to get a compile time error if the user did not call isOk before calling value.
As far as I know and searched it does not seem possible but I wanted to ask here just to be sure I didn't miss any c++ magic.
FauxDupes:
How to check at compile time that a function may be called at compile time?
This is about knowing wether your function is a constexpr function. I want to know if one function has been called before the other has been called.
What you want is not possible directly without changing your design substantially.
What you can do is enforce calling always both by wrapping them in a single call:
??? foo(const F& f) {
return f.isOk() ? f.value() : f.getError();
}
However, this just shifts the problem to choosing the return type. You could return a std::variant or with some changes on the design a std::optional, but whatever you do it will be left to the caller to check what actually has been returned.
Don't assume the most stupid user and don't try to protect them from any possible mistake. Instead assume that they do read documentation.
Having to check whether a returned value is valid is a quite common pattern: functions that return a pointer can return a null-pointer, functions returning an iterator can return the end iterator. Such cases are well documented and a responsible caller will check if the returned value is valid.
To get further inspiration I refer you to std::optional, a quite modern addition to C++, which also heavily relies on the user to know what they are dealing with.
PS: Just as one counter-example, a user might write code like this, which makes it impossible to make the desired check at compile time with your current design:
int n;
std::cin >> n;
auto f = foo();
if(n > 10 && !f.isOk())
return f.getError();
auto v = f.value();
One strategy for this kind of thing is to leverage __attribute__((warn_unused_result)) (for GCC) or _Check_return_ (msvc).
Then, change foo() to return the error condition:
SomeObj obj;
auto result = foo(obj);
This will nudge the caller into handling the error. Of course there are obvious limitations: foo() cannot be a constructor, for example, and the caller cannot use auto for the typename.
One way to ensure order is to transform the temporary dependency into physical dependency:
Move method F::getError() and F::value() into their own structure wrapper (Error, Value).
Change bool F::isOk() to something like:
std::variant<Error, Value> F::isOk()
Then, you cannot use Error::getError or Value::value() before calling isOk, as expected:
auto f = foo();
auto isOk = f.isOk();
if (auto* e = std::get_if<Error>(&isOk)) // Or std::visit
return e->getError();
auto& value = std::get<Value>(&isOk);
auto v = value.value();

Reuse of variable of type auto

I have a special class to be used as return type of methods, containing the wanted value or in case of failure an error message which is even cascading from earlier errors. It works as expected.
As the returned type is differently complex I like to use the keyword auto. But when using a lot of methods I have to create new return variables.
A typical part of code looks like this:
auto ret1 = methodA();
if(ret1.isValid()...
auto ret2 = methodB();
if(ret2.isValid()...
I dont like to always create a new variable. But I like the elegant way of error handling. Using a more dump return type like an error code in integer would solve the problem but then I have no benefit from the error handling return type.
Is there any trick to reuse the first return variable ret1?
You would have to create new scopes to reuse the variable name for a different variable, like:
{
auto ret = methodA();
if (ret.isValid()) ...
}
{
auto ret = methodB();
if (ret.isValid()) ...
}
You can also take advantage of the scope created by if, placing the init-statement inside:
if (auto ret = methodA(); ret.isValid()) ...
if (auto ret = methodB(); ret.isValid()) ...
auto is not a type.
It is a keyword, that says "put the type here for me, by deducing it from the initial value". That occurs during compilation, once.
You cannot reuse ret1 to store an object of a different type, whether you use auto or not.
This shouldn't really be a problem. If you're concerned about "running out of names", or "having many similar names", your names are not descriptive enough and/or your scopes aren't tight enough.
auto is not a type. In auto foo = bar(); the compiler simply figures out what type bar() actually returns and substitutes that in. So if bar() returns int then that's the type of foo, if it returns bool then that is the type of foo. And once the type that auto should be replaced with (the first time) has been determined, then it can never change. auto doesn't mean "variable type" it just means "hey compiler, I'm too lazy to figure out the type to put here, please do it for me", but there is no difference what-so-ever compared to you just writing the final type yourself.
So, you can reuse the variable if what you assign to it the second time is of the same type as the first time - otherwise not.
I dont like to always create a new variable.
Much better is to create a const variable:
const auto ret1 = methodA();
if(ret1.isValid()...
const auto ret2 = methodB();
if(ret2.isValid()...
In this case you need to make const all the methods like isValid, but that is even better: "is" shouldn't have side effects and modify the state.
Next step is to remove the temp variable at all:
if(methodA().isValid()) {
...
}
if(methodB().isValid()) {
...
}
The alternative is to wrap each function call into a block:
{
const auto ret = methodA();
if(ret.isValid()...
}
{
const auto ret = methodB();
if(ret.isValid()...
}
This allows you to reuse the const variable name.
Each block becomes a candidate for extraction into a separate function (see Uncle Bob in "Clean Code").

Capture arguments to a callback in google mock

I have an object which has a method like this:
mockObj.foo(cb);
where cb is a function of the following signature:
void cb(vector<A> &, vector<B> &);
Is there any way to capture the 2 arguments passed to cb to see if the function did what I wanted it to do? I expect cb to be called N number of times.
If you want to test what Obj class is doing - unit test Obj class in separation, like (of course I know real Obj::cb is not clearing input - this is just an example):
TEST(ObjTest, shouldResetInput)
{
vector<A> aa(1);
vector<B> bb(1);
Obj objUnderTest;
objUnderTest.cb(aa, bb);
ASSERT_TRUE(aa.empty());
ASSERT_TRUE(bb.empty());
}
In other objects, where Obj is used, inject it as ObjMock and just check only that this cb function is called with input as you expect - check input by Container Matchers. If you want in this clients of Obj change the input after the function is called - use Side Effect Actions.

Prevent nested C++ struct from being deleted when parent is GC'd

Here is a pretty trivial example of the problem I'm having. struct Foo contains struct Bar which contains one int. If a Foo is garbage collected, then its inner Bar is also removed, even if there are still references to that bar.
Python code
import example
def get_bar():
foo = example.Foo()
foo.bar.x = 10
bar = foo.bar
print("before {}".format(bar.x))
return foo.bar # foo (and bar) are deleted when this returns
bar = get_bar()
print("after {}".format(bar.x))
Output
> before 10
> after 39656152
I've eliminated all pointers and references from the C++ code, hoping that SWIG would use the same value semantics, but it is still internally converting things to Foo* and Bar*. I guess my question is, how can I convince SWIG to make a copy of bar in _wrap_Foo_bar_get?
Example code below:
example.h
struct Bar {
int x;
};
struct Foo {
Bar bar;
};
example.i
%module "example"
%{
#include "example.h"
%}
%include "example.h"
CMakeLists.txt
FIND_PACKAGE(SWIG REQUIRED)
INCLUDE(${SWIG_USE_FILE})
FIND_PACKAGE(PythonLibs)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH} .)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
SET(CMAKE_SWIG_FLAGS "")
SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES CPLUSPLUS ON)
SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "-includeall")
SWIG_ADD_MODULE(example python example.i example.h)
SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES})
And here is the generated SWIG method that is grabbing a reference to bar rather its value:
SWIGINTERN PyObject *_wrap_Foo_bar_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
Foo *arg1 = (Foo *) 0 ;
void *argp1 = 0 ;
int res1 = 0 ;
PyObject * obj0 = 0 ;
Bar *result = 0 ;
if (!PyArg_ParseTuple(args,(char *)"O:Foo_bar_get",&obj0)) SWIG_fail;
res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Foo, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Foo_bar_get" "', argument " "1"" of type '" "Foo *""'");
}
arg1 = reinterpret_cast< Foo * >(argp1);
result = (Bar *)& ((arg1)->bar);
resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Bar, 0 | 0 );
return resultobj;
fail:
return NULL;
}
SWIG (and Boost Python) are fighting an uphill battle by interfacing between languages with very different data models. You are making that battle that much harder (unwinnable) by expecting those SWIG-wrapped objects to behave exactly like other Python objects. They don't because they can't. The C++ and Python data models are quite different.
In C++, that Bar instance that is embedded within class Foo is an integral part of a Foo object. The memory occupied by that embedded Bar object is a part of the overall memory for that containing Foo object. When foo goes out of scope and is destructed, foo.bar must necessarily go out of scope and be destructed along with it's containing object. Your foo.bar is not detachable from foo. The two objects have identical lifespans.
That's not the case in Python. A Python object that contains a sub-object doesn't contain that sub-object in the C++ sense. The memory for the containing and contained objects are distinct and non-overlapping. The containing object instead has a reference to the contained sub-object. This makes those sub-objects in Python detachable from the objects that contain them. Just get a separate reference reference to that sub-object and voila!, the containing and contained objects have different life spans.
One way around this problem is to use smart pointers in your C++ code. SWIG does support these to some extent. Another way around this problem is to never let it rear its ugly head. Be aggressive with data hiding in the code that you are exposing to SWIG. The problem never arises if that Bar object embedded within that Foo object is properly hidden. Use the member functions, not the member data, and you'll be much better off.
One final word: There is another, somewhat kludgy, way around this problem, and that's to use the thisown attribute. Had you set foo.thisown = 0 in your Python function get_bar you wouldn't have had this problem. You would have had a leak, however.

C++ fprintf over many functions to a single text file

I am having difficulty in printing to a text file from chosen locations within a large C++ code project.
Using C++ I am using a function X which is called multiple times.
This is called from a function Y
I wish to output the results of function X to a single text file and have done so by continously using declarations, fopen, fprintf, fclose set of functions - this works – albeit very slowly.
However, I only wish to print results to file when X is called from a specific area of the host function Y.
I am looking to do so, whilist being minimally invasive with the current code (i.e. I wouldn’t like to add another argument to the function X, nor would I like to declare global variables).
Is their a way a unique methods to effectively ‘tell’ the code and child functions when to start printing to file and when to stop.
(p.s. I have post-processed my results using VBA however this workaround is found to be inefficient).
Any ideas or code constructs would be most welcome!
swarm
Below is the child function X:
void `X`() {
FILE *f2 = NULL;
f2 = fopen("log.txt", "a");
// Calculate a result: `result`
fprintf(f2, "%.4e ", result);
fclose (f2);
}
Below is the main calling function Y:
void Y Y(){
for i=1:100{
X();
X();
X(); // <-- Wishing to print only this line to a text file
}
}
Since you're in C++, you can add an overload of X that takes an argument of when to do it, and not have to change any callers.
You have
void X(args);
Add
void X(args, bool doIt);
Then, move the code in the original X to the new one, checking doIt.
In the original X, call X(args, false)
Somehow the boolean state of whether to actually log has to be passed. Choices are: an argument, a global, an member variable (static or instance), a thread local variable, or a file.
Whatever you do. it will probably be logically equivalent to declaring a global variable. But you can ease the pain of this in various ways:
If X is a class member, you can declare the variable as a static member of X's class.
If X belongs to a namespace, your global variable can belong to that namespace.
You can declare it as a static variable, local to X's source file, and use a function in the source file to set its value.
And so on.
If you don't want to keep binary compliance, than you can also transform X function to structure/class with overloaded operator() - then add field or method specyfying if you should print it or not. - however this is quite similar to another global variable. Except overloading X, i doubt there is any other method that doesn't use globals or something similar.
How are you keeping your FILE* pointer between X calls? global? stativ variable in function?