printf symbol name and value - eval

Suppose somewhere I have defined several symbols:
#lang racket
(define foo 123)
(define bar '("1" "2" "3"))
I need a way to produce a string like "foo = 123" or "bar = '("1" "2" "3")". I wrote a function for that:
(define (f2 sy)
(format "~a = ~s" sy (eval sy)))
This function works in the interpretator window pretty well.
> (f2 'foo)
"foo = 123"
> (f2 'bar)
"bar = (\"1\" \"2\" \"3\")"
That is quite satisfactory for me. However, when I use it in the code, I get
foo: unbound identifier;
also, no #%top syntax transformer is bound in: foo
I have a feeling that I am doing something wrong. Can you please suggest the right way to solve my problem?
P.S.: I am using DrRacket, version 5.3.1

First of all, eval should really only be used as a last resort in Racket. It makes your program less efficient and harder to understand. The right way to do this is probably to write a macro such as the following:
(define-syntax-rule (f2 sy)
(format "~a = ~s" (quote sy) sy))
(define foo 2)
(f2 foo)
This macro just substitutes the name of the variable you want to lookup into the format expression in the body. The quote turns the variable name into a symbol you can print. This macro doesn't work as a procedure, because (f2 foo) would deference foo before you can quote and print its name.
Note: the reason why your eval doesn't work as expected is because eval always evaluates with respect to a namespace, which dictates what is in scope. The default namespace within a module has nothing in it, so eval can't see foo or anything else. You can read more about namespaces in the Guide.

Another solution, also inspired by Asumu Takikawa uses the trick described in the guide:
(define-namespace-anchor a)
(define ns (namespace-anchor->namespace a))
(define (f2 sy)
(format "~a = ~s" sy (eval sy ns)))
On the contrast to the solution with macros, this function can be mapped.

Related

Coq VST Internal structure copying

run into a problem with VST(Verified Software Toolchain) 2.5v library for Coq 8.10.1:
Got an error with the latest working commit of VST namely "Internal structure copying is not supported".
Minimal example:
struct foo {unsigned int a;};
struct foo f() {
struct foo q;
return q; }
On starting proof got an error:
Error: Tactic failure: The expression (_q)%expr contains internal structure-copying, a feature of C not currently supported in Verifiable C (level 97).
This is due to the check_normalized in floyd/forward.v :
Fixpoint check_norm_expr (e: expr) : diagnose_expr :=
match e with
| Evar _ ty => diagnose_this_expr (access_mode ty) e
...
So, the questions are:
1) What suggested workarounds exists?
2) What is the reason for this limitation?
3) Where can I get a list of unsupported features?
1) The workaround is to change your C program to copy field by field.
2) The reason is the absurdly complicated and target-ISA-dependent implementation/semantics of C's structure-copying, especially in parameter passing and function-return.
3) The first 10 lines of Chapter 4 ("Verifiable C and clightgen") of the reference manual has a short list of unsupported features, but unfortunately struct-by-copy is not on that list. That's a bug.

Variable arity functions in Racket/C FFI

Declaring functions with Racket's FFI is simple enough to do with _fun and define-ffi-definer. (A tutorial can be found on the PRL blog) For example, I can make a binding for atoi:
#lang racket
(require ffi/unsafe
ffi/unsafe/define)
(define-ffi-definer define-libc #f)
(define-libc atoi (_fun _string -> _int))
And now I can call atoi with Racket strings:
> (atoi "5")
5
The problem now is, how do I call C functions with a variable arity, such as printf, who's signature is:
int printf(const char *format, ...);
I would guess that (since the linking happens dynamically), the Racket code should have a 'rest' argument at the end, which takes an array (pointer) for the rest of the arguments, that is either null terminated or (more likely), indicated by yet another argument. However, I can't think of any good ways to test this.
So, how do you handle variable arity functions with the Racket-C FFI?
Look at this solution c-printf:
(provide c-printf)
(define interfaces (make-hash))
(define (c-printf fmt . args)
(define itypes
(cons _string
(map (lambda (x)
(cond [(and (integer? x) (exact? x)) _int]
[(and (number? x) (real? x)) _double*]
[(string? x) _string]
[(bytes? x) _bytes]
[(symbol? x) _symbol]
[else (error 'c-printf
"don't know how to deal with ~e" x)]))
args)))
(let ([printf (hash-ref interfaces itypes
(lambda ()
;; Note: throws away the return value of printf
(let ([i (get-ffi-obj "printf" #f
(_cprocedure itypes _void))])
(hash-set! interfaces itypes i)
i)))])
(apply printf fmt args)))

passing unevaluated expressions to C/C++

I'd like to pass a variable number of arguments from a function to C/C++, but would like to leave the arguments unevaluated and at the same time don't want to do any computations in R (aside from calling the C/C++ function), i.e. I don't want to call substitute in my R function. One option for this that I thought I could use is .External and doing smth like this:
R_fn = function(...) .External("cpp_fn", ...)
...
# and in C code:
SEXP cpp_fn (SEXP arglist) {
}
However .External is evaluating arguments in ..., so if I try something like
rm(x, y) # just making sure these don't exist
R_fn(x*y)
I get an error because R is trying to evaluate x*y before sending it to the function.
To contrast, the following works in R:
f = function(...) g(...)
g = function(x, ...) print(substitute(x))
f(x*y*z)
# x * y * z
What other options do I have? Clearly it's possible to do as R itself does it for a number of functions, e.g. substitute itself, but I don't understand how to do it. I added the rcpp tag because my eventual usage of this is going to be in Rcpp.
One possibility is to do what match.call does (thanks to Ricardo Saporta for pointing me in that direction). This requires copy-pasting a few definitions from R source code that I won't do here, but the basic idea is to get the calling function from R_GlobalContext and then extract the function arguments from there. The rough sketch is as follows:
R_fn = function(...) .Call("cpp_fn")
// and in C++ code
Language cpp_fn() {
SEXP sysp = ((RCNTXT*)R_GlobalContext)->sysparent;
RCNTXT *cptr = (RCNTXT*)R_GlobalContext;
while (cptr != NULL) {
if (cptr->callflag & CTXT_FUNCTION && cptr->cloenv == sysp)
break;
cptr = cptr->nextcontext;
}
cptr = cptr->nextcontext; // because this is called from .Call and not from R_fn
// and now cptr->promargs has the unevaluated arguments to do as one pleases
// e.g.
Language firstArg(R_PromiseExpr(CAR(cptr->promargs)));
return firstArg;
}

Watch out for C function names with R code

So here is something a bit crazy.
If you have some C code which is called by an R function (as a shared object), try adding this to the code
void warn() {
int i; // just so the function has some work, but you could make it empty to, or do other stuff
}
If you then call warn() anywhere in the C code being called by the R function you get a segfault;
*** caught segfault ***
address 0xa, cause 'memory not mapped'
Traceback:
1: .C("C_function_called_by_R", as.double(L), as.double(G), as.double(T), as.integer(nrow), as.integer(ncolL), as.integer(ncolG), as.integer(ncolT), as.integer(trios), as.integer(seed), as.double(pval), as.double(pval1), as.double(pval2), as.double(pval3), as.double(pval4), as.integer(ntest), as.integer(maxit), as.integer(threads), as.integer(quietly))
2: package_name::R_function(L, G, T, trios)
3: func()
4: system.time(func())
5: doTryCatch(return(expr), name, parentenv, handler)
6: tryCatchOne(expr, names, parentenv, handlers[[1L]])
7: tryCatchList(expr, classes, parentenv, handlers)
8: tryCatch(expr, error = function(e) { call <- conditionCall(e) if (!is.null(call)) { if (identical(call[[1L]], quote(doTryCatch))) call <- sys.call(-4L) dcall <- deparse(call)[1L] prefix <- paste("Error in", dcall, ": ") LONG <- 75L msg <- conditionMessage(e) sm <- strsplit(msg, "\n")[[1L]] w <- 14L + nchar(dcall, type = "w") + nchar(sm[1L], type = "w") if (is.na(w)) w <- 14L + nchar(dcall, type = "b") + nchar(sm[1L], type = "b") if (w > LONG) prefix <- paste(prefix, "\n ", sep = "") } else prefix <- "Error : " msg <- paste(prefix, conditionMessage(e), "\n", sep = "") .Internal(seterrmessage(msg[1L])) if (!silent && identical(getOption("show.error.messages"), TRUE)) { cat(msg, file = stderr()) .Internal(printDeferredWarnings()) } invisible(structure(msg, class = "try-error", condition = e))})
9: try(system.time(func()))
10: .executeTestCase(funcName, envir = sandbox, setUpFunc = .setUp, tearDownFunc = .tearDown)
11: .sourceTestFile(testFile, testSuite$testFuncRegexp)
12: runTestSuite(testSuite)
aborting ...
Segmentation fault (core dumped)
(END)
Needless to say the code runs fine if you call the same function from a C or C++ wrapper instead of from an R function. If you rename warn() it also works fine.
Any ideas? Is this a protected name/symbol? Is there a list of such names? I'm using R version 2.14.1 on Ubuntu 12.01 (i686-pc-linux-gnu (32-bit)). C code is compiled with GNU GCC 4.6.3.
This seems like quite an interesting question. Here's my minimal example, in a file test.c I have
void warn() {}
void my_fun() { warn(); }
I compile it and then run
$ R CMD SHLIB test.c
$ R -e "dyn.load('test.so'); .C('my_fun')"
With my linux gcc version 4.6.3., the R output is
> dyn.load('test.so'); .C('my_fun')
R: Success
list()
with that "R: Success" coming from the warn function defined in libc (see man warn, defined in err.h). What happens is that R loads several dynamic libraries as a matter of course, and then loads test.so as instructed. When my_fun gets called, the dynamic linker resolves warn, but the rules of resolution are to search globally for the warn symbol, and not just in test.so. I really don't know what the global search rules are, perhaps in the order the .so's were opened, but whatever the case the resolution is not where I was expecting.
What is to be done? Specifying
static void warn() {}
forces resolution at compile time, when the .o is created, and hence avoiding the problem. This wouldn't work if, for instance, warn was defined in one file (utilities.c) and my_fun in another. On Linux dlopen (the function used to load a shared object) can be provided with a flag RTLD_DEEPBIND that does symbol resolution locally before globally, but (a) R does not use dlopen that way and (b) there are several (see p. 9) reservations with this kind of approach. So as far as I can tell the best practice is to use static where possible, and to carefully name functions to avoid name conflicts. This latter is not quite as bad as it seems, since R loads package shared objects such that the package symbols themselves are NOT added to the global name space (see ?dyn.load and the local argument, and also note the OS-specific caveats).
I'd be interested in hearing of a more robust 'best practice'.

Search and replace in C source code, without touching comments

I have a lot of c code in which I would like to replace old syntax style with a new style. E.g. the following prefixes "si":
int siName;
should become "i":
int iName;
But the reg-expression or other find/replace tool, should not touch any source code comments.
Any solution?
You can try out coccinelle. It has a bit of a learning curve, but it parses the C code and executes the transformations given to it in a script. For example, for renaming a function from foo to bar, the script would look like this (from here):
##
##
-foo()
+bar()
It can probably rename variables based on regular expressions as well, I haven't yet found out a way though.
In vi use
:%s/\<Oldword\>/Newword/gc
This asks you whether or not to replace a particular occurrence of the whole word which you may happily neglect if it is a part of the comment.
With respect to the suggestion about Coccinelle, you can match using regular expressions using the following notation:
identifier foo =~ "xxx";
That is, foo will match any identifier that contains xxx. PCRE regular expressions are supported.
You can also use python to create a new identifier:
#a#
identifier x;
##
foo(x)
#script:python b#
x << a.x;
xx;
##
coccinelle.xx = "%s%s" % (x,x)
##
identifier a.x;
identifier b.xx;
##
foo(
- x
+ xx
)
For the program:
int main () {
foo(one);
}
This gives
int main () {
foo(oneone);
}

Resources