Experiment: Macro Expansion(v2 · en)
A macro receives unevaluated code and returns data convertible back into expressions; only the expansion result enters evaluation. This experiment uses macroexpand-1 to observe "expansion" and "evaluation" separately: expansion is a data transformation; evaluation is what produces values (see the "code is data" section of Values and Expressions).
Steps
Step 1: Define a macro and expand once (without evaluating)
Define twice, then expand without executing:
(defmacro twice [e] `(+ ,e ,e))
(println (macroexpand-1 '(twice 3)))
Expected observation: stdout is (+ 3 3). What macroexpand-1 returns is data — a list; the argument 3 was spliced into the template, but no addition has happened. The expander captures no call-site locals and performs no evaluation at this point.
Step 2: Only the expansion result enters evaluation
Apply the same macro at a call position:
(println (twice 6))
Expected observation: stdout is 12. The evaluator sees the equivalent of Step 1's expansion (+ 6 6) — the macro rewrites code before evaluation, and the two occurrences of 6 mean it will be evaluated twice (here a pure expression, no side effects).
Step 3: The branch that was not expanded never runs
Prove with a syntax-rules macro that "an expression left out of the expansion is not evaluated":
(defmacro choose-first (syntax-rules () ((_ x y) x)))
(println (choose-first 7 (/ 1 0)))
Expected observation: stdout is 7, with no division-by-zero error and exit code 0. (/ 1 0) never entered evaluation — the macro expansion discarded it. Were (choose-first 7 (/ 1 0)) an ordinary function call, its arguments would evaluate before the call and the division would necessarily happen; that is precisely the line between macros and functions.
步骤总览
| 步骤 | 预期观察 |
|---|---|
| Step 1: Define a macro and expand once (without evaluating) | stdout is =(+ 3 3)=. What =macroexpand-1= returns is *data* — a list; the argument =3= was spliced into the template, but no addition has happened. The expander captures no call-site locals and performs no evaluation at this point. |
| Step 2: Only the expansion result enters evaluation | stdout is =12=. The evaluator sees the equivalent of Step 1's expansion =(+ 6 6)= — the macro rewrites code *before* evaluation, and the two occurrences of =6= mean it will be evaluated twice (here a pure expression, no side effects). |
| Step 3: The branch that was not expanded never runs | stdout is =7=, with no division-by-zero error and exit code 0. =(/ 1 0)= never entered evaluation — the macro expansion discarded it. Were =(choose-first 7 (/ 1 0))= an ordinary function call, its arguments would evaluate before the call and the division would necessarily happen; that is precisely the line between macros and functions. |
无 JS 执行会话
下面的原生表单创建一个执行会话(服务端 P6-b runner 子进程求值,本页进程不执行用户代码);会话页内逐步运行、查看观察、重置或关闭。
JSON API 同一能力走 POST /api/experiments;两条路径共用同一 runner 合同。