How to make C function visible to Racket - racket

I am trying to embed Racket in C++, how do I accomplish something like this
Scheme_Object* c_function(int argc, Scheme_Object** objects) {
printf("a c function with %d args", argc);
return scheme_null;
}
scheme_eval_string("(c_function)", env); // c_function undefined
I try scheme_make_prim_w_arity, but it seems I can use scheme_apply to it.

scheme_eval_string, like other forms of eval in Racket, operate on particular namespaces and won't be able to find functions or other bindings not available in those namespaces. You should:
Read this section of the docs about eval and namespaces.
Not use eval -- it's almost always the wrong tool.

Related

Matching against the enclosing function's return type

Is it possible for a Rust macro to match against the enclosing function's return type?
An example is something like a logging and assert macro which also returns Err in functions returning Result and panics in functions not returning Result. To implement this the macro should somehow know about the enclosing function's return type.
I suppose this is not possible with declarative macros (macro_rules!) because they have a limited set of matching types (as described in The Rust Reference, chapter Macros By Example): items, blocks, statements, patterns, expressions, types, identifiers, and so on, but not the enclosing function's return type.
But perhaps with procedural macros?
Summary: No, it's not easily possible, even with procedural macros. And I actually think you shouldn't write such a thing, even if it's possible. Just let your macro evaluate to a Result and let the user deal with it.
Function-like macro
Rust macros, procedural and declarative, only have access to their input stream: just a list of tokens. For function-like macros (the ones you invoke via foo!(...)), the input is just what you pass to them. So you could manually pass the return type:
macro_rules! foo {
(Result $($stuff:tt)*) => { return Err(()); };
($($stuff:tt)*) => { panic!(); };
}
fn returns_result() -> Result<String, ()> {
foo!(Result<(), ()>); // will return `Err`
Ok("hi".into())
}
fn returns_string() -> String {
foo!(String); // will panic
"hi".into()
}
But I guess that is not what you want: the user would have to manually specify the return type for each macro invocation.
The same goes for procedural macros that are invoked this way.
Procedural macro attribute
Can we define a procedural macro where the return type of the function is in the input token stream? Yes, preferably via a proc-macro attribute. If you define such an attribute bar, you could write this:
#[bar]
fn returns_result() -> Result<String, ()> { ... }
And your procedural macro would receive the whole function definition as input, including the return type. But what are you going to do with that information?
You can change the whole function as you like, so one idea would be to search for all foo!() macro invocations in the function and replace them with return Err or panic!() depending on the return type. That is: do the macro invocation step for your own macros via a procedural macro.
But I think this is a bad idea for several reasons. Most importantly, I don't think it's well defined when the compiler calls the procedural macro. So the compiler could attempt to invoke your foo!() macros before calling the procedural macro.
So it could work via procedural macro, but not in a way that is typical. So it's rather hacky.
What I think is the best solution
Lastly, how would I do it? Let your macro evaluate to a Result. Then the user can easily decide themselves what to do with it. If they return a Result, they just need to add ?. If they don't, they have the freedom to choose between .unwrap(), expect() and other ways to panic.
I understand why you are trying to do what you want to do (it's easier for the user and comfortable), but I think it's not a good idea. It probably comes down to "spooky action at a distance": what a macro in your function does suddenly depends on the return type of that function. That means when you change that, the whole semantics of the function change. This sounds like something you could shoot yourself in the foot with very easily. That's also probably the reason why it's not easy in Rust.

Make perl look ahead for sub prototypes

Perl is a bit too forgiving: If you pass extra arguments to subs they are simply ignored.
To avoid this I would like to use prototypes to make sure each sub is given the correct amount of arguments.
This works OK as long as I declare the prototype before using it:
sub mysub($);
sub mysub2($);
mysub(8);
mysub(8,2); # Complain here
sub mysub($) {
mysub2($#);
}
sub mysub2($) {
if($_[0] == 1) {
mysub(2);
}
print $#;
}
But I really hate splitting this up. I would much rather that Perl read the full file to see if there are declarations further down. So I would like to write something like:
use prototypes_further_down; # This does not work
mysub(8);
mysub(8,2); # Complain here
sub mysub($) {
mysub2($#);
}
sub mysub2($) {
if($_[0] == 1) {
mysub(2);
}
print $#;
}
Can I somehow ask Perl to do that?
To avoid this I would like to use prototypes to make sure each sub is given the correct amount of arguments.
No, you would not. Despite the similarity in name, Perl prototypes are not your father's function prototypes. Quoting The Problem with Prototypes (emphasis mine),
Perl 5's prototypes serve two purposes. First, they're hints to the parser to change the way it parses subroutines and their arguments. Second, they change the way Perl 5 handles arguments to those subroutines when it executes them. A common novice mistake is to assume that they serve the same language purpose as subroutine signatures in other languages. This is not true.
In addition to them not having the same intended purpose, bypassing prototypes is trivial, so they provide no actual protection against someone who deliberately wishes to call your code in (what you believe to be) the "wrong" way. As perldoc perlsub tells us,
The function declaration must be visible at compile time. The prototype affects only interpretation of new-style calls to the function, where new-style is defined as not using the & character. In other words, if you call it like a built-in function, then it behaves like a built-in function. If you call it like an old-fashioned subroutine, then it behaves like an old-fashioned subroutine. It naturally falls out from this rule that prototypes have no influence on subroutine references like \&foo or on indirect subroutine calls like &{$subref} or $subref->().
Method calls are not influenced by prototypes either, because the function to be called is indeterminate at compile time, since the exact code called depends on inheritance.
Even if you could get it to complain about mysub(8,2), &mysub(8,2) or $subref = \&mysub; $subref->(8,2) or (if mysub were an object method inside package MyModule) $o = MyModule->new; $o->mysub(8,2) would work without complaint.
If you want to validate how your subs are called using core Perl (prior to 5.20), then you need to perform the validation yourself within the body of the sub. Perl 5.20 and newer have a ("experimental" at the time of this writing) Signatures extension to sub declarations which may work for your purposes, but I've never used it myself, so I can't speak to its effectiveness or limitations. There are also many CPAN modules available for handling this sort of thing, which you can find by doing searches for things like "signature" or "prototype".
Regardless of your chosen approach, you will not be able to get compile-time errors about incorrect function signatures unless you define those signatures before they are used. In cases such as your example, where two subs mutually call each other, this can be accomplished by using a forward declaration to establish its signature in advance:
sub mysub($foo); # Forward declaration
sub mysub2 { mysub(8) }
sub mysub { mysub2('infinite loops ftw!') } # Complete version of the code

How to use Javascript's for (attr in this) with Coffeescript

In Javascript, the "for (attr in this)" is often dangerous to use... I agree. That's one reason I like Coffeescript. However, I'm programming in Coffeescript and have a case where I need Javascript's "for (attr in this)". Is there a good way to do this in Coffeescript?
What I am doing now is writing a bunch of logic in embedded raw Javascript, such as:
...coffeescript here...
for (attr in this) {
if (stuff here) {
etc
}
}
It'd be nice to use as little Javascript as possible... any suggestions for how I can achieve this and maximize my use of Coffeescript?
Instead of for item in items which iterates through arrays, you can use for attr, value of object, which works more like for in from JS.
for own attr, value of this
if attr == 'foo' && value == 'bar'
console.log 'Found a foobar!'
Compiled: https://gist.github.com/62860f0c07d60320151c
It accepts both the key and the value in the loop, which is very handy. And you can insert the own keyword right after the for in order to enforce an if object.hasOwnProperty(attr) check which should filter out anything from the prototype that you don't want in there.
Squeegy's answer is correct. Let me just amend it by adding that the usual solution to JavaScript's for...in being "dangerous" (by including prototype properties) is to add a hasOwnProperty check. CoffeeScript can do this automatically using the special own keyword:
for own attr of this
...
is equivalent to the JavaScript
for (attr in this) {
if (!Object.prototype.hasOwnProperty(this, attr)) continue;
...
}
When in doubt about whether you should use for...of or for own...of, it's generally safer to use own.
You can use for x in y or for x of y depending on how you want to interpret a list of elements. The newest version of CoffeeScript aims to solve this problem, and you can read about its new use with an issue (that has since been implemented and closed) here on GitHub

How do I access List template of C++ program from Perl using SWIG?

I want to access a template List of C++ program from a Perl script and use those values.
Example code:
typedef list < Struct1 * > sturct1_list;
struct Struct2
{
int i;
struct1_list List1;
}
struct Struct1
{
int j;
}
I used one swig generated api and did the following:
$myList = Struct2_struct1List_get
print "Reference type: " . ref($myList) ;
now this prints as:
Reference type: \_p\_std\_\_listTutils\_\_Struct1\_p\_t
how to get the values from the structure using this?
Update from duplicate question:
in interface file i put
%template(ListStruct1) std::list< Struct1 * >;
after i generate the ".pm" file. I checked the APIs available this list.
I found
ListStuct1_size
ListStuct1_empty
ListStuct1_clear
ListStuct1_push.
I was able to use those elements. But i dont know how to access individual elements of the list using these API? or am I missing something in interface file?
UPDATED:
Is typemap possible to return the list as array here??
First of all, general info
This tutorial shows how to do the wrapper for templates.
The same tutorial shows how to use the module from Perl, but the perl example doesn't touch templates.
This SO article shows how to do that with a Vector
Here's a general SWIG STL documentation that seems to mention std_list.i interface.
Second, regarding lists
You can not "access" C++ list like a Perl array, by a subscript. If you wanted that, you must use a Vector as underlying type.
As an alternate, create a class extending List, give it a new method which returns an element by an index, and expose that method in an interface.
If you wish to access the list by finding an element, like in C++, you need to write a List interface that exposes find() method - the default one does not from reading the source code.
In your interface, try:
%include "std_list.i"
%template(ListStruct1) std::list< Struct1 * >;
The std library is kinda funny, there's no actual binary object called list that swig can just wrap, it's all templates - so swig needs some extra help to figure out what's going on.
That should add insert, remove, and a bunch of other list specific functions to the wrapper.
If the above doesn't work, try adding:
%define SWIG_EXPORT_ITERATOR_METHODS
UPDATE: Of course, I neglected to mention (or even realize) that this works great for python, java, and a few others, but is totally broken in perl...

Defining operators in Boo

I'm looking to move some of my lighter weight metaprogramming from Nemerle to Boo and I'm trying to figure out how to define custom operators. For example, I can do the following in Nemerle:
macro #<-(func, v) {
<[ $func($v) ]>
}
Then these two are equivalent:
foo <- 5;
foo(5);
I can't find a way of doing this in Boo -- any ideas?
While Boo supports operator overloading by defining the appropriate static operator function (op_addition), and also supports syntactic macros, it does not support creating custom operators at this time.
I'm not sure if this is exactly what you need but you can create syntactic macros in Boo. There's some information on the CodeHaus site, http://boo.codehaus.org/Syntactic+Macros, but the syntax has changed in one of the recent releases. I don't know of any tutorials on the new syntax but the source release for Boo 0.8.2 has some examples (some of the language structures are implemented as macros). If you don't want to download the full source a view of the SVN repository is available, https://svn.codehaus.org/boo/boo/trunk/src/Boo.Lang.Extensions/Macros/. The assert macro would be a good place to start.
HTH
Stoo