Runtime Evaluation: the eval Expression

Sometimes it is convenient to able to evaluate expressions that are dynamically constructed at runtime. For instance, consider the problem of implementing a database of mathematical objects in Magma. Suppose that these mathematical objects are very large, but can be constructed in only a few lines of Magma code (a good example of this would be Magma's database of best known linear codes). It would be very inefficient to store these objects in a file for later retrieval; a better solution would be to instead store a string giving the code necessary to construct each object. Magma's eval feature can then be used to dynamically parse and execute this code on demand.

eval expression
The eval expression works as follows: first, it evaluates the given expression, which must evaluate to a string. This string is then treated as a piece of Magma code which yields a result (that is, the code must be an expression, not a statement), and this result becomes the result of the eval expression.

The string that is evaluated can be of two forms: it can be a Magma expression, e.g., "1+2", "Random(x)", or it can be a sequence of Magma statements. In the first case, the string does not have to be terminated with a semicolon, and the result of the expression given in the string will be the result of the eval expression. In the second case, the last statement given in the string should be a return statement; it is easiest to think of this case as defining the body of a function.

The string that is used in the eval expression can refer to any variable that is in scope during the evaluation of the eval expression. However, it is not possible for the expression to modify any of these variables.

Example State_eval1 (H1E17)

In this example we demonstrate the basic usage of the eval keyword.
> x := eval "1+1";  // OK
> x;
2
> eval "1+1;"; // not OK
2
>> eval "1+1;"; // not OK
   ^
Runtime error: eval must return a value
> eval "return 1+1;"; // OK
2
> eval "x + 1"; // OK
3
> eval "x := x + 1; return x";
>> eval "x := x + 1; return x";
   ^
In eval expression, line 1, column 1:
>> x := x + 1; return x;
   ^
    Located in:
    >> eval "x := x + 1; return x";
       ^
User error: Imported environment value 'x' cannot be used as a local

Example State_eval2 (H1E18)

In this example we demonstrate how eval can be used to construct Magma objects specified with code only available at runtime.
> M := Random(MatrixRing(GF(2), 5));
> M;
[1 1 1 1 1]
[0 0 1 0 1]
[0 0 1 0 1]
[1 0 1 1 1]
[1 1 0 1 1]
> Write("/tmp/test", M, "Magma");
> s := Read("/tmp/test");
> s;
MatrixAlgebra(GF(2), 5) ! [ GF(2) | 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1,
1, 0, 1, 1, 1, 1, 1, 0, 1, 1 ]
> M2 := eval s;
> assert M eq M2;
V2.28, 13 July 2023