Runtime evaluation: Difference between revisions
Content added Content deleted
(I'm pretty sure Java can't do this) |
(Updated to reflect requirements.) |
||
Line 198: | Line 198: | ||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
{{incorrect|Slate|It does not discuss passing in or returning values, or the environment the expression is evaluated in., and it does not show taking in an arbitrary program as from user input.}} |
|||
Here is some code in Slate that uses run-time evaluation. |
|||
In Slate, programs are represented as Syntax Node trees, with methods defined on the various syntactic types. The backtick syntax provides a convenient quoting mechanism, and as objects, they have convenient methods defined for evaluation or evaluation within a specific environment: |
|||
<lang slate> |
<lang slate> |
||
`(4 + 5) evaluate. |
|||
w@(Gtk Workspace traits) evaluateSelected [ |
|||
`(4 + 5) evaluateIn: prototypes. |
|||
| selection parser result | |
|||
</lang> |
|||
You can also explicitly invoke the Parser on a String, to convert it into syntactic objects: |
|||
selection: w selectedTextOrCurrentLine. |
|||
<lang slate> |
|||
parser: (Syntax Parser newOn: selection reader). |
|||
(Syntax Parser newOn: '4 + 5') upToEnd do: [| :each | print: each evaluate] |
|||
[ parser isAtEnd ] whileFalse: [ |
|||
result: (parser next evaluateIn: w namespace) |
|||
]. |
|||
result |
|||
]. |
|||
</lang> |
</lang> |
||
You can construct a program using externally-specified values using <tt>`unquote</tt> within a quoted expression: |
|||
<lang slate> |
|||
define: #x -> 4. |
|||
`(x `unquote + 5) evaluate. |
|||
</slate> |
|||
Or you can obviously construct a string: |
|||
<lang slate> |
|||
define: #x -> 4. |
|||
(Syntax Parser newOn: x printString ; ' + 5') |
|||
</lang> |
|||
The <tt>evaluate</tt> method also takes into consideration the current lexical scope, unless another environment is specified. The following returns 10, no matter what binding <tt>x</tt> has in the local namespace: |
|||
<lang slate> |
|||
[| x | x: 5. `(x `unquote + 5) evaluate] do. |
|||
</lang> |
|||
Slate can sandbox via constructing a fresh namespace and evaluating within it, but this mechanism is not strongly secure yet. |
|||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |