-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLayerNavigator.res
More file actions
382 lines (337 loc) · 8.67 KB
/
Copy pathLayerNavigator.res
File metadata and controls
382 lines (337 loc) · 8.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// SPDX-License-Identifier: MPL-2.0
// LayerNavigator.res - Navigate through abstraction layers
open Types
/**
* Layer Navigator
*
* Shows how code transforms through the 5 layers of abstraction:
* Grammar → Parser → AST → Semantics → Runtime
*
* Students can click any code element and see it across all layers.
* This teaches how abstractions work and where problems originate.
*/
// The five layers of abstraction
type layer =
| Grammar // EBNF rules that define what's valid
| Parser // How text becomes structure (parse tree)
| AST // Abstract syntax tree (simplified structure)
| Semantics // Type checking, scope analysis
| Runtime // Actual execution values
// Layer view representation
type layerView = {
layer: layer,
content: string,
highlighted: option<(int, int)>, // Start/end position in this layer
metadata: dict<string, string>,
}
// Navigation state - which layer we're currently viewing
type navigationState = {
currentLayer: layer,
selectedNode: option<string>, // ID of selected AST node
layerViews: array<layerView>,
}
/**
* Create layer views for a given AST node
*/
let createLayerViews = (node: stmt, sourceCode: string): array<layerView> => {
let views = []
// Layer 1: Grammar (EBNF rule that matched)
let grammarRule = getGrammarRule(node)
Array.push(views, {
layer: Grammar,
content: grammarRule,
highlighted: None,
metadata: Dict.fromArray([("rule-type", "statement")]),
})
// Layer 2: Parser (parse tree structure)
let parseTree = formatParseTree(node)
Array.push(views, {
layer: Parser,
content: parseTree,
highlighted: None,
metadata: Dict.fromArray([("tree-depth", "3")]),
})
// Layer 3: AST (abstract syntax tree node)
let astRepr = formatASTNode(node)
Array.push(views, {
layer: AST,
content: astRepr,
highlighted: None,
metadata: Dict.fromArray([("node-type", nodeTypeName(node))]),
})
// Layer 4: Semantics (type analysis)
let semanticInfo = analyzeSemantics(node)
Array.push(views, {
layer: Semantics,
content: semanticInfo,
highlighted: None,
metadata: Dict.fromArray([("type-check", "pending")]),
})
// Layer 5: Runtime (execution trace)
Array.push(views, {
layer: Runtime,
content: "Execution: [not yet run]",
highlighted: None,
metadata: Dict.fromArray([("state", "pending")]),
})
views
}
/**
* Get EBNF grammar rule for a statement
*/
let getGrammarRule = (stmt: stmt): string => {
switch stmt {
| LetStmt({mutable_, _}) =>
if mutable_ {
`letStmt ::= "let" "mut" identifier "=" expression`
} else {
`letStmt ::= "let" identifier "=" expression`
}
| IfStmt(_) =>
`ifStmt ::= "if" expression
statement*
("elseif" expression statement*)*
("else" statement*)?
"end"`
| WhileStmt(_) =>
`whileStmt ::= "while" expression
statement*
"end"`
| ForStmt(_) =>
`forStmt ::= "for" identifier "in" expression
statement*
"end"`
| PrintStmt({println, _}) =>
if println {
`printStmt ::= "println" "(" expression ("," expression)* ")"`
} else {
`printStmt ::= "print" "(" expression ("," expression)* ")"`
}
| GutterBlock(_) =>
`gutterBlock ::= "gutter"
statement*
"end"`
| ExprStmt(_) =>
`exprStmt ::= expression`
| _ =>
`statement ::= /* unknown */`
}
}
/**
* Format parse tree for display
*/
let formatParseTree = (stmt: stmt): string => {
switch stmt {
| LetStmt({name, value, mutable_, _}) =>
let mutStr = if mutable_ { "mut " } else { "" }
`letStmt
├─ "let"
├─ ${mutStr}identifier("${name}")
├─ "="
└─ ${formatExprParseTree(value, 1)}`
| PrintStmt({println, args, _}) =>
let fname = if println { "println" } else { "print" }
`printStmt
├─ "${fname}"
├─ "("
├─ args: ${Int.toString(Array.length(args))}
└─ ")"`
| _ =>
`statement (simplified)`
}
}
and formatExprParseTree = (expr: expr, depth: int): string => {
let indent = String.repeat(" ", depth)
switch expr {
| IntLit(n, _) =>
`literal(${Int.toString(n)})`
| StringLit(s, _) =>
`literal("${s}")`
| Ident(name, _) =>
`identifier("${name}")`
| Binary(left, op, right, _) =>
`binary
${indent}├─ ${formatExprParseTree(left, depth + 1)}
${indent}├─ operator(${binaryOpToString(op)})
${indent}└─ ${formatExprParseTree(right, depth + 1)}`
| _ =>
`expression`
}
}
/**
* Format AST node for display
*/
let formatASTNode = (stmt: stmt): string => {
switch stmt {
| LetStmt({name, value, type_, mutable_, loc}) =>
let typeStr = switch type_ {
| Some(t) => `: ${typeExprToString(t)}`
| None => ""
}
`LetStmt {
name: "${name}",
mutable: ${mutable_ ? "true" : "false"},
type: ${typeStr},
value: ${formatExprAST(value)},
loc: line ${Int.toString(loc.start.line)}
}`
| PrintStmt({println, args, _}) =>
`PrintStmt {
println: ${println ? "true" : "false"},
args: [${Int.toString(Array.length(args))} expressions]
}`
| _ =>
`Statement { ... }`
}
}
and formatExprAST = (expr: expr): string => {
switch expr {
| IntLit(n, _) => `IntLit(${Int.toString(n)})`
| StringLit(s, _) => `StringLit("${s}")`
| Ident(name, _) => `Ident("${name}")`
| Binary(left, op, right, _) =>
`Binary(${formatExprAST(left)}, ${binaryOpToString(op)}, ${formatExprAST(right)})`
| _ => `Expr(...)`
}
}
/**
* Analyze semantics for a node
*/
let analyzeSemantics = (stmt: stmt): string => {
switch stmt {
| LetStmt({name, value, type_, _}) =>
let inferredType = inferExprType(value)
let typeCheck = switch type_ {
| Some(annotated) =>
if typeExprsMatch(annotated, inferredType) {
`✓ Type check passed: ${typeExprToString(annotated)}`
} else {
`✗ Type mismatch: expected ${typeExprToString(annotated)}, got ${typeExprToString(inferredType)}`
}
| None =>
`Type inferred: ${typeExprToString(inferredType)}`
}
`Variable: ${name}
Scope: local
${typeCheck}`
| _ =>
`Semantic analysis: [pending]`
}
}
/**
* Infer type of an expression (simplified)
*/
let inferExprType = (expr: expr): typeExpr => {
switch expr {
| IntLit(_, _) => TyInt
| FloatLit(_, _) => TyFloat
| StringLit(_, _) => TyString
| BoolLit(_, _) => TyBool
| _ => TyInt // Simplified
}
}
/**
* Check if two type expressions match
*/
let typeExprsMatch = (t1: typeExpr, t2: typeExpr): bool => {
switch (t1, t2) {
| (TyInt, TyInt) => true
| (TyFloat, TyFloat) => true
| (TyString, TyString) => true
| (TyBool, TyBool) => true
| _ => false
}
}
/**
* Convert type expression to string
*/
let typeExprToString = (t: typeExpr): string => {
switch t {
| TyInt => "Int"
| TyFloat => "Float"
| TyString => "String"
| TyBool => "Bool"
| TyArray(inner) => `Array<${typeExprToString(inner)}>`
| TyEcho(a, b) =>
switch (a, b) {
| (None, _) => "Echo"
| (Some(ta), None) => `Echo<${typeExprToString(ta)}>`
| (Some(ta), Some(tb)) => `Echo<${typeExprToString(ta)}, ${typeExprToString(tb)}>`
}
| TyEchoResidue(a, b) =>
switch (a, b) {
| (None, _) => "EchoR"
| (Some(ta), None) => `EchoR<${typeExprToString(ta)}>`
| (Some(ta), Some(tb)) => `EchoR<${typeExprToString(ta)}, ${typeExprToString(tb)}>`
}
| TyIdent(name) => name
}
}
/**
* Get node type name
*/
let nodeTypeName = (stmt: stmt): string => {
switch stmt {
| LetStmt(_) => "LetStmt"
| AssignStmt(_) => "AssignStmt"
| IfStmt(_) => "IfStmt"
| WhileStmt(_) => "WhileStmt"
| ForStmt(_) => "ForStmt"
| PrintStmt(_) => "PrintStmt"
| GutterBlock(_) => "GutterBlock"
| ExprStmt(_) => "ExprStmt"
| _ => "Statement"
}
}
/**
* Binary operator to string
*/
let binaryOpToString = (op: binaryOp): string => {
switch op {
| Add => "+"
| Sub => "-"
| Mul => "*"
| Div => "/"
| Mod => "%"
| Eq => "=="
| Neq => "!="
| Lt => "<"
| Gt => ">"
| Lte => "<="
| Gte => ">="
| _ => "op"
}
}
/**
* Navigate to a specific layer
*/
let navigateToLayer = (state: navigationState, targetLayer: layer): navigationState => {
{
...state,
currentLayer: targetLayer,
}
}
/**
* Get layer name for display
*/
let layerName = (layer: layer): string => {
switch layer {
| Grammar => "Grammar (EBNF)"
| Parser => "Parser (Parse Tree)"
| AST => "AST (Abstract Syntax)"
| Semantics => "Semantics (Type Check)"
| Runtime => "Runtime (Execution)"
}
}
/**
* Get layer index (for visualization)
*/
let layerIndex = (layer: layer): int => {
switch layer {
| Grammar => 0
| Parser => 1
| AST => 2
| Semantics => 3
| Runtime => 4
}
}