fromscratch-pycpu 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fromscratch_pycpu-0.1.0.dist-info/METADATA +232 -0
- fromscratch_pycpu-0.1.0.dist-info/RECORD +47 -0
- fromscratch_pycpu-0.1.0.dist-info/WHEEL +4 -0
- fromscratch_pycpu-0.1.0.dist-info/entry_points.txt +2 -0
- fromscratch_pycpu-0.1.0.dist-info/licenses/LICENSE +21 -0
- pycpu/__init__.py +11 -0
- pycpu/__main__.py +68 -0
- pycpu/_version.py +24 -0
- pycpu/arithmetic.py +176 -0
- pycpu/assembler.py +580 -0
- pycpu/circuit.py +359 -0
- pycpu/cockpit/__init__.py +8 -0
- pycpu/cockpit/app.py +545 -0
- pycpu/cockpit/code.py +161 -0
- pycpu/cockpit/examples/countdown.pebble +7 -0
- pycpu/cockpit/examples/divide-by-zero.pebble +7 -0
- pycpu/cockpit/examples/factorial.pebble +9 -0
- pycpu/cockpit/examples/greeting.pebble +4 -0
- pycpu/cockpit/examples/times-table.pebble +6 -0
- pycpu/cockpit/examples/tour.pebble +31 -0
- pycpu/cockpit/explain.py +660 -0
- pycpu/cockpit/page.html +1261 -0
- pycpu/cockpit/picture.py +470 -0
- pycpu/cockpit/session.py +778 -0
- pycpu/cockpit/walks/a-call-and-the-stack.toml +47 -0
- pycpu/cockpit/walks/many-instructions.toml +39 -0
- pycpu/cockpit/walks/subtracting-with-gates.toml +39 -0
- pycpu/cockpit/walks/where-n-lives.toml +39 -0
- pycpu/cockpit/walks/why-the-clock-ticks.toml +50 -0
- pycpu/cockpit/walks.py +518 -0
- pycpu/computer.py +175 -0
- pycpu/cpu.py +648 -0
- pycpu/cpu_parts.py +140 -0
- pycpu/fast.py +320 -0
- pycpu/isa.py +243 -0
- pycpu/logic.py +222 -0
- pycpu/memory.py +268 -0
- pycpu/proof.py +263 -0
- pycpu/py.typed +0 -0
- pycpu/simulator.py +361 -0
- pycpu/state.py +146 -0
- pycpu/translator/__init__.py +29 -0
- pycpu/translator/codegen.py +493 -0
- pycpu/translator/program.py +211 -0
- pycpu/translator/runtime.py +166 -0
- pycpu/translator/subset.py +688 -0
- pycpu/view.py +55 -0
pycpu/cockpit/page.html
ADDED
|
@@ -0,0 +1,1261 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>The Cockpit - PyCPU</title>
|
|
7
|
+
<link rel="icon" href="data:,">
|
|
8
|
+
<style>
|
|
9
|
+
:root { --bg:#f6f6fa; --fg:#1d1d27; --card:#fff; --line:#d5d5e0; --accent:#5e35b1; --hot:#ffb300; --hotfg:#201600; --muted:#5d5d70; --here:#ede7f6; --shade:#f3f0f9; --picked:#00897b; --error:#c62828; --look:#00897b; --cheer:#2e7d32; --one:#cfe3ff; --onefg:#0b2a55; }
|
|
10
|
+
@media (prefers-color-scheme: dark) {
|
|
11
|
+
:root { --bg:#17171f; --fg:#ececf4; --card:#222230; --line:#3a3a4e; --accent:#b39ddb; --hot:#ffb300; --hotfg:#201600; --muted:#a4a4b8; --here:#33294d; --shade:#29243a; --picked:#4db6ac; --error:#ef9a9a; --look:#4db6ac; --cheer:#81c784; --one:#29466e; --onefg:#e3eeff; }
|
|
12
|
+
}
|
|
13
|
+
* { box-sizing:border-box; }
|
|
14
|
+
body { margin:0; overflow:hidden; font:15px/1.45 system-ui, sans-serif; background:var(--bg); color:var(--fg); }
|
|
15
|
+
/* Layout C: the bars on top, then your program on the left and the magnifying glass on the right. */
|
|
16
|
+
main { height:100vh; display:grid; grid-template-rows:auto auto auto minmax(0,1fr); gap:.45rem; padding:.5rem .75rem; }
|
|
17
|
+
h1 { margin:0 0 .4rem; font-size:1.4rem; } h2 { margin:0 0 .3rem; font-size:1rem; } h3 { margin:0 0 .2rem; font-size:.85rem; text-transform:uppercase; letter-spacing:.03em; color:var(--muted); }
|
|
18
|
+
p { margin:.2rem 0; }
|
|
19
|
+
.muted { color:var(--muted); }
|
|
20
|
+
.row { display:flex; flex-wrap:wrap; gap:.4rem; align-items:center; }
|
|
21
|
+
.spacer { flex:1 1 auto; }
|
|
22
|
+
.bar { display:flex; flex-wrap:wrap; gap:.35rem .5rem; align-items:center; }
|
|
23
|
+
.brand { font-weight:700; margin-right:.3rem; }
|
|
24
|
+
input, select, textarea, button { font:inherit; padding:.25rem .55rem; border:1px solid var(--line); border-radius:6px; background:var(--bg); color:var(--fg); }
|
|
25
|
+
textarea { font-family:ui-monospace,monospace; font-size:.85rem; width:100%; min-height:9rem; }
|
|
26
|
+
input[type=number] { width:5.5rem; }
|
|
27
|
+
button { background:var(--accent); color:var(--bg); cursor:pointer; border-color:var(--accent); }
|
|
28
|
+
button:disabled { opacity:.45; cursor:not-allowed; }
|
|
29
|
+
button.quiet { background:transparent; color:var(--accent); border-color:var(--line); }
|
|
30
|
+
button.go { font-weight:700; }
|
|
31
|
+
[hidden] { display:none !important; }
|
|
32
|
+
.lamp { border:1px solid var(--line); border-radius:999px; padding:.05rem .6rem; font-size:.8rem; }
|
|
33
|
+
/* A 1 on a wire or a lamp is blue; only a change glows in the hot colour. */
|
|
34
|
+
.lamp.on, .wire.on { background:var(--one); color:var(--onefg); border-color:var(--one); }
|
|
35
|
+
.card { background:var(--card); border:1px solid var(--line); border-radius:8px; padding:.45rem .7rem; }
|
|
36
|
+
#walk-bar { border-left:4px solid var(--accent); }
|
|
37
|
+
#walk-say { font-size:1.05rem; }
|
|
38
|
+
#walk-say.dim, .dim { opacity:.55; }
|
|
39
|
+
.cheer { color:var(--cheer); font-weight:700; }
|
|
40
|
+
#said p { margin:0; }
|
|
41
|
+
#error { color:var(--error); font-weight:600; }
|
|
42
|
+
.panes { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); grid-template-areas:"program glass"; gap:.6rem; min-height:0; }
|
|
43
|
+
.pane { background:var(--card); border:1px solid var(--line); border-radius:8px; padding:.6rem .75rem; min-height:0; min-width:0; }
|
|
44
|
+
#program { grid-area:program; display:flex; flex-direction:column; gap:.5rem; }
|
|
45
|
+
#glass { grid-area:glass; }
|
|
46
|
+
#walks { grid-column:1 / -1; grid-row:1 / -1; }
|
|
47
|
+
#program, #glass, #walks, #expert { overflow:auto; }
|
|
48
|
+
#code { flex:1 1 auto; min-height:4rem; overflow:auto; border:1px solid var(--line); border-radius:6px; }
|
|
49
|
+
#boxes { flex:0 0 auto; display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:.5rem; max-height:40%; min-height:0; }
|
|
50
|
+
.box { overflow:auto; min-height:0; border:1px solid var(--line); border-radius:6px; padding:.3rem .45rem; }
|
|
51
|
+
#expert { position:fixed; z-index:5; top:.5rem; right:.75rem; bottom:.75rem; width:min(27rem, calc(100vw - 1.5rem)); box-shadow:0 6px 30px rgba(0,0,0,.25); }
|
|
52
|
+
#expert h3 { margin-top:.7rem; }
|
|
53
|
+
table { border-collapse:collapse; width:100%; font-family:ui-monospace,monospace; font-size:.85rem; }
|
|
54
|
+
td { text-align:left; padding:.05rem .4rem; vertical-align:top; white-space:pre; }
|
|
55
|
+
td.mark { width:1.4rem; color:var(--accent); font-weight:700; }
|
|
56
|
+
td.num { width:2.5rem; color:var(--muted); text-align:right; }
|
|
57
|
+
tr.here td { background:var(--here); font-weight:700; }
|
|
58
|
+
tr.sub td { background:var(--shade); font-size:.8rem; }
|
|
59
|
+
tr.sub.next td { font-weight:700; }
|
|
60
|
+
tr.clickable { cursor:pointer; }
|
|
61
|
+
.changed { background:var(--hot) !important; color:var(--hotfg) !important; border-color:var(--hot) !important; }
|
|
62
|
+
tr.changed td { background:var(--hot); color:var(--hotfg); }
|
|
63
|
+
.tag { font-family:system-ui, sans-serif; font-size:.68rem; font-weight:700; text-transform:uppercase; letter-spacing:.03em; margin-left:.35rem; }
|
|
64
|
+
.look-here { outline:3px solid var(--look); outline-offset:2px; border-radius:6px; }
|
|
65
|
+
#output { font-family:ui-monospace,monospace; white-space:pre-wrap; margin:0; }
|
|
66
|
+
nav#trail { display:flex; flex-wrap:wrap; gap:.25rem; align-items:center; margin-bottom:.5rem; }
|
|
67
|
+
nav#trail button { background:transparent; color:var(--accent); border-color:var(--line); padding:.1rem .45rem; font-size:.85rem; }
|
|
68
|
+
nav#trail button[aria-current] { background:var(--here); color:var(--fg); font-weight:700; }
|
|
69
|
+
#playing-note { font-weight:600; padding:1rem; text-align:center; border:2px dashed var(--line); border-radius:8px; }
|
|
70
|
+
.big { font-family:ui-monospace,monospace; font-size:1.5rem; font-weight:700; background:var(--here); color:var(--fg); border:1px solid var(--line); border-radius:8px; padding:.4rem .7rem; text-align:left; width:100%; }
|
|
71
|
+
.fields { display:grid; grid-auto-flow:column; justify-content:start; gap:0 1.1rem; font-family:ui-monospace,monospace; margin:.5rem 0; }
|
|
72
|
+
.fields .bits { font-size:1.15rem; letter-spacing:.06em; }
|
|
73
|
+
.fields .name, .fields .value { font-size:.8rem; }
|
|
74
|
+
.regs { display:flex; flex-wrap:wrap; gap:.3rem; margin:.4rem 0; }
|
|
75
|
+
.reg { background:var(--bg); color:var(--fg); border-color:var(--line); font-family:ui-monospace,monospace; font-size:.85rem; padding:.15rem .45rem; }
|
|
76
|
+
.flow { display:grid; grid-template-columns:minmax(0,1fr) auto minmax(0,1fr); gap:.6rem; align-items:center; margin:.5rem 0; }
|
|
77
|
+
.wires { display:flex; flex-direction:column; gap:.3rem; }
|
|
78
|
+
.wirebox { border:1px solid var(--line); border-radius:6px; padding:.25rem .45rem; font-size:.85rem; }
|
|
79
|
+
.wirebox strong { font-family:ui-monospace,monospace; }
|
|
80
|
+
.partbox { font-size:1.15rem; font-weight:700; padding:1rem .8rem; }
|
|
81
|
+
ul.parts { list-style:none; padding:0; margin:.2rem 0; display:grid; grid-template-columns:repeat(auto-fill,minmax(11rem,1fr)); gap:.35rem; }
|
|
82
|
+
ul.parts button { width:100%; text-align:left; background:var(--bg); color:var(--fg); border-color:var(--line); }
|
|
83
|
+
.gate { display:flex; flex-wrap:wrap; gap:.4rem; align-items:center; background:var(--bg); border:1px solid var(--line); border-radius:6px; padding:.3rem .55rem; margin:.3rem 0; }
|
|
84
|
+
.gate.picked { outline:3px solid var(--picked); }
|
|
85
|
+
.wire { border:1px solid var(--line); border-radius:4px; padding:0 .45rem; font-family:ui-monospace,monospace; font-size:.85rem; }
|
|
86
|
+
ol#walk-list { padding-left:1.4rem; }
|
|
87
|
+
ol#walk-list li { margin:.4rem 0; }
|
|
88
|
+
ol#walk-list button { font-size:1.05rem; text-align:left; }
|
|
89
|
+
#walks-note { color:var(--error); font-weight:600; }
|
|
90
|
+
a { color:var(--accent); }
|
|
91
|
+
.built { margin-top:.6rem; }
|
|
92
|
+
.built-code { overflow:auto; max-height:16rem; margin:.3rem 0; padding:.35rem .5rem; border:1px solid var(--line); border-radius:6px; background:var(--bg); font-family:ui-monospace,monospace; font-size:.78rem; white-space:pre; }
|
|
93
|
+
@media (max-width:44rem) {
|
|
94
|
+
main { padding:.4rem; gap:.3rem; }
|
|
95
|
+
.brand { display:none; }
|
|
96
|
+
#examples { flex:1 1 7rem; min-width:0; }
|
|
97
|
+
.panes { grid-template-columns:minmax(0,1fr); grid-template-rows:minmax(0,3fr) minmax(0,2fr); grid-template-areas:"glass" "program"; }
|
|
98
|
+
#boxes { grid-template-columns:repeat(2,minmax(0,1fr)); }
|
|
99
|
+
.big { font-size:1.15rem; }
|
|
100
|
+
.flow { grid-template-columns:minmax(0,1fr); }
|
|
101
|
+
.built-code { max-height:10rem; }
|
|
102
|
+
}
|
|
103
|
+
</style>
|
|
104
|
+
</head>
|
|
105
|
+
<body>
|
|
106
|
+
<main>
|
|
107
|
+
<header class="bar" role="group" aria-label="Controls">
|
|
108
|
+
<span class="brand">The Cockpit</span>
|
|
109
|
+
<button type="button" id="walks-button" class="quiet">Walks</button>
|
|
110
|
+
<button type="button" id="play">Play</button>
|
|
111
|
+
<button type="button" id="pause" class="quiet">Pause</button>
|
|
112
|
+
<button type="button" id="step" class="go step"></button>
|
|
113
|
+
<button type="button" id="step-into" hidden>Step into ▸</button>
|
|
114
|
+
<button type="button" id="rewind" class="quiet step">Rewind</button>
|
|
115
|
+
<select id="examples" aria-label="Load an example program">
|
|
116
|
+
<option value="">an example</option>
|
|
117
|
+
</select>
|
|
118
|
+
<button type="button" id="load-example" class="quiet">Load</button>
|
|
119
|
+
<button type="button" id="expert-button" class="quiet" aria-controls="expert" aria-expanded="false">Expert</button>
|
|
120
|
+
<span id="status" class="row" aria-live="polite"></span>
|
|
121
|
+
</header>
|
|
122
|
+
|
|
123
|
+
<section id="walk-bar" class="card" aria-label="The walk" hidden>
|
|
124
|
+
<div class="row">
|
|
125
|
+
<strong id="walk-title"></strong>
|
|
126
|
+
<span id="walk-place" class="muted"></span>
|
|
127
|
+
<span class="spacer"></span>
|
|
128
|
+
<button type="button" id="walk-back" class="quiet">◂ Back</button>
|
|
129
|
+
<button type="button" id="walk-next">Next ▸</button>
|
|
130
|
+
<button type="button" id="back-to-walk" hidden>Back to the walk</button>
|
|
131
|
+
<button type="button" id="walk-leave" class="quiet">Leave</button>
|
|
132
|
+
</div>
|
|
133
|
+
<p id="walk-say"></p>
|
|
134
|
+
<div id="try" hidden>
|
|
135
|
+
<p><strong>Now you try:</strong> <span id="try-task"></span></p>
|
|
136
|
+
<p id="try-cheer" class="cheer" hidden>You did it! Pick another walk, or keep exploring.</p>
|
|
137
|
+
<div id="try-read" hidden></div>
|
|
138
|
+
<button type="button" id="try-again" class="quiet" hidden>Start the task again</button>
|
|
139
|
+
</div>
|
|
140
|
+
</section>
|
|
141
|
+
|
|
142
|
+
<div id="said" aria-live="polite">
|
|
143
|
+
<p><strong>What just happened:</strong> <span id="happened"></span></p>
|
|
144
|
+
<p id="note" class="muted"></p>
|
|
145
|
+
<p id="error" role="alert"></p>
|
|
146
|
+
</div>
|
|
147
|
+
|
|
148
|
+
<div class="panes">
|
|
149
|
+
<section id="walks" class="pane" aria-label="Guided walks">
|
|
150
|
+
<h1>The Cockpit</h1>
|
|
151
|
+
<p>A whole computer made of NAND gates, with the lid off. Each walk shows you one idea on the real machine, one sentence at a time. Pick one to start.</p>
|
|
152
|
+
<p id="walks-note" role="alert"></p>
|
|
153
|
+
<ol id="walk-list"></ol>
|
|
154
|
+
<button type="button" id="explore" class="quiet">Explore on my own</button>
|
|
155
|
+
</section>
|
|
156
|
+
|
|
157
|
+
<section id="program" class="pane" aria-label="Your program">
|
|
158
|
+
<h2>Your program</h2>
|
|
159
|
+
<p id="pebble-note" class="muted"></p>
|
|
160
|
+
<div id="code"><table><tbody id="pebble"></tbody></table></div>
|
|
161
|
+
<div id="boxes">
|
|
162
|
+
<div class="box" id="variables-box"><h3>Variables</h3><div id="variables"></div></div>
|
|
163
|
+
<div class="box" id="stack-box" title="The top of the stack comes first"><h3>The stack</h3><div id="stack"></div></div>
|
|
164
|
+
<div class="box" id="output-box"><h3>Printed</h3><pre id="output"></pre></div>
|
|
165
|
+
</div>
|
|
166
|
+
</section>
|
|
167
|
+
|
|
168
|
+
<section id="glass" class="pane" aria-label="The magnifying glass">
|
|
169
|
+
<nav id="trail" aria-label="Trail: how deep the glass is looking"></nav>
|
|
170
|
+
<p id="playing-note" hidden>Pause to look inside the gates. While the computer plays, the gates are not running, so there is nothing real to show here.</p>
|
|
171
|
+
<div id="lens"></div>
|
|
172
|
+
</section>
|
|
173
|
+
</div>
|
|
174
|
+
</main>
|
|
175
|
+
|
|
176
|
+
<aside id="expert" class="pane" aria-label="Expert drawer" hidden>
|
|
177
|
+
<div class="row"><h2>Expert</h2><span class="spacer"></span><button type="button" id="expert-close" class="quiet">Close</button></div>
|
|
178
|
+
<p class="muted">Every exact move, for when you know just what you want.</p>
|
|
179
|
+
<h3>Step by a size</h3>
|
|
180
|
+
<div class="row" role="group" aria-label="Step sizes">
|
|
181
|
+
<button type="button" class="step" data-size="gate" data-count="1">1 gate</button>
|
|
182
|
+
<button type="button" class="step" data-size="gate" data-count="100">100 gates</button>
|
|
183
|
+
<button type="button" class="step" data-size="cycle">1 cycle</button>
|
|
184
|
+
<button type="button" class="step" data-size="instruction">1 instruction</button>
|
|
185
|
+
<button type="button" class="step" data-size="line" title="Run to the next Pebble line, running any function it calls all the way through">Line</button>
|
|
186
|
+
<button type="button" class="step" data-size="line_into" title="Run to the next Pebble line, following a call into the function">Line into</button>
|
|
187
|
+
</div>
|
|
188
|
+
<h3>Run</h3>
|
|
189
|
+
<div class="row">
|
|
190
|
+
<input id="count" type="number" min="1" max="10000" value="10" aria-label="Instructions to run">
|
|
191
|
+
<button type="button" id="run" class="step">Run</button>
|
|
192
|
+
<label class="row">Play speed
|
|
193
|
+
<select id="speed" aria-label="Instructions a second while playing">
|
|
194
|
+
<option value="1">1 a second</option>
|
|
195
|
+
<option value="10">10 a second</option>
|
|
196
|
+
<option value="100" selected>100 a second</option>
|
|
197
|
+
<option value="1000">1,000 a second</option>
|
|
198
|
+
<option value="10000">10,000 a second</option>
|
|
199
|
+
<option value="100000">100,000 a second</option>
|
|
200
|
+
</select>
|
|
201
|
+
</label>
|
|
202
|
+
</div>
|
|
203
|
+
<h3>Your own program</h3>
|
|
204
|
+
<textarea id="source" spellcheck="false" aria-label="Your program, in Pebble or assembly">let n = 3
|
|
205
|
+
while n > 0 {
|
|
206
|
+
print(n)
|
|
207
|
+
n = n - 1
|
|
208
|
+
}
|
|
209
|
+
</textarea>
|
|
210
|
+
<div class="row">
|
|
211
|
+
<button type="button" id="load-pebble">Load Pebble</button>
|
|
212
|
+
<button type="button" id="load" class="quiet">Load assembly</button>
|
|
213
|
+
</div>
|
|
214
|
+
<p class="muted">Translated (for Pebble) or assembled, put in memory, and paused at its start.</p>
|
|
215
|
+
</aside>
|
|
216
|
+
<script>
|
|
217
|
+
"use strict";
|
|
218
|
+
// What a part means, in plain words, and which concept page explains it.
|
|
219
|
+
// Whole paths come first, because some names (like "flags") mean different things in different places.
|
|
220
|
+
const PATHS = {
|
|
221
|
+
"": ["The whole circuit: the CPU and the RAM, filed into named parts.", "Looking Inside a Circuit (looking-inside.md)"],
|
|
222
|
+
"cpu.flags": ["The flags register: four bits remembering whether the last result was zero, negative, carried or overflowed.", "Machine Code (machine-code.md)"],
|
|
223
|
+
"cpu.operand": ["The operand chooser: picks what goes into the ALU's second input for this instruction.", "The Control Unit (the-control-unit.md)"],
|
|
224
|
+
"cpu.alu.control": ["The ALU's control: works out from the op dial whether this job is a subtraction.", "The ALU (the-alu.md)"],
|
|
225
|
+
"cpu.alu.flags": ["The ALU's flags part: it holds the zero check, which lights up when the result is all 0s.", "The ALU (the-alu.md)"],
|
|
226
|
+
};
|
|
227
|
+
const LEVELS = {
|
|
228
|
+
"ram": ["The RAM: memory, every bit of every word a latch made of gates.", "RAM (ram.md)"],
|
|
229
|
+
"cpu": ["The CPU: its registers, the control unit, the ALU and the wires between them.", "What Is a CPU? (what-is-a-cpu.md)"],
|
|
230
|
+
"phase": ["The phase register: one bit saying whether the next beat fetches or executes.", "Fetch, Decode, Execute (fetch-decode-execute.md)"],
|
|
231
|
+
"ir": ["The instruction register: holds the instruction being worked on.", "Fetch, Decode, Execute (fetch-decode-execute.md)"],
|
|
232
|
+
"pc": ["The program counter: the address of the next instruction.", "What Is a CPU? (what-is-a-cpu.md)"],
|
|
233
|
+
"sp": ["The stack pointer: the address of the top of the stack.", "The Stack (the-stack.md)"],
|
|
234
|
+
"halt": ["The halt registers: whether the machine has stopped, and its halt code.", "Machine Code (machine-code.md)"],
|
|
235
|
+
"halted": ["The halted bit: 1 once the machine has stopped.", "Machine Code (machine-code.md)"],
|
|
236
|
+
"halt_code": ["The halt code: why the machine stopped (0 means it finished normally).", "Machine Code (machine-code.md)"],
|
|
237
|
+
"decode": ["The decoder: turns the opcode into one lit wire per kind of instruction.", "The Control Unit (the-control-unit.md)"],
|
|
238
|
+
"control": ["The control: works out which jobs this instruction needs done.", "The Control Unit (the-control-unit.md)"],
|
|
239
|
+
"registers": ["The register file: r0 to r7, and the choosers that read and write them.", "The Control Unit (the-control-unit.md)"],
|
|
240
|
+
"condition": ["The condition check: decides whether a branch should be taken.", "The Control Unit (the-control-unit.md)"],
|
|
241
|
+
"sp_minus_1": ["An adder that works out sp - 1, for pushing.", "The Stack (the-stack.md)"],
|
|
242
|
+
"sp_plus_1": ["An adder that works out sp + 1, for popping.", "The Stack (the-stack.md)"],
|
|
243
|
+
"next_sp": ["Choosers that pick the stack pointer's next value.", "The Stack (the-stack.md)"],
|
|
244
|
+
"pc_plus_1": ["An adder that works out pc + 1, the next instruction's address.", "Fetch, Decode, Execute (fetch-decode-execute.md)"],
|
|
245
|
+
"branch_target": ["An adder that works out where a branch would land.", "Fetch, Decode, Execute (fetch-decode-execute.md)"],
|
|
246
|
+
"next_pc": ["Choosers that pick the program counter's next value.", "Fetch, Decode, Execute (fetch-decode-execute.md)"],
|
|
247
|
+
"address_mux": ["Choosers that pick which address goes to memory.", "Fetch, Decode, Execute (fetch-decode-execute.md)"],
|
|
248
|
+
"address_check": ["The check that an address is inside memory.", "Fetch, Decode, Execute (fetch-decode-execute.md)"],
|
|
249
|
+
"port": ["The check for a store to the output port, the computer's screen.", "Fetch, Decode, Execute (fetch-decode-execute.md)"],
|
|
250
|
+
"fault": ["The fault check: spots a bad address and stops the machine.", "Fetch, Decode, Execute (fetch-decode-execute.md)"],
|
|
251
|
+
"write_back": ["Choosers that pick the value written back into a register.", "Fetch, Decode, Execute (fetch-decode-execute.md)"],
|
|
252
|
+
"ram_data": ["Choosers that pick the word a store writes to memory.", "Fetch, Decode, Execute (fetch-decode-execute.md)"],
|
|
253
|
+
"ram_wires": ["Buffers that carry the CPU's address, data and write wires over to the RAM.", "Fetch, Decode, Execute (fetch-decode-execute.md)"],
|
|
254
|
+
"alu": ["The ALU: two numbers go in, a dial picks the job, a result and four flag lamps come out.", "The ALU (the-alu.md)"],
|
|
255
|
+
"adder": ["The adder: sixteen columns that add, one after the other, passing a carry along.", "Adding (adding.md)"],
|
|
256
|
+
"bit": ["One bit: one column of a sum, or one storage cell of a register.", "Adding (adding.md)"],
|
|
257
|
+
"full_adder": ["A full adder: adds two bits and a carry that came in.", "Adding (adding.md)"],
|
|
258
|
+
"half_adder": ["A half adder: adds two bits, giving a sum digit and a carry.", "Adding (adding.md)"],
|
|
259
|
+
"xor": ["An XOR gate, made of 4 NANDs: on when its inputs differ.", "Logic Gates from NAND (gates.md)"],
|
|
260
|
+
"and": ["An AND gate, made of 2 NANDs: on only when both inputs are on.", "Logic Gates from NAND (gates.md)"],
|
|
261
|
+
"or": ["An OR gate, made of 3 NANDs: on when either input is on.", "Logic Gates from NAND (gates.md)"],
|
|
262
|
+
"mux": ["A chooser: picks one of two wires, steered by a select wire.", "Choosing and Decoding (choosing-and-decoding.md)"],
|
|
263
|
+
"choose": ["The inside of a chooser: gates that let one of the two wires through.", "Choosing and Decoding (choosing-and-decoding.md)"],
|
|
264
|
+
"or_many": ["An OR over many wires: on if any one of them is on.", "Logic Gates from NAND (gates.md)"],
|
|
265
|
+
"is_zero": ["The zero check: on only when every wire of the result is off.", "The ALU (the-alu.md)"],
|
|
266
|
+
"operand": ["The operand: flips the bits of B when subtracting.", "Negative Numbers (negative-numbers.md)"],
|
|
267
|
+
"overflow": ["The overflow check: spots a signed answer that does not fit.", "Negative Numbers (negative-numbers.md)"],
|
|
268
|
+
"select": ["The select: choosers steered by the op dial pick the answer.", "Choosing and Decoding (choosing-and-decoding.md)"],
|
|
269
|
+
"master": ["The master latch: the first half of a flip-flop, open while the clock is low.", "The Clock (the-clock.md)"],
|
|
270
|
+
"slave": ["The slave latch: the second half of a flip-flop, open when the clock rises.", "The Clock (the-clock.md)"],
|
|
271
|
+
"word": ["One word of memory: sixteen latches made of gates, one for each bit.", "RAM (ram.md)"],
|
|
272
|
+
"register": ["One register: sixteen flip-flops holding one number.", "Registers (registers.md)"],
|
|
273
|
+
};
|
|
274
|
+
const GATE_LINE = ["One NAND gate: its output is 0 only when both inputs are 1. Every part above is built from these.", "Switches and NAND (switches-and-nand.md)"];
|
|
275
|
+
const FALLBACK = ["A part of the circuit, made of smaller parts and gates.", "Looking Inside a Circuit (looking-inside.md)"];
|
|
276
|
+
// Plain words for each part the glass can look at (the same names as PART_NAMES in picture.py).
|
|
277
|
+
const PART_WORDS = {"cpu.alu": "ALU", "cpu.write_back": "write-back", "cpu.address_mux": "memory address", "cpu.next_pc": "next-instruction", "cpu.next_sp": "stack pointer", "cpu.halt": "halt", "cpu.registers": "registers", "ram": "RAM", "cpu": "CPU"};
|
|
278
|
+
// Plain words for every wire name a part view can show (the names in GateMachine.taps).
|
|
279
|
+
const TAP_WORDS = {
|
|
280
|
+
"a": "number A",
|
|
281
|
+
"b": "number B",
|
|
282
|
+
"result": "answer",
|
|
283
|
+
"flags": "flag lamps",
|
|
284
|
+
"alu": "the ALU's answer",
|
|
285
|
+
"memory": "the word read from memory",
|
|
286
|
+
"imm8": "the number inside the instruction",
|
|
287
|
+
"register_a": "the first register's number",
|
|
288
|
+
"sp": "stack pointer",
|
|
289
|
+
"destination": "which register gets it",
|
|
290
|
+
"value": "the number to write",
|
|
291
|
+
"write": "write it? (1 means yes)",
|
|
292
|
+
"pc": "program counter",
|
|
293
|
+
"sp_minus_1": "stack pointer − 1",
|
|
294
|
+
"address": "the address sent to memory",
|
|
295
|
+
"pc_plus_1": "program counter + 1",
|
|
296
|
+
"branch_target": "where a branch would land",
|
|
297
|
+
"jump_to": "where a jump goes",
|
|
298
|
+
"next_pc": "the next program counter",
|
|
299
|
+
"load": "change it? (1 means yes)",
|
|
300
|
+
"sp_plus_1": "stack pointer + 1",
|
|
301
|
+
"register": "a register's number",
|
|
302
|
+
"next_sp": "the next stack pointer",
|
|
303
|
+
"bad_address": "bad address? (1 means yes)",
|
|
304
|
+
"halt_instruction": "is it a halt? (1 means yes)",
|
|
305
|
+
"halt_now": "stop now? (1 means yes)",
|
|
306
|
+
"code": "the halt code",
|
|
307
|
+
"write_select": "which register gets it",
|
|
308
|
+
"data": "the number to keep",
|
|
309
|
+
"read_a": "first register being read",
|
|
310
|
+
"read_b": "second register being read",
|
|
311
|
+
"out": "the word at that address"
|
|
312
|
+
};
|
|
313
|
+
// Which fields each opcode's word holds, and which bits each field is (the Instruction Set page).
|
|
314
|
+
const FIELDS = {"0": ["rd", "ra", "rb", "fn"], "1": ["ra", "rb"], "2": ["rd", "imm8"], "3": ["rd", "imm8"], "4": ["rd", "ra", "off6"], "5": ["rd", "ra", "off6"], "6": ["addr12"], "7": ["addr12"], "8": ["cond", "off9"], "9": [], "10": ["rd"], "11": ["rd"], "12": ["rd"], "13": ["rd"], "14": ["rd", "imm8"], "15": ["imm8"]};
|
|
315
|
+
const FIELD_BITS = {"opcode": [15, 12], "rd": [11, 9], "cond": [11, 9], "ra": [8, 6], "rb": [5, 3], "fn": [2, 0], "imm8": [7, 0], "off6": [5, 0], "off9": [8, 0], "addr12": [11, 0]};
|
|
316
|
+
const FIELD_TITLES = {
|
|
317
|
+
"opcode": "The job: which kind of instruction this is.",
|
|
318
|
+
"rd": "A register this instruction works on.",
|
|
319
|
+
"cond": "Which flags a branch checks.",
|
|
320
|
+
"ra": "The first register to read.",
|
|
321
|
+
"rb": "The second register to read.",
|
|
322
|
+
"fn": "Which sum the ALU does.",
|
|
323
|
+
"imm8": "A small number written inside the instruction itself.",
|
|
324
|
+
"off6": "How far from the address in the register, up or down.",
|
|
325
|
+
"off9": "How far to jump, forwards or back.",
|
|
326
|
+
"addr12": "The address to go to."
|
|
327
|
+
};
|
|
328
|
+
const SIGNED = { "off6": 6, "off9": 9 };
|
|
329
|
+
const ADDI = 14;
|
|
330
|
+
const DEPTHS = ["line", "instruction", "part", "gate"];
|
|
331
|
+
const FLAGS = ["zero", "negative", "carry", "overflow"];
|
|
332
|
+
const CHANGED = "changed";
|
|
333
|
+
const NO_GATE = "so there is no gate to show.";
|
|
334
|
+
const NOTHING_YET = "(nothing yet)";
|
|
335
|
+
const WALK_NOT_FOUND = "Walk not found.";
|
|
336
|
+
const UNREACHABLE = "Could not reach the Cockpit";
|
|
337
|
+
// The code panel under a part's wires.
|
|
338
|
+
const BUILT_TITLE = "The code that built this";
|
|
339
|
+
const NO_CODE = "The code isn't available here.";
|
|
340
|
+
const HIDDEN_TITLE = "A hidden helper: Pebble made this box for itself (a for loop keeps its end value here). Its name starts with $, which no program could write.";
|
|
341
|
+
|
|
342
|
+
let busy = false; // a button's request is on its way
|
|
343
|
+
let latest = null; // the last picture drawn
|
|
344
|
+
let latestText = ""; // ... and its JSON, to skip drawing the same picture twice
|
|
345
|
+
let listing = null; // the last GET /api/listing
|
|
346
|
+
let fetchingListing = false;
|
|
347
|
+
let look = "line"; // how deep the glass looks: one of DEPTHS
|
|
348
|
+
let gatePath = "cpu"; // the part of the circuit the gates depth shows
|
|
349
|
+
let partPath = null; // the part the part depth shows; null means the instruction's own
|
|
350
|
+
let codeScroll = { path: null, top: 0 }; // where the learner left the code box
|
|
351
|
+
let codeOpen = false; // whether "The code that built this" is open
|
|
352
|
+
let pickedGate = null; // {id, path}: the gate "show this gate" highlights, for its own picture only
|
|
353
|
+
let lensSeq = 0; // counts glass requests, so only the newest answer is drawn
|
|
354
|
+
let glowing = new Set(); // what the latest picture changed, as data-glow keys
|
|
355
|
+
let walkKey = null; // "name:step" of the walk step the glass last followed
|
|
356
|
+
let wandered = false; // the glass was moved away from where the walk is looking
|
|
357
|
+
|
|
358
|
+
function el(tag, text, cls) {
|
|
359
|
+
const e = document.createElement(tag);
|
|
360
|
+
if (text !== undefined) e.textContent = text;
|
|
361
|
+
if (cls) e.className = cls;
|
|
362
|
+
return e;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function button(text, cls, onclick) {
|
|
366
|
+
const b = el("button", text, cls);
|
|
367
|
+
b.type = "button";
|
|
368
|
+
b.onclick = onclick;
|
|
369
|
+
return b;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function hex(n) { return "0x" + n.toString(16).toUpperCase().padStart(4, "0"); }
|
|
373
|
+
|
|
374
|
+
function showError(text) { document.getElementById("error").textContent = text; }
|
|
375
|
+
|
|
376
|
+
// Scroll the box that holds `node` (never the whole page) so that `node` is in view.
|
|
377
|
+
function keepVisible(node) {
|
|
378
|
+
if (!node) return;
|
|
379
|
+
let box = node.parentElement;
|
|
380
|
+
while (box && box.scrollHeight <= box.clientHeight + 1) box = box.parentElement;
|
|
381
|
+
if (!box || box === document.body || box === document.documentElement) return;
|
|
382
|
+
const top = node.getBoundingClientRect().top - box.getBoundingClientRect().top + box.scrollTop;
|
|
383
|
+
if (top < box.scrollTop + 16 || top + node.offsetHeight > box.scrollTop + box.clientHeight - 16) {
|
|
384
|
+
box.scrollTop = Math.max(0, top - box.clientHeight / 3);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// ---- talking to the Cockpit -------------------------------------------------
|
|
389
|
+
|
|
390
|
+
function messageOf(text, status) {
|
|
391
|
+
try { return JSON.parse(text).message || "The Cockpit refused that (" + status + ")."; } catch (e) { return "The Cockpit refused that (" + status + ")."; }
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Send one button's request and draw its answer. A refusal shows its message, then asks
|
|
395
|
+
// for the picture again, to catch up with what is really happening (a stream may have dropped).
|
|
396
|
+
async function send(url, body, onRefused) {
|
|
397
|
+
if (busy) return;
|
|
398
|
+
busy = true;
|
|
399
|
+
setControls();
|
|
400
|
+
try {
|
|
401
|
+
const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
402
|
+
const text = await response.text();
|
|
403
|
+
if (!response.ok) {
|
|
404
|
+
const message = messageOf(text, response.status);
|
|
405
|
+
if (onRefused) { onRefused(response.status, message); return; }
|
|
406
|
+
showError(message);
|
|
407
|
+
refresh();
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
showError("");
|
|
411
|
+
drawText(text);
|
|
412
|
+
} catch (e) {
|
|
413
|
+
showError(UNREACHABLE);
|
|
414
|
+
} finally {
|
|
415
|
+
busy = false;
|
|
416
|
+
setControls();
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// Read the picture without moving anything; used at the start and after the stream reconnects.
|
|
421
|
+
async function refresh() {
|
|
422
|
+
try {
|
|
423
|
+
const response = await fetch("/api/machine");
|
|
424
|
+
if (response.ok) drawText(await response.text());
|
|
425
|
+
} catch (e) {
|
|
426
|
+
showError(UNREACHABLE);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function listen() {
|
|
431
|
+
if (!window.EventSource) return;
|
|
432
|
+
const events = new EventSource("/api/events");
|
|
433
|
+
events.addEventListener("machine", (e) => drawText(e.data));
|
|
434
|
+
// After a dropped stream reconnects, catch up with anything missed in between.
|
|
435
|
+
events.addEventListener("open", refresh);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// ---- walks ----------------------------------------------------------------
|
|
439
|
+
|
|
440
|
+
function openWalk(name, step, fromLink) {
|
|
441
|
+
send("/api/walk", { name: name, step: step }, fromLink ? linkRefused : undefined);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// A walk link the Cockpit refused: a 404 means no walk has that name; anything else is
|
|
445
|
+
// shown in the Cockpit's own words, as every other refusal is.
|
|
446
|
+
function linkRefused(status, message) {
|
|
447
|
+
if (status === 404) showWalks(WALK_NOT_FOUND);
|
|
448
|
+
else { showWalks(); showError(message); }
|
|
449
|
+
refresh();
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// Replay the walk to where it is now (a step, or the start of its task), on the real machine.
|
|
453
|
+
function replayWalk() {
|
|
454
|
+
const w = latest && latest.walk;
|
|
455
|
+
if (!w) return;
|
|
456
|
+
walkKey = null;
|
|
457
|
+
latestText = "";
|
|
458
|
+
openWalk(w.name, w.step);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function showWalks(note) {
|
|
462
|
+
document.getElementById("walks-note").textContent = note || "";
|
|
463
|
+
document.getElementById("walks").hidden = false;
|
|
464
|
+
document.getElementById("program").hidden = true;
|
|
465
|
+
document.getElementById("glass").hidden = true;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function hideWalks() {
|
|
469
|
+
document.getElementById("walks").hidden = true;
|
|
470
|
+
document.getElementById("program").hidden = false;
|
|
471
|
+
document.getElementById("glass").hidden = false;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
async function loadWalks() {
|
|
475
|
+
try {
|
|
476
|
+
const response = await fetch("/api/walks");
|
|
477
|
+
if (!response.ok) return;
|
|
478
|
+
const list = document.getElementById("walk-list");
|
|
479
|
+
(await response.json()).forEach((w) => {
|
|
480
|
+
const li = el("li");
|
|
481
|
+
li.append(button(w.title, "", () => openWalk(w.name, 0, false)));
|
|
482
|
+
list.append(li);
|
|
483
|
+
});
|
|
484
|
+
} catch (e) {
|
|
485
|
+
showError(UNREACHABLE);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// A new walk step moves the glass to the walk's depth; other pictures leave the glass alone.
|
|
490
|
+
function followWalk(m) {
|
|
491
|
+
const w = m.walk;
|
|
492
|
+
if (!w) {
|
|
493
|
+
if (walkKey !== null && location.hash) history.replaceState(null, "", location.pathname + location.search);
|
|
494
|
+
walkKey = null;
|
|
495
|
+
wandered = false;
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
const key = w.name + ":" + w.step;
|
|
499
|
+
if (key === walkKey) return;
|
|
500
|
+
walkKey = key;
|
|
501
|
+
wandered = false;
|
|
502
|
+
look = w.look;
|
|
503
|
+
pickedGate = null;
|
|
504
|
+
partPath = null;
|
|
505
|
+
gatePath = gatesOf(m, m.parts.instruction);
|
|
506
|
+
if (w.show === "last_gate" && m.last_gate) {
|
|
507
|
+
gatePath = m.last_gate.path;
|
|
508
|
+
pickedGate = { id: m.last_gate.id, path: m.last_gate.path };
|
|
509
|
+
}
|
|
510
|
+
history.replaceState(null, "", "#walk=" + encodeURIComponent(w.name));
|
|
511
|
+
hideWalks();
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function drawWalk(m) {
|
|
515
|
+
const w = m.walk;
|
|
516
|
+
document.getElementById("walk-bar").hidden = !w;
|
|
517
|
+
if (!w) return;
|
|
518
|
+
const away = w.off_script || (wandered && !w.trying);
|
|
519
|
+
document.getElementById("walk-title").textContent = w.title;
|
|
520
|
+
document.getElementById("walk-place").textContent = w.trying ? "Now you try" : "Step " + (w.step + 1) + " of " + w.count;
|
|
521
|
+
const say = document.getElementById("walk-say");
|
|
522
|
+
say.textContent = w.trying ? "" : (w.say || "");
|
|
523
|
+
say.hidden = w.trying;
|
|
524
|
+
say.classList.toggle("dim", away);
|
|
525
|
+
document.getElementById("try").hidden = !w.trying;
|
|
526
|
+
document.getElementById("try-task").textContent = w.task || "";
|
|
527
|
+
document.getElementById("try-cheer").hidden = !w.done;
|
|
528
|
+
const read = document.getElementById("try-read");
|
|
529
|
+
read.hidden = !w.done;
|
|
530
|
+
read.replaceChildren(readAbout(w.see_also, "to see how this idea is built"));
|
|
531
|
+
document.getElementById("try-again").hidden = !(w.trying && !w.done);
|
|
532
|
+
document.getElementById("walk-next").hidden = w.trying;
|
|
533
|
+
document.getElementById("back-to-walk").hidden = !away;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// Outline the one thing a walk step points at, and scroll its own box to it.
|
|
537
|
+
function outline(show, m) {
|
|
538
|
+
let target = null;
|
|
539
|
+
if (show === "pebble.line") target = document.querySelector("#pebble tr.here");
|
|
540
|
+
else if (show === "variables" || show === "memory") target = document.getElementById("variables-box");
|
|
541
|
+
else if (show === "stack") target = document.getElementById("stack-box");
|
|
542
|
+
else if (show === "output") target = document.getElementById("output-box");
|
|
543
|
+
else if (show === "registers") target = document.getElementById("regs");
|
|
544
|
+
else if (show === "flags") target = document.getElementById("flag-lamps");
|
|
545
|
+
else if (show === "happened") target = document.getElementById("said");
|
|
546
|
+
else if (show === "instruction") target = document.getElementById("the-instruction") || document.querySelector("#pebble tr.next");
|
|
547
|
+
else if (show === "last_gate" && m.last_gate) target = document.querySelector(".gate.picked");
|
|
548
|
+
if (!target) return;
|
|
549
|
+
target.classList.add("look-here");
|
|
550
|
+
keepVisible(target);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function outlineShow(m) {
|
|
554
|
+
document.querySelectorAll(".look-here").forEach((n) => n.classList.remove("look-here"));
|
|
555
|
+
const w = m.walk;
|
|
556
|
+
if (w && w.show && !w.off_script && !wandered) outline(w.show, m);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// ---- the glow: only the latest picture's changes ----------------------------------
|
|
560
|
+
|
|
561
|
+
function markChanged(node) {
|
|
562
|
+
node.classList.add(CHANGED);
|
|
563
|
+
node.append(el("span", CHANGED, "tag"));
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function glowIn(root) {
|
|
567
|
+
root.querySelectorAll("[data-glow]").forEach((node) => {
|
|
568
|
+
if (glowing.has(node.dataset.glow) && !node.classList.contains(CHANGED)) markChanged(node);
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function drawChanged(m) {
|
|
573
|
+
document.querySelectorAll("." + CHANGED).forEach((node) => {
|
|
574
|
+
node.classList.remove(CHANGED);
|
|
575
|
+
node.querySelectorAll(":scope > .tag").forEach((t) => t.remove());
|
|
576
|
+
});
|
|
577
|
+
const c = m.changed;
|
|
578
|
+
glowing = new Set();
|
|
579
|
+
c.registers.forEach((i) => glowing.add("r" + i));
|
|
580
|
+
c.flags.forEach((f) => glowing.add("flag:" + f));
|
|
581
|
+
c.memory.forEach((a) => glowing.add("mem:" + a));
|
|
582
|
+
if (c.pc) glowing.add("pc");
|
|
583
|
+
if (c.sp) glowing.add("sp");
|
|
584
|
+
glowIn(document);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// ---- the program pane -------------------------------------------------------
|
|
588
|
+
|
|
589
|
+
// Fetch the listing for picture m. While one fetch is out, later calls are dropped, and
|
|
590
|
+
// the check when it lands catches anything they would have done.
|
|
591
|
+
async function fetchListing(m) {
|
|
592
|
+
if (fetchingListing) return;
|
|
593
|
+
fetchingListing = true;
|
|
594
|
+
const askedFor = m.program;
|
|
595
|
+
try {
|
|
596
|
+
const response = await fetch("/api/listing");
|
|
597
|
+
if (response.ok) listing = await response.json();
|
|
598
|
+
} catch (e) {
|
|
599
|
+
showError(UNREACHABLE);
|
|
600
|
+
} finally {
|
|
601
|
+
fetchingListing = false;
|
|
602
|
+
}
|
|
603
|
+
// A program may have been loaded while that fetch was out: look again at the newest picture.
|
|
604
|
+
if (!latest) return;
|
|
605
|
+
if (listingIsStale(latest)) {
|
|
606
|
+
if (latest.program !== askedFor) fetchListing(latest);
|
|
607
|
+
} else {
|
|
608
|
+
drawProgram(latest);
|
|
609
|
+
if (look === "line") drawLens(latest);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// The listing is fetched once per program. Each load gives the program a new number,
|
|
614
|
+
// and the listing says which number it was made for.
|
|
615
|
+
function listingIsStale(m) {
|
|
616
|
+
return !listing || listing.program !== m.program;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
function rowsOfLine(line) {
|
|
620
|
+
return listing && !listingIsStale(latest) ? listing.rows.filter((r) => r.pebble_line === line) : [];
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
function codeText(r) {
|
|
624
|
+
return (r.labels.length ? r.labels.join(": ") + ": " : "") + r.text;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
function instructionRow(r, m, sub) {
|
|
628
|
+
const next = !m.halted && r.address === m.instruction.address;
|
|
629
|
+
const row = el("tr", undefined, (sub ? "sub" : "") + (next ? " next" : ""));
|
|
630
|
+
row.append(el("td", sub ? "" : (next ? ">" : ""), "mark"), el("td", (sub && next ? "> " : "") + r.address, "num"), el("td", codeText(r)));
|
|
631
|
+
return row;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function drawProgram(m) {
|
|
635
|
+
const body = document.getElementById("pebble");
|
|
636
|
+
body.replaceChildren();
|
|
637
|
+
const p = m.pebble;
|
|
638
|
+
let mark = null;
|
|
639
|
+
if (p) {
|
|
640
|
+
p.source.forEach((text, i) => {
|
|
641
|
+
const n = i + 1;
|
|
642
|
+
const row = el("tr");
|
|
643
|
+
const here = n === p.line;
|
|
644
|
+
row.append(el("td", here ? "▶" : "", "mark"), el("td", String(n), "num"), el("td", text));
|
|
645
|
+
if (here) { row.classList.add("here"); mark = row; }
|
|
646
|
+
body.append(row);
|
|
647
|
+
if (here && !m.halted) {
|
|
648
|
+
rowsOfLine(n).forEach((r) => {
|
|
649
|
+
const sub = instructionRow(r, m, true);
|
|
650
|
+
if (sub.classList.contains("next")) mark = sub;
|
|
651
|
+
body.append(sub);
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
});
|
|
655
|
+
} else if (listing && !listingIsStale(m)) {
|
|
656
|
+
listing.rows.forEach((r) => {
|
|
657
|
+
const row = instructionRow(r, m, false);
|
|
658
|
+
if (row.classList.contains("next")) mark = row;
|
|
659
|
+
body.append(row);
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
keepVisible(mark);
|
|
663
|
+
drawPebbleNote(m);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function drawPebbleNote(m) {
|
|
667
|
+
const note = document.getElementById("pebble-note");
|
|
668
|
+
const p = m.pebble;
|
|
669
|
+
if (!p) {
|
|
670
|
+
note.textContent = "This program is written in assembly, so there are no Pebble lines: here is its machine code, with > on the next instruction.";
|
|
671
|
+
} else if (m.halted) {
|
|
672
|
+
note.textContent = p.message + "." + (p.line ? " The marked line is the one to blame." : "");
|
|
673
|
+
} else if (m.running) {
|
|
674
|
+
note.textContent = p.line === null ? "Playing: inside a ready-made routine." : "Playing: on line " + p.line + ".";
|
|
675
|
+
} else if (p.line === null) {
|
|
676
|
+
note.textContent = "Inside a ready-made routine (multiply, divide or print). It has no Pebble line of its own.";
|
|
677
|
+
} else {
|
|
678
|
+
note.textContent = "Running line " + p.line + ". One line is many instructions: they are listed under it, and > marks the next one.";
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
function cellRow(cells, part, glowKey) {
|
|
683
|
+
const row = el("tr", undefined, "clickable");
|
|
684
|
+
row.title = "Click to look at the gates of this word of memory (" + part + ")";
|
|
685
|
+
cells.forEach((c) => row.append(typeof c === "string" ? el("td", c) : c));
|
|
686
|
+
row.dataset.glow = glowKey;
|
|
687
|
+
row.onclick = () => gates(part);
|
|
688
|
+
return row;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
function drawStack(m) {
|
|
692
|
+
const box = document.getElementById("stack");
|
|
693
|
+
box.replaceChildren();
|
|
694
|
+
if (m.stack.length === 0) {
|
|
695
|
+
box.append(el("p", "Empty: sp is at the very end of memory, where it starts.", "muted"));
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
const table = el("table");
|
|
699
|
+
const body = el("tbody");
|
|
700
|
+
m.stack.forEach((cell) => body.append(cellRow([cell.address + ": " + cell.word], cell.part, "mem:" + cell.address)));
|
|
701
|
+
table.append(body);
|
|
702
|
+
box.append(table);
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
function drawVariables(m) {
|
|
706
|
+
const box = document.getElementById("variables");
|
|
707
|
+
box.replaceChildren();
|
|
708
|
+
const v = m.variables;
|
|
709
|
+
if (!v) {
|
|
710
|
+
let why = "No frame is ready here: the code is still building its frame, or returning, or a ready-made routine is running. Step on and the names appear.";
|
|
711
|
+
if (!m.pebble) why = "This program is assembly, which has no variable names.";
|
|
712
|
+
else if (m.running) why = "Variables are shown while paused.";
|
|
713
|
+
else if (m.halted) why = "The program has stopped.";
|
|
714
|
+
box.append(el("p", why, "muted"));
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
box.append(el("p", (v.function === null ? "The top level" : "Inside " + v.function) + ", frame pointer r7 = " + v.frame_pointer + ".", "muted"));
|
|
718
|
+
const table = el("table");
|
|
719
|
+
const body = el("tbody");
|
|
720
|
+
v.names.forEach((n) => {
|
|
721
|
+
const name = el("td", n.name + (n.kind === "parameter" ? " (parameter)" : ""));
|
|
722
|
+
const row = cellRow([name, String(n.value), "at " + n.address], n.part, "mem:" + n.address);
|
|
723
|
+
if (n.hidden) {
|
|
724
|
+
row.classList.add("dim");
|
|
725
|
+
row.title = HIDDEN_TITLE;
|
|
726
|
+
}
|
|
727
|
+
body.append(row);
|
|
728
|
+
});
|
|
729
|
+
if (v.names.length === 0) body.append(el("tr", "No variables here.", "muted"));
|
|
730
|
+
table.append(body);
|
|
731
|
+
box.append(table);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// ---- the magnifying glass -----------------------------------------------------
|
|
735
|
+
|
|
736
|
+
function partWords(path) { return PART_WORDS[path] || path.split(".").pop(); }
|
|
737
|
+
|
|
738
|
+
// The part the part depth shows: one the learner picked, or else the instruction's own.
|
|
739
|
+
function shownPart(m) { return partPath || m.parts.instruction; }
|
|
740
|
+
|
|
741
|
+
// Where a part's gates are: the scope that makes its outputs (for halt, cpu.fault).
|
|
742
|
+
function gatesOf(m, path) { return m.parts.gates[path] || path; }
|
|
743
|
+
|
|
744
|
+
// "Read about it", linking a concept page on the public docs site (the API gives the URL).
|
|
745
|
+
function readAbout(page, why) {
|
|
746
|
+
const box = el("div");
|
|
747
|
+
const line = el("p", "Read about it: ");
|
|
748
|
+
const link = el("a", page.title);
|
|
749
|
+
link.href = page.url;
|
|
750
|
+
link.target = "_blank";
|
|
751
|
+
link.rel = "noopener";
|
|
752
|
+
line.append(link, ", " + why + ".");
|
|
753
|
+
box.append(line);
|
|
754
|
+
return box;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// The code that built a part: closed until opened, then its file and line, the code, and the link.
|
|
758
|
+
function drawBuiltBy(b, path) {
|
|
759
|
+
const box = el("div", undefined, "built");
|
|
760
|
+
const inside = el("div");
|
|
761
|
+
const toggle = button("", "quiet", () => { codeOpen = !codeOpen; show(); if (codeOpen) keepVisible(inside); });
|
|
762
|
+
const show = () => {
|
|
763
|
+
toggle.textContent = BUILT_TITLE + (codeOpen ? " ▾" : " ▸");
|
|
764
|
+
toggle.setAttribute("aria-expanded", String(codeOpen));
|
|
765
|
+
inside.hidden = !codeOpen;
|
|
766
|
+
};
|
|
767
|
+
inside.append(el("p", "Built by " + b.function + ", in " + b.file + ":" + b.line, "muted"));
|
|
768
|
+
if (b.code === null) {
|
|
769
|
+
inside.append(el("p", NO_CODE));
|
|
770
|
+
} else {
|
|
771
|
+
const code = el("pre", undefined, "built-code");
|
|
772
|
+
code.textContent = b.code;
|
|
773
|
+
code.onscroll = () => { codeScroll = { path: path, top: code.scrollTop }; };
|
|
774
|
+
inside.append(code);
|
|
775
|
+
}
|
|
776
|
+
inside.append(readAbout(b.page, "the page that explains this part"));
|
|
777
|
+
show();
|
|
778
|
+
box.append(toggle, inside);
|
|
779
|
+
return box;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// Every part with a part view, to pick from at the part depth.
|
|
783
|
+
function partList(m, current) {
|
|
784
|
+
const list = el("ul", undefined, "parts");
|
|
785
|
+
Object.keys(PART_WORDS).filter((p) => p !== "cpu").forEach((p) => {
|
|
786
|
+
const li = el("li");
|
|
787
|
+
const b = button(partWords(p), "", () => { partPath = p; setLook("part"); });
|
|
788
|
+
if (p === current) b.setAttribute("aria-current", "true");
|
|
789
|
+
li.append(b);
|
|
790
|
+
list.append(li);
|
|
791
|
+
});
|
|
792
|
+
return list;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
// Move the glass (never the machine). During a walk's steps, looking somewhere else is wandering off.
|
|
796
|
+
function setLook(depth, path) {
|
|
797
|
+
look = depth;
|
|
798
|
+
if (path !== undefined) gatePath = path;
|
|
799
|
+
const w = latest && latest.walk;
|
|
800
|
+
wandered = Boolean(w && !w.trying && (look !== w.look || partPath !== null));
|
|
801
|
+
if (latest) { drawWalk(latest); drawGlass(latest); drawStep(latest); setControls(); }
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
function goDeeper() {
|
|
805
|
+
const next = DEPTHS[DEPTHS.indexOf(look) + 1];
|
|
806
|
+
if (!next) return;
|
|
807
|
+
pickedGate = null;
|
|
808
|
+
if (next === "part") partPath = null;
|
|
809
|
+
setLook(next, next === "gate" ? gatesOf(latest, shownPart(latest)) : undefined);
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
function gates(path) {
|
|
813
|
+
pickedGate = null;
|
|
814
|
+
setLook("gate", path);
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
function lookCloser() {
|
|
818
|
+
return button("Look closer ▾", "quiet", goDeeper);
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function drawTrail(m) {
|
|
822
|
+
const trail = document.getElementById("trail");
|
|
823
|
+
trail.replaceChildren();
|
|
824
|
+
const p = m.pebble;
|
|
825
|
+
const names = {
|
|
826
|
+
line: p ? (p.line === null ? "Ready-made routine" : "Line " + p.line) : "Machine code",
|
|
827
|
+
instruction: m.halted ? "halted" : m.instruction.text,
|
|
828
|
+
part: partWords(shownPart(m)),
|
|
829
|
+
gate: "gates",
|
|
830
|
+
};
|
|
831
|
+
const deepest = DEPTHS.indexOf(look);
|
|
832
|
+
DEPTHS.slice(0, deepest + 1).forEach((depth, i) => {
|
|
833
|
+
if (i > 0) trail.append(el("span", "›", "muted"));
|
|
834
|
+
const crumb = button(names[depth], "", () => { pickedGate = null; setLook(depth, depth === "gate" ? gatesOf(m, shownPart(m)) : undefined); });
|
|
835
|
+
if (depth === look && look !== "gate") crumb.setAttribute("aria-current", "step");
|
|
836
|
+
trail.append(crumb);
|
|
837
|
+
});
|
|
838
|
+
if (look !== "gate") return;
|
|
839
|
+
// Inside the gates, every part on the way down is a crumb too.
|
|
840
|
+
const base = gatesOf(m, shownPart(m));
|
|
841
|
+
const under = gatePath === base || gatePath.startsWith(base + ".");
|
|
842
|
+
const start = under ? base : "";
|
|
843
|
+
const rest = (under ? gatePath.slice(base.length) : gatePath).split(".").filter((s) => s);
|
|
844
|
+
let at = start;
|
|
845
|
+
rest.forEach((name) => {
|
|
846
|
+
at = at ? at + "." + name : name;
|
|
847
|
+
const to = at;
|
|
848
|
+
trail.append(el("span", "›", "muted"));
|
|
849
|
+
trail.append(button(name, "", () => { pickedGate = null; setLook("gate", to); }));
|
|
850
|
+
});
|
|
851
|
+
trail.lastChild.setAttribute("aria-current", "step");
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
function drawGlass(m) {
|
|
855
|
+
document.getElementById("playing-note").hidden = !m.running;
|
|
856
|
+
document.getElementById("lens").hidden = m.running;
|
|
857
|
+
// The "just changed" label belongs to the picture that offered the button: any later
|
|
858
|
+
// move that did not change that same gate takes it away, so it can never go stale.
|
|
859
|
+
const g = m.last_gate;
|
|
860
|
+
if (!g || !pickedGate || g.id !== pickedGate.id || g.path !== pickedGate.path) pickedGate = null;
|
|
861
|
+
drawTrail(m);
|
|
862
|
+
if (m.running) { lensSeq++; return; }
|
|
863
|
+
drawLens(m);
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
function drawLens(m) {
|
|
867
|
+
const lens = document.getElementById("lens");
|
|
868
|
+
lens.replaceChildren();
|
|
869
|
+
drawShowGate(m, lens);
|
|
870
|
+
if (look === "line") lensLine(m, lens);
|
|
871
|
+
else if (look === "instruction") lensInstruction(m, lens);
|
|
872
|
+
else if (look === "part") lensPart(m, lens);
|
|
873
|
+
else lensGates(m, lens);
|
|
874
|
+
glowIn(lens);
|
|
875
|
+
outlineShow(m);
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
function drawShowGate(m, lens) {
|
|
879
|
+
const g = m.last_gate;
|
|
880
|
+
const slot = el("div");
|
|
881
|
+
const showGate = slot;
|
|
882
|
+
if (g) {
|
|
883
|
+
showGate.append(button("show this gate (gate " + g.id + ", now " + g.value + ", in " + g.path + ")", "quiet", () => {
|
|
884
|
+
pickedGate = { id: g.id, path: g.path };
|
|
885
|
+
setLook("gate", g.path);
|
|
886
|
+
}));
|
|
887
|
+
} else if (look === "gate" && m.note && m.note.endsWith(NO_GATE) && !(m.happened || "").includes(m.note)) {
|
|
888
|
+
// A gate step that ended on a clock wire (or an instruction's end): say why there is no button.
|
|
889
|
+
showGate.append(el("p", m.note, "muted"));
|
|
890
|
+
}
|
|
891
|
+
if (slot.childNodes.length) lens.append(slot);
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
function lensLine(m, lens) {
|
|
895
|
+
lensSeq++;
|
|
896
|
+
const p = m.pebble;
|
|
897
|
+
if (!p) {
|
|
898
|
+
lens.append(el("div", "Machine code", "big"), el("p", "This program is machine code, so it has no Pebble lines. Look closer to see its next instruction."), lookCloser());
|
|
899
|
+
return;
|
|
900
|
+
}
|
|
901
|
+
if (m.halted) {
|
|
902
|
+
lens.append(el("div", p.message + ".", "big"));
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
if (p.line === null) {
|
|
906
|
+
lens.append(el("div", "A ready-made routine", "big"), el("p", "Inside a ready-made routine (multiply, divide or print). It has no Pebble line of its own. Look closer to see its next instruction."), lookCloser());
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
const big = button("Line " + p.line + ": " + p.source[p.line - 1].trim(), "big", goDeeper);
|
|
910
|
+
big.title = "Look closer";
|
|
911
|
+
const rows = rowsOfLine(p.line);
|
|
912
|
+
lens.append(big);
|
|
913
|
+
if (rows.length) {
|
|
914
|
+
lens.append(el("p", "This one line is " + rows.length + " tiny instruction" + (rows.length === 1 ? "" : "s") + ". The next one to run is marked >."));
|
|
915
|
+
const table = el("table");
|
|
916
|
+
const body = el("tbody");
|
|
917
|
+
rows.forEach((r) => {
|
|
918
|
+
const row = instructionRow(r, m, false);
|
|
919
|
+
row.classList.add("clickable");
|
|
920
|
+
row.onclick = goDeeper;
|
|
921
|
+
body.append(row);
|
|
922
|
+
});
|
|
923
|
+
table.append(body);
|
|
924
|
+
lens.append(table);
|
|
925
|
+
}
|
|
926
|
+
lens.append(lookCloser());
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
function fieldValue(name, value, op, i) {
|
|
930
|
+
if (name === "opcode") return i.text.split(/\s+/)[0];
|
|
931
|
+
if (name === "rd" || name === "ra" || name === "rb") return "r" + value;
|
|
932
|
+
const width = SIGNED[name] || (name === "imm8" && op === ADDI ? 8 : 0);
|
|
933
|
+
if (width && value >= 1 << (width - 1)) return String(value - (1 << width));
|
|
934
|
+
return String(value);
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
function drawFields(i, lens) {
|
|
938
|
+
const op = i.word >> 12;
|
|
939
|
+
const bits = i.word.toString(2).padStart(16, "0");
|
|
940
|
+
const groups = [];
|
|
941
|
+
let next = 15;
|
|
942
|
+
["opcode", ...FIELDS[String(op)]].forEach((name) => {
|
|
943
|
+
const [hi, lo] = FIELD_BITS[name];
|
|
944
|
+
if (hi < next) groups.push([null, next, hi + 1]);
|
|
945
|
+
groups.push([name, hi, lo]);
|
|
946
|
+
next = lo - 1;
|
|
947
|
+
});
|
|
948
|
+
if (next >= 0) groups.push([null, next, 0]);
|
|
949
|
+
const box = el("div", undefined, "fields");
|
|
950
|
+
groups.forEach(([name, hi, lo]) => {
|
|
951
|
+
const column = el("div");
|
|
952
|
+
column.style.display = "grid";
|
|
953
|
+
const value = parseInt(bits.slice(15 - hi, 16 - lo), 2);
|
|
954
|
+
column.append(
|
|
955
|
+
el("span", bits.slice(15 - hi, 16 - lo), "bits"),
|
|
956
|
+
el("span", name === null ? "not used" : (name === "opcode" ? "job" : name), "name muted"),
|
|
957
|
+
el("span", name === null ? "" : fieldValue(name, value, op, i), "value"),
|
|
958
|
+
);
|
|
959
|
+
if (name) column.title = FIELD_TITLES[name];
|
|
960
|
+
box.append(column);
|
|
961
|
+
});
|
|
962
|
+
lens.append(box);
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
function drawRegisters(m, lens) {
|
|
966
|
+
const regs = el("div", undefined, "regs");
|
|
967
|
+
regs.id = "regs";
|
|
968
|
+
const box = (name, value, part, key) => {
|
|
969
|
+
const b = button(name + " " + value, "reg", () => gates(part));
|
|
970
|
+
b.title = "Look at the gates of " + name + " (" + hex(value) + ")";
|
|
971
|
+
b.dataset.glow = key;
|
|
972
|
+
regs.append(b);
|
|
973
|
+
};
|
|
974
|
+
m.registers.forEach((value, i) => box("r" + i, value, m.parts.registers[i], "r" + i));
|
|
975
|
+
box("pc", m.pc, m.parts.pc, "pc");
|
|
976
|
+
box("sp", m.sp, m.parts.sp, "sp");
|
|
977
|
+
const flags = el("div", undefined, "regs");
|
|
978
|
+
flags.id = "flag-lamps";
|
|
979
|
+
FLAGS.forEach((flag) => {
|
|
980
|
+
const lamp = el("span", flag + " " + m.flags[flag], "lamp" + (m.flags[flag] ? " on" : ""));
|
|
981
|
+
lamp.dataset.glow = "flag:" + flag;
|
|
982
|
+
flags.append(lamp);
|
|
983
|
+
});
|
|
984
|
+
lens.append(regs, flags);
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
function lensInstruction(m, lens) {
|
|
988
|
+
lensSeq++;
|
|
989
|
+
const i = m.instruction;
|
|
990
|
+
if (m.halted) {
|
|
991
|
+
lens.append(el("div", "Halted", "big"), el("p", "The machine has halted, so no instruction is next. pc is " + m.pc + "."));
|
|
992
|
+
} else if (i.word === null) {
|
|
993
|
+
lens.append(el("div", "Outside memory", "big"), el("p", "The next instruction's address, " + i.address + ", is outside memory."));
|
|
994
|
+
} else {
|
|
995
|
+
const big = button(i.text, "big", goDeeper);
|
|
996
|
+
big.id = "the-instruction";
|
|
997
|
+
big.title = "Look closer: the part of the CPU that does this instruction's main work";
|
|
998
|
+
lens.append(big, el("p", "the instruction at address " + i.address + (m.at_boundary ? ", next to run" : ", part-way through"), "muted"));
|
|
999
|
+
drawFields(i, lens);
|
|
1000
|
+
}
|
|
1001
|
+
drawRegisters(m, lens);
|
|
1002
|
+
if (!m.halted) lens.append(lookCloser());
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
async function lensPart(m, lens) {
|
|
1006
|
+
const path = shownPart(m);
|
|
1007
|
+
lens.append(el("p", "Next beat: " + m.phase + ". Every instruction takes two beats: a fetch, then an execute.", "muted"));
|
|
1008
|
+
const holder = el("div");
|
|
1009
|
+
lens.append(holder);
|
|
1010
|
+
const mine = ++lensSeq;
|
|
1011
|
+
try {
|
|
1012
|
+
const response = await fetch("/api/part?path=" + encodeURIComponent(path));
|
|
1013
|
+
if (mine !== lensSeq) return;
|
|
1014
|
+
if (!response.ok) {
|
|
1015
|
+
holder.append(el("p", "No one part of the CPU does this. Look closer to see all of the CPU's gates."), lookCloser());
|
|
1016
|
+
holder.append(el("h3", "Every part"), partList(m, path));
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
const part = await response.json();
|
|
1020
|
+
if (mine !== lensSeq) return;
|
|
1021
|
+
const side = (wires) => {
|
|
1022
|
+
const column = el("div", undefined, "wires");
|
|
1023
|
+
wires.forEach((w) => {
|
|
1024
|
+
const box = el("div", undefined, "wirebox");
|
|
1025
|
+
box.title = w.name;
|
|
1026
|
+
box.append(el("span", (TAP_WORDS[w.name] || w.name) + " "), el("strong", String(w.value)));
|
|
1027
|
+
column.append(box);
|
|
1028
|
+
});
|
|
1029
|
+
return column;
|
|
1030
|
+
};
|
|
1031
|
+
const middle = button(part.name, "partbox", goDeeper);
|
|
1032
|
+
middle.title = "Look closer: the gates that make the " + part.name + "'s outputs, in " + part.gates;
|
|
1033
|
+
const flow = el("div", undefined, "flow");
|
|
1034
|
+
flow.append(side(part.inputs), middle, side(part.outputs));
|
|
1035
|
+
holder.append(el("p", "What goes into the " + part.name + " and what comes out, read off its real wires:"), flow);
|
|
1036
|
+
if (part.gates !== part.path) {
|
|
1037
|
+
holder.append(el("p", "Its gates are in " + part.gates + ", the block its code builds, so Look closer opens " + part.gates + ".", "muted"));
|
|
1038
|
+
}
|
|
1039
|
+
holder.append(lookCloser(), drawBuiltBy(part.built_by, path), el("h3", "Every part"), partList(m, path));
|
|
1040
|
+
const pre = holder.querySelector(".built-code");
|
|
1041
|
+
if (pre && codeScroll.path === path) pre.scrollTop = codeScroll.top;
|
|
1042
|
+
if (part.path === "ram") {
|
|
1043
|
+
holder.append(el("p", "Its answer, out, is made in ram.read0 to ram.read15, near the top of Look closer's list.", "muted"));
|
|
1044
|
+
}
|
|
1045
|
+
outlineShow(latest);
|
|
1046
|
+
} catch (e) {
|
|
1047
|
+
showError(UNREACHABLE);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
function levelFor(p) {
|
|
1052
|
+
if (p in PATHS) return PATHS[p];
|
|
1053
|
+
let last = p.split(".").pop().replace(/#\d+$/, "");
|
|
1054
|
+
if (/^bit\d+$/.test(last)) last = "bit";
|
|
1055
|
+
else if (/^word\d+$/.test(last)) last = "word";
|
|
1056
|
+
else if (/^r\d$/.test(last)) last = "register";
|
|
1057
|
+
else if (/^(and|or|xor)_bus$/.test(last)) return ["A row of 16 identical gates, one per bit.", "Logic Gates from NAND (gates.md)"];
|
|
1058
|
+
else if (last === "mux_bus") return ["A row of choosers: each picks one of two wires, steered by a select wire.", "Choosing and Decoding (choosing-and-decoding.md)"];
|
|
1059
|
+
return LEVELS[last] || FALLBACK;
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
async function lensGates(m, lens) {
|
|
1063
|
+
const path = gatePath;
|
|
1064
|
+
const holder = el("div");
|
|
1065
|
+
lens.append(holder);
|
|
1066
|
+
const mine = ++lensSeq;
|
|
1067
|
+
try {
|
|
1068
|
+
const response = await fetch("/api/view?path=" + encodeURIComponent(path));
|
|
1069
|
+
if (mine !== lensSeq) return;
|
|
1070
|
+
if (!response.ok) { holder.append(el("p", "There is no part called " + path + ".", "muted")); return; }
|
|
1071
|
+
const view = await response.json();
|
|
1072
|
+
if (mine !== lensSeq) return;
|
|
1073
|
+
const [words, page] = levelFor(path);
|
|
1074
|
+
holder.append(el("p", words), el("p", "Read more: " + page, "muted"));
|
|
1075
|
+
if (view.gates.length > 0) holder.append(el("p", GATE_LINE[0] + " (" + GATE_LINE[1] + ")", "muted"));
|
|
1076
|
+
holder.append(el("h3", "Parts inside"));
|
|
1077
|
+
const parts = el("ul", undefined, "parts");
|
|
1078
|
+
// RAM's thousands of word parts are all alike: list the other parts first, so the
|
|
1079
|
+
// read blocks that make its answer are easy to find.
|
|
1080
|
+
const word = (c) => /^word\d+$/.test(c.name);
|
|
1081
|
+
[...view.children.filter((c) => !word(c)), ...view.children.filter(word)].forEach((child) => {
|
|
1082
|
+
const li = el("li");
|
|
1083
|
+
li.append(button(child.name + " - " + child.gate_count + " gates", "", () => { pickedGate = null; setLook("gate", path ? path + "." + child.name : child.name); }));
|
|
1084
|
+
parts.append(li);
|
|
1085
|
+
});
|
|
1086
|
+
if (view.children.length === 0) parts.append(el("li", "No smaller parts here.", "muted"));
|
|
1087
|
+
holder.append(parts, el("h3", "Gates here"));
|
|
1088
|
+
view.gates.forEach((g) => {
|
|
1089
|
+
const row = el("div", undefined, "gate");
|
|
1090
|
+
row.append(el("strong", "gate " + g.id));
|
|
1091
|
+
const wire = (label, id, value) => el("span", label + " w" + id + " = " + value, "wire" + (value ? " on" : ""));
|
|
1092
|
+
row.append(wire("in", g.a, g.value_a), wire("in", g.b, g.value_b), el("span", "NAND ->"), wire("out", g.out, g.value_out));
|
|
1093
|
+
if (pickedGate && g.id === pickedGate.id && path === pickedGate.path) {
|
|
1094
|
+
row.classList.add("picked");
|
|
1095
|
+
row.append(el("span", "the gate that just changed", "tag"));
|
|
1096
|
+
}
|
|
1097
|
+
holder.append(row);
|
|
1098
|
+
});
|
|
1099
|
+
if (view.gates.length === 0) holder.append(el("p", "No gates directly here, look in the parts above.", "muted"));
|
|
1100
|
+
outlineShow(latest);
|
|
1101
|
+
keepVisible(holder.querySelector(".gate.picked"));
|
|
1102
|
+
} catch (e) {
|
|
1103
|
+
showError(UNREACHABLE);
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
// ---- drawing a picture, and the controls ---------------------------------------
|
|
1108
|
+
|
|
1109
|
+
function drawStatus(m) {
|
|
1110
|
+
const status = document.getElementById("status");
|
|
1111
|
+
status.replaceChildren(el("span", m.running ? "playing" : "paused", "lamp" + (m.running ? " on" : "")));
|
|
1112
|
+
if (m.halted) {
|
|
1113
|
+
const why = m.fault ? m.fault.toLowerCase().replaceAll("_", " ") : (m.halt_code === 0 ? "finished" : "stopped");
|
|
1114
|
+
status.append(el("span", "halted: " + why + " (code " + m.halt_code + ")", "lamp on"));
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
function drawSaid(m) {
|
|
1119
|
+
document.getElementById("happened").textContent = m.happened || NOTHING_YET;
|
|
1120
|
+
// A no-gate note is the same sentence as `happened`, and the glass has its own spot for one.
|
|
1121
|
+
const noGate = m.note && m.note.endsWith(NO_GATE);
|
|
1122
|
+
const extra = m.note && m.note !== m.happened && !noGate ? m.note : "";
|
|
1123
|
+
document.getElementById("note").textContent = extra;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
function drawStep(m) {
|
|
1127
|
+
const step = document.getElementById("step");
|
|
1128
|
+
step.textContent = m.steps[look];
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
function setControls() {
|
|
1132
|
+
const running = latest ? latest.running : false;
|
|
1133
|
+
document.querySelectorAll("button.step").forEach((b) => { b.disabled = busy || running; });
|
|
1134
|
+
document.getElementById("step-into").disabled = busy || running;
|
|
1135
|
+
document.getElementById("play").disabled = busy || running;
|
|
1136
|
+
document.getElementById("pause").disabled = busy || !running;
|
|
1137
|
+
document.getElementById("count").disabled = busy || running;
|
|
1138
|
+
["load-example", "load-pebble", "load", "walk-next", "walk-back", "back-to-walk", "walk-leave", "explore", "try-again"].forEach((id) => { document.getElementById(id).disabled = busy; });
|
|
1139
|
+
const w = latest && latest.walk;
|
|
1140
|
+
if (w && w.step === 0) document.getElementById("walk-back").disabled = true;
|
|
1141
|
+
document.getElementById("step-into").hidden = !(w && w.trying && w.step_kind === "into" && look === "line");
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
// A new program starts the glass at its top depth; a walk sets its own.
|
|
1145
|
+
function startLook(m) {
|
|
1146
|
+
look = m.pebble ? "line" : "instruction";
|
|
1147
|
+
partPath = null;
|
|
1148
|
+
gatePath = gatesOf(m, m.parts.instruction);
|
|
1149
|
+
pickedGate = null;
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
function drawText(text) {
|
|
1153
|
+
if (text === latestText) return; // a button's answer and its event carry the same picture
|
|
1154
|
+
latestText = text;
|
|
1155
|
+
const m = JSON.parse(text);
|
|
1156
|
+
const before = latest;
|
|
1157
|
+
latest = m;
|
|
1158
|
+
if (!m.walk && (!before || before.program !== m.program)) startLook(m);
|
|
1159
|
+
followWalk(m);
|
|
1160
|
+
drawStatus(m);
|
|
1161
|
+
drawSaid(m);
|
|
1162
|
+
drawWalk(m);
|
|
1163
|
+
drawVariables(m);
|
|
1164
|
+
drawStack(m);
|
|
1165
|
+
document.getElementById("output").textContent = m.output || NOTHING_YET;
|
|
1166
|
+
if (listingIsStale(m)) fetchListing(m); else drawProgram(m);
|
|
1167
|
+
drawGlass(m);
|
|
1168
|
+
drawStep(m);
|
|
1169
|
+
drawChanged(m);
|
|
1170
|
+
setControls();
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
async function loadExamples() {
|
|
1174
|
+
try {
|
|
1175
|
+
const response = await fetch("/api/examples");
|
|
1176
|
+
if (!response.ok) return;
|
|
1177
|
+
const examples = await response.json();
|
|
1178
|
+
const select = document.getElementById("examples");
|
|
1179
|
+
examples.forEach((x) => {
|
|
1180
|
+
const option = el("option", x.title);
|
|
1181
|
+
option.value = x.name;
|
|
1182
|
+
select.append(option);
|
|
1183
|
+
});
|
|
1184
|
+
const own = el("option", "Write your own...");
|
|
1185
|
+
own.value = "*own";
|
|
1186
|
+
select.append(own);
|
|
1187
|
+
select.onchange = () => {
|
|
1188
|
+
if (select.value !== "*own") return;
|
|
1189
|
+
select.value = "";
|
|
1190
|
+
openExpert(true);
|
|
1191
|
+
};
|
|
1192
|
+
document.getElementById("load-example").onclick = () => {
|
|
1193
|
+
const chosen = examples.find((x) => x.name === select.value);
|
|
1194
|
+
if (chosen) send("/api/pebble", { source: chosen.source });
|
|
1195
|
+
};
|
|
1196
|
+
} catch (e) {
|
|
1197
|
+
showError(UNREACHABLE);
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
function openExpert(open, focusSource) {
|
|
1202
|
+
document.getElementById("expert").hidden = !open;
|
|
1203
|
+
document.getElementById("expert-button").setAttribute("aria-expanded", String(open));
|
|
1204
|
+
if (open && focusSource !== false) document.getElementById("source").focus();
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
document.querySelectorAll("button[data-size]").forEach((b) => {
|
|
1208
|
+
b.addEventListener("click", () => {
|
|
1209
|
+
const body = { size: b.dataset.size };
|
|
1210
|
+
if (b.dataset.count) body.count = Number(b.dataset.count);
|
|
1211
|
+
send("/api/step", body);
|
|
1212
|
+
});
|
|
1213
|
+
});
|
|
1214
|
+
document.getElementById("step").addEventListener("click", () => send("/api/step", { depth: look }));
|
|
1215
|
+
document.getElementById("step-into").addEventListener("click", () => send("/api/step", { size: "line_into" }));
|
|
1216
|
+
document.getElementById("rewind").addEventListener("click", () => send("/api/rewind", {}));
|
|
1217
|
+
document.getElementById("run").addEventListener("click", () => send("/api/run", { instructions: Number(document.getElementById("count").value) }));
|
|
1218
|
+
document.getElementById("play").addEventListener("click", () => send("/api/play", { speed: Number(document.getElementById("speed").value) }));
|
|
1219
|
+
document.getElementById("pause").addEventListener("click", () => send("/api/pause", {}));
|
|
1220
|
+
document.getElementById("load").addEventListener("click", () => send("/api/program", { source: document.getElementById("source").value }));
|
|
1221
|
+
document.getElementById("load-pebble").addEventListener("click", () => send("/api/pebble", { source: document.getElementById("source").value }));
|
|
1222
|
+
document.getElementById("expert-button").addEventListener("click", () => openExpert(document.getElementById("expert").hidden, false));
|
|
1223
|
+
document.getElementById("expert-close").addEventListener("click", () => openExpert(false));
|
|
1224
|
+
document.getElementById("walks-button").addEventListener("click", () => showWalks());
|
|
1225
|
+
document.getElementById("explore").addEventListener("click", () => {
|
|
1226
|
+
hideWalks();
|
|
1227
|
+
if (latest && latest.walk) send("/api/walk/leave", {});
|
|
1228
|
+
});
|
|
1229
|
+
document.getElementById("walk-leave").addEventListener("click", () => send("/api/walk/leave", {}));
|
|
1230
|
+
document.getElementById("walk-next").addEventListener("click", () => { const w = latest && latest.walk; if (w) openWalk(w.name, w.step + 1); });
|
|
1231
|
+
document.getElementById("walk-back").addEventListener("click", () => { const w = latest && latest.walk; if (w) openWalk(w.name, w.step - 1); });
|
|
1232
|
+
document.getElementById("back-to-walk").addEventListener("click", replayWalk);
|
|
1233
|
+
document.getElementById("try-again").addEventListener("click", replayWalk);
|
|
1234
|
+
window.addEventListener("hashchange", () => {
|
|
1235
|
+
if (!location.hash.startsWith("#walk=")) return;
|
|
1236
|
+
const name = walkInHash();
|
|
1237
|
+
if (name === null) showWalks(WALK_NOT_FOUND);
|
|
1238
|
+
else openWalk(name, 0, true);
|
|
1239
|
+
});
|
|
1240
|
+
|
|
1241
|
+
// The walk named in the address, or null when its escapes are malformed.
|
|
1242
|
+
function walkInHash() {
|
|
1243
|
+
try { return decodeURIComponent(location.hash.slice(6)); } catch (e) { return null; }
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
async function start() {
|
|
1247
|
+
// Read the address first: drawing a picture of a walk already open rewrites it.
|
|
1248
|
+
const linked = location.hash.startsWith("#walk=");
|
|
1249
|
+
const link = linked ? walkInHash() : "";
|
|
1250
|
+
await refresh();
|
|
1251
|
+
loadExamples();
|
|
1252
|
+
loadWalks();
|
|
1253
|
+
listen();
|
|
1254
|
+
if (link) openWalk(link, 0, true);
|
|
1255
|
+
else if (linked) showWalks(WALK_NOT_FOUND);
|
|
1256
|
+
else showWalks();
|
|
1257
|
+
}
|
|
1258
|
+
start();
|
|
1259
|
+
</script>
|
|
1260
|
+
</body>
|
|
1261
|
+
</html>
|