How to execute code from a string variable in Crystal? - eval

I like eval in Ruby because it works pretty straightforward:
eval("puts 7 * 8") # => 56
What is an eval's equivalent in Crystal ? I know that we can do something similar with macro:
macro eval(code)
{{code.id}}
end
eval("puts 7 * 8") # => 56
But this won't work with runtime values:
a = "yo"
eval("puts #{a}") # => prints nothing

Crystal is a compiled language, while Ruby is interpreted. That makes evaluating code at runtime much more complicated.
In your example, the macro is expanded at compile time, so actually your program is just puts 7 * 8. In other words, it works because the code is known at compile time.
But if you wanted to execute the code contained in an arbitrary string, it would have to invoke the Crystal compiler and then execute the resulting executable. This is actually something we do in the Crystal unit tests. But there is no "eval" function included in the standard library because that would imply that your compiled program includes the Crystal compiler built in and it actually doesn't make much sense.
Another problem is how to pass arguments and take return values. Since the program you're running and the evaluated code are the result of different compilations, they might have different binary representations of the same types.
On the other hand, using eval in Ruby is usually known as a bad practice and must be avoided if possible.

waj, one of the developers of the Crystal language, wrote in 2015
because that would imply that your compiled program includes the Crystal compiler built in and it actually doesn't make much sense.
But, including the interpreter in the executable may not be such a crazy idea in 2022. Anyolite can include mruby or CRuby in the executable.
https://github.com/Anyolite/anyolite
kitty.cr
require "anyolite"
code = ARGV[0]
class Kitty
def initialize(#n : Int32)
end
def mew
puts "mew " * #n
end
end
Anyolite::RbInterpreter.create do |rb|
Anyolite.wrap(rb, Kitty)
Anyolite.eval(code)
end
build:
crystal build kitty.cr
run:
./kitty "Kitty.new(3).mew"
output:
mew mew mew
The generated executable is about 7MB larger (probably because it contains mruby). However, that is not a problem considering the advantage of being able to eval with Crystal. Yes, eval may be a bad practice. But I think there are cases where it can be very useful.

Related

Stata: Call a do file containing loop from a program in the other do file

I am trying to call a do file which has loops from a program in other do file. I am getting an error.
Now, if I use do instead of include, it runs fine but I don't get to use local macros created. I used include so I can use the macros further in the program. I don't want to use global.
First do file (test.do).
forval i = 1/5 {
local val`i' = `i'
}
Second do file(call-test.do)
capture program drop test
program test
include "test.do"
di `val1'
end
test
I got error r(9611);
I using version 16.1
Response from Stata support
The -include- is designed to let you share definitions. It will not
work correctly within a program as documented in -help include-
The short answer is that -include- is usually ok to use in programs,
but not with looping commands, and if you use -include- in a program,
it probably isn't working the way you think it is.
Here's the long version of exactly what is going on:
When you use -include- in a program, your program literally includes
the -include- command in it. The program does NOT have the contents
of the include file substituted in place. That's the start of the
problem for looping commands.
In any case, when a program executes the -include- command, Stata gets
confused about whether to define a loop program on the behalf of a
looping command globally or within the program, and things go downhill
from there. Given how the code is structured, it is unlikely we could
fix -include- to behave differently, so our documentation really
should simply recommend against using -include- in programs. In
addition, at the point at which the failure occurs, Stata simply knows
that it cannot call a program that it thinks should already be in
memory, hence the 9611 return code. It has no idea at that point that
this was because it was called with -include-, unfortunately.
We could in the future introduce a true C-like "#include" for use in
programs which would simply substitute in-line the lines from whatever
was included into your program

Calculate an arbitrary type's size without executing a program

Given any type in a C program, I would like to know it's size, such as one would when executing the following line,
printf("%d\n",sizeof(myType));
without actually executing the program. The solution must work with arbitrary types whose size can be determined at compile time, such as user-defined structs.
The rationale is that, if it can be known at compile time, there should be a way to extract that information without having to run the program. Possibly something a bit more elegant than having to parse the resulting assembler source or binary for literal contstants, but if that's the only way, I'll take what I can get.
This question doesn't quite work for me, since OP's solution relies on executing the code, and the most voted answer relies on the preprocessor info directive actually expanding macros (my toolchain doesn't apparently).
For background, I'm developing for PIC18 MCUs and using the XC8 compiler.
What I ultimately want is to verify that some structures I've defined take up their expected size in memory.
This is a classic use case for static assertions. If your compiler supports _Static_assert, you can write
_Static_assert(sizeof(mystruct) == expected_size, "Invalid struct size.");
demo 1
If you use an older compiler that does not support C-1x yet, use a common work-around that relies on declaring an array type with negative size:
#define CHECK_SIZE(x,e) if(sizeof(char[2*(sizeof(x)==e)-1])==1);
demo 2

Is there any design tools that I can get the exact number of instructions of different functions in C code

I need to analyze some c code with functions and I want to get the exact number of instructions of different function in c code. I have no idea. Thanks.
If you're talking about assembly instructions, this is pretty easy:
Make a small C program with main. Immediately in main, call your desired function. Compile with the gcc -c option (outputs an object file). Open up your object f ile (.o) in a text editor. Look for t he call function (This is the call into the function). Start counting the lines until you hit a return (ret) instruction.
There you go! Of course, your compiler will probably optimize this object code so it might be a little more complex, but this is probably a really easy way to do it.

Testcases for a C interpreter

I would like to test a little ANSI C interpreter.
My tool interprets my C program. It doesn't produce machine code; and I can't access the heap/stack after execution!
I was thinking of validating return values / outputs against GCC or something like this.
I was searching for something that fits for me, but i hardly found anything FREE or open source.
Does anybody have an idea/suggestion how to test my interpreter?
Can anybody recommend something like a test suite; or a package of test cases?
I also wrote a C interpreter and mainly relied on the gcc.c - torture/execute test cases. This test suite consists of "code fragments which have historically broken easily". The advantage of this test cases is, that they have to be executed to provide a result (and not, e.g., only compiled) and then the result is matched to an expected result. You do not need to compare it with the result of an executed program, that was compiled by GCC. You basically just need to include the files in the directory and execute them which contrasts some other test suites, where you have to parse expected results from configuration files or similar. You can download the tests from the GCC repository.
One disadvantage for you might be, that the test cases are often extensive and can also include GNU extensions such as the asm statement for executing assembler code or attributes on how to align memory content. They also include some test cases for some old K&C function style notation like in the following example (not taken from the suite):
int func(a)
int a;
{
return a + 1;
}
However, I still would recommend you to look through the test cases and see what you can execute, as they also test many "normal" corner cases for ASNI C.

C - How to get a user defined function and turn it into a pointer?

I would like to know if there is any way of getting a user defined function (with two variables) from stdin in mathematical form and turn it into a function pointer. In other words, what I want to do is run:
> ./program a*b
Program turns that into a pointer of a function that returns:
return a*b;
So, the output of program is
user_defined_function(int)(int)
which would then be part of a much larger program.
I would post some code if I had any idea of how to tackle this problem, but I don't... I just need help with the step of turning the user defined function into a function pointer, since I know how to turn the user defined function into a C function.
There is no simple solution to that since you would have to generate code.
Simples solution that comes to my mind for this:
generate a C file from within your programm that only has one function, inserting the command line argument as return statement
give the function a known or generated name
exec the compiler and generate a shared library
dynamically load that shared library
call the known function
I fear it doesn't get any simpler than that.
The other solution would be to write/ use an expression parser and parse the math expression and than evaluate at runtime...
Just for fun, here is a link to CINT
CINT is an interpreter for C and C++ code...
... A CINT script can call compiled classes/functions and compiled code can make callbacks to CINT interpreted functions ...
I'm not saying this is a "good" solution (and in fact it may be very "bad" in cases!), but some people have already put a good bit of effort -- "slightly less than 400,000 lines of code" -- into this project ;-)
Happy coding.
This is very hard to do in C because it is a compiled language. You could do what Mario The Spoon is suggesting, or you could switch to a dynamic language like ruby or javascript. These languages have an "eval" method that takes a string and executes the code inside the string, and they have the ability to dynamically define functions.
What you're proposing is entirely possible, you simply write code which transforms user text into machine code. This is called a compiler. gcc would be much like your program, if it ran the code it generated.

Resources