This repository was archived by the owner on Nov 7, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathsimulation.ts
More file actions
2300 lines (2133 loc) · 92.7 KB
/
Copy pathsimulation.ts
File metadata and controls
2300 lines (2133 loc) · 92.7 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Port von `VisuStructSimulationEngine.swift`: führt ein Struktogramm Schritt für Schritt aus.
* Verzweigungen und Schleifen ersetzen sich beim Ausführen durch die Schritte ihres Rumpfs.
*/
import { ElementType, type VSCase, type VSDocument, type VSElement } from './model'
import { MBOT_COMMANDS, MBOT_SENSORS, makeMBotAction, mbotArguments, parseMBotCommand, substituteMBotSensors, type MBotAction, type MBotSensorValues } from './mbot'
export type SimValue =
| { kind: 'int'; value: number }
| { kind: 'double'; value: number }
| { kind: 'string'; value: string }
| { kind: 'boolean'; value: boolean }
| { kind: 'intArray'; value: number[] }
| { kind: 'doubleArray'; value: number[] }
| { kind: 'stringArray'; value: string[] }
| { kind: 'booleanArray'; value: boolean[] }
/** Zweidimensionales Array (`boolean[][] sitze`): Zeilen, darin die Werte. */
| { kind: 'grid'; elementType: SimValueType; value: (number | string | boolean)[][] }
/** `new Scanner(new File(…))` oder `new BufferedReader(new FileReader(…))`: liest Zeile für Zeile, `next` ist die nächste. */
| { kind: 'reader'; className: 'Scanner' | 'BufferedReader'; file: string; lines: string[]; next: number }
/** `new PrintWriter(…)`: sammelt Text, der erst mit `close()` in der Datei landet (wie in Java). */
| { kind: 'writer'; file: string; text: string }
/** `null`, z. B. von `readLine()` am Ende der Datei. */
| { kind: 'null' }
export type SimValueType = 'int' | 'double' | 'string' | 'boolean'
export type StepKind =
| 'statement'
| 'branch'
| 'switchSelection'
| 'forLoopStart'
| 'forLoopCondition'
| 'forLoopIncrement'
| 'whileLoop'
| 'doUntilLoop'
| 'doUntilCondition'
| 'infiniteLoop'
| 'jump'
| 'call'
| 'callEnd'
export interface SimStep {
path: number[]
text: string
kind: StepKind
cases?: VSCase[]
loopBody?: VSElement[]
forParts?: string[]
/** Aufrufebene: 0 ist das Hauptprogramm, jeder Aufruf bekommt eine neue Nummer. */
frame?: number
/** Im Unterprogramm: Pfad des Aufruf-Kastens im Hauptprogramm, der markiert bleibt. */
callPath?: number[]
}
/** Sucht zum Text eines Aufruf-Kastens das passende Diagramm (z. B. einen offenen Reiter). */
export type SubprogramResolver = (name: string) => VSDocument | undefined
/** Ab dieser Tiefe bricht die Simulation ab (vermutlich ein Aufruf, der sich selbst aufruft). */
export const maxCallDepth = 100
export interface InputRequest {
variableName: string
valueType: SimValueType
prompt: string
/** Wie in Java hinter `System.out.print("Note: ")`: Die Eingabe steht in derselben Zeile wie diese Ausgabe. */
continuesLine?: boolean
/** Pseudocode: Die Frage gehört zu einer Bedingung, die Antwort (true/false) entscheidet den Weg. */
decision?: boolean
}
/** Meldungen der Simulation, unabhängig von der Sprache. */
export type SimNotice =
| { kind: 'finished' }
| { kind: 'infiniteLoopWithoutBody' }
| { kind: 'unsupportedStatement'; text: string }
| { kind: 'invalidExpression'; text: string }
| { kind: 'unknownVariable'; text: string }
| { kind: 'divisionByZero' }
| { kind: 'wholeNumberExpected' }
| { kind: 'numberExpected' }
| { kind: 'booleanExpected' }
| { kind: 'subprogramNotFound'; text: string }
| { kind: 'callTooDeep' }
/** Die Werte in den Klammern passen nicht zur Kopfzeile des Unterprogramms. */
| { kind: 'callArguments'; text: string }
/** Ein Unterprogramm mit Rückgabetyp endet ohne `return`. */
| { kind: 'missingReturn'; text: string }
/** `Files.readString(Path.of("…"))` mit einem Namen, den es nicht gibt. */
| { kind: 'fileNotFound'; text: string }
/** `nextLine()`, obwohl die Datei zu Ende ist (in Java eine NoSuchElementException). */
| { kind: 'endOfFile'; text: string }
/** Eine Methode auf `null` (in Java eine NullPointerException). */
| { kind: 'nullValue'; text: string }
| { kind: 'other'; text: string }
export interface SimState {
stepIndex: number
variables: Map<string, SimValue>
outputLines: string[]
/** Die letzte Ausgabe war `System.out.print(…)`: Die nächste Ausgabe schreibt in derselben Zeile weiter. */
outputLineOpen?: boolean
inputRequest?: InputRequest
/** Fehler zur letzten Eingabe (z. B. keine Zahl). */
inputErrorNotice?: SimNotice
lastTrace?: string
/** Hinweis nach dem letzten Schritt (Ende, Fehler). */
notice?: SimNotice
/** Nach einem Fehler bleibt die Simulation auf dem fehlerhaften Schritt stehen. */
isHalted: boolean
/** Dateien, die das Programm geschrieben hat (Name → Inhalt). */
files: Map<string, string>
/** Befehle an den mBot2 in der Reihenfolge der Schritte (`mbot.forward(10)` usw.). */
robotActions: MBotAction[]
}
export function noticeEnglish(n: SimNotice): string {
switch (n.kind) {
case 'finished': return 'Simulation finished.'
case 'infiniteLoopWithoutBody': return 'Infinite loop has no body.'
case 'unsupportedStatement': return `Unsupported statement: ${n.text}`
case 'invalidExpression': return `Invalid expression: ${n.text}`
case 'unknownVariable': return `Unknown variable: ${n.text}`
case 'divisionByZero': return 'Division by zero.'
case 'wholeNumberExpected': return 'Please enter a whole number.'
case 'numberExpected': return 'Please enter a number.'
case 'booleanExpected': return 'Please enter true or false.'
case 'subprogramNotFound': return `No open diagram is called ${n.text}. The call was skipped.`
case 'callTooDeep': return 'Too many nested calls. Does a subprogram call itself?'
case 'callArguments': return `The call does not match the header of ${n.text}. Check the values in the parentheses.`
case 'missingReturn': return `${n.text} ended without returning a value with return.`
case 'fileNotFound': return `There is no file called ${n.text}.`
case 'endOfFile': return `The file ${n.text} has no more lines.`
case 'nullValue': return `${n.text} is null.`
case 'other': return n.text
}
}
export function noticeGerman(n: SimNotice): string {
switch (n.kind) {
case 'finished': return 'Simulation beendet.'
case 'infiniteLoopWithoutBody': return 'Die Endlosschleife hat keinen Rumpf.'
case 'unsupportedStatement': return `Nicht unterstützte Anweisung: ${n.text}`
case 'invalidExpression': return `Ungültiger Ausdruck: ${n.text}`
case 'unknownVariable': return `Unbekannte Variable: ${n.text}`
case 'divisionByZero': return 'Division durch null.'
case 'wholeNumberExpected': return 'Bitte eine ganze Zahl eingeben.'
case 'numberExpected': return 'Bitte eine Zahl eingeben.'
case 'booleanExpected': return 'Bitte true oder false eingeben.'
case 'subprogramNotFound': return `Kein offenes Diagramm heißt ${n.text}. Der Aufruf wurde übersprungen.`
case 'callTooDeep': return 'Zu viele verschachtelte Aufrufe. Ruft sich ein Unterprogramm selbst auf?'
case 'callArguments': return `Der Aufruf passt nicht zur Kopfzeile von ${n.text}. Prüfe die Werte in den Klammern.`
case 'missingReturn': return `${n.text} hat keinen Wert mit return zurückgegeben.`
case 'fileNotFound': return `Es gibt keine Datei ${n.text}.`
case 'endOfFile': return `Die Datei ${n.text} hat keine Zeile mehr.`
case 'nullValue': return `${n.text} ist null.`
case 'other': return n.text
}
}
class SimulationError extends Error {
constructor(readonly notice: SimNotice) {
super(noticeEnglish(notice))
}
}
const unsupported = (text: string) => new SimulationError({ kind: 'unsupportedStatement', text })
const invalid = (text: string) => new SimulationError({ kind: 'invalidExpression', text })
const unknownVar = (text: string) => new SimulationError({ kind: 'unknownVariable', text })
const divByZero = () => new SimulationError({ kind: 'divisionByZero' })
/** Textdateien, die Java mit `Files.readString(Path.of("name"))` liest, z. B. aus einer Lektion. */
const textFiles = new Map<string, string>()
export function registerTextFile(name: string, content: string) {
textFiles.set(name, content)
}
export const textFileEntries = (): [string, string][] => [...textFiles]
function toNotice(error: unknown): SimNotice {
if (error instanceof SimulationError) return error.notice
return { kind: 'other', text: error instanceof Error ? error.message : String(error) }
}
// MARK: - Werte
/** `%.12g` wie in C. */
function formatG12(value: number): string {
if (value === 0) return '0'
if (!Number.isFinite(value)) return Number.isNaN(value) ? 'nan' : value > 0 ? 'inf' : '-inf'
const exp = Math.floor(Math.log10(Math.abs(Number(value.toPrecision(12)))))
if (exp < -4 || exp >= 12) {
const [mantissa, e] = value.toExponential(11).split('e')
const m = mantissa.includes('.') ? mantissa.replace(/0+$/, '').replace(/\.$/, '') : mantissa
const n = Number(e)
return `${m}e${n < 0 ? '-' : '+'}${String(Math.abs(n)).padStart(2, '0')}`
}
const fixed = value.toFixed(Math.max(0, 11 - exp))
return fixed.includes('.') ? fixed.replace(/0+$/, '').replace(/\.$/, '') : fixed
}
function formatDouble(value: number): string {
if (Number.isFinite(value) && Math.round(value) === value) return value.toFixed(1)
return formatG12(value)
}
export function describeValue(v: SimValue): string {
switch (v.kind) {
case 'int': return String(v.value)
case 'double': return formatDouble(v.value)
case 'string': return v.value
case 'boolean': return String(v.value)
case 'intArray': return '[' + v.value.map(String).join(', ') + ']'
case 'doubleArray': return '[' + v.value.map(formatDouble).join(', ') + ']'
case 'stringArray': return '[' + v.value.join(', ') + ']'
case 'booleanArray': return '[' + v.value.map(String).join(', ') + ']'
case 'grid': return '[' + describeRows(v).join(', ') + ']'
case 'reader': return `${v.className}(${v.file})`
case 'writer': return `PrintWriter(${v.file})`
case 'null': return 'null'
}
}
/** Ein 2D-Array Zeile für Zeile, z. B. für die Anzeige unter Variablen. */
export function describeRows(v: SimValue & { kind: 'grid' }): string[] {
return v.value.map((row) => '[' + row.map((x) => describeValue(elementValue(v.elementType, x))).join(', ') + ']')
}
function elementValue(type: SimValueType, raw: number | string | boolean): SimValue {
switch (type) {
case 'int': return { kind: 'int', value: raw as number }
case 'double': return { kind: 'double', value: raw as number }
case 'string': return { kind: 'string', value: raw as string }
case 'boolean': return { kind: 'boolean', value: raw as boolean }
}
}
function elementDefault(type: SimValueType): number | string | boolean {
return type === 'string' ? '' : type === 'boolean' ? false : 0
}
function isArrayValue(v: SimValue): boolean {
return v.kind === 'intArray' || v.kind === 'doubleArray' || v.kind === 'stringArray' || v.kind === 'booleanArray' || v.kind === 'grid'
}
function asDouble(v: SimValue): number {
return v.kind === 'int' || v.kind === 'double' ? v.value : NaN
}
const int = (value: number): SimValue => ({ kind: 'int', value })
const dbl = (value: number): SimValue => ({ kind: 'double', value })
// MARK: - Zeichenklassen
const isWhitespace = (c: string | undefined) => c !== undefined && /\s/u.test(c)
const isLetter = (c: string) => /\p{L}/u.test(c)
const isNumberChar = (c: string) => /\p{N}/u.test(c)
function isIdentifier(text: string): boolean {
const chars = Array.from(text)
if (chars.length === 0 || !(isLetter(chars[0]) || chars[0] === '_')) return false
return chars.every((c) => isLetter(c) || isNumberChar(c) || c === '_')
}
function valueTypeKeyword(text: string): SimValueType | undefined {
switch (text.toLowerCase()) {
case 'int': return 'int'
case 'double': return 'double'
case 'string': return 'string'
// Ein `char` ist in VisuStruct ein String mit genau einem Zeichen.
case 'char': return 'string'
case 'boolean': case 'bool': return 'boolean'
default: return undefined
}
}
function valueTypeOf(v: SimValue): SimValueType {
return v.kind === 'int' ? 'int' : v.kind === 'double' ? 'double' : v.kind === 'boolean' ? 'boolean' : 'string'
}
function unquotedString(text: string): string | undefined {
const chars = Array.from(text)
// Zeichenliteral wie in Java: 'a'
if (chars.length === 3 && chars[0] === "'" && chars[2] === "'") return chars[1]
if (chars.length < 2 || chars[0] !== '"' || chars[chars.length - 1] !== '"') return undefined
const inner = chars.slice(1, -1).join('')
// `"a\"" + b + "\"c"` beginnt und endet auch mit `"`, ist aber kein einzelnes Literal.
if (!/^(?:[^"\\]|\\.)*$/u.test(inner)) return undefined
return inner.replaceAll('\\"', '"').replaceAll('\\n', '\n')
}
function normalizeNumericExpression(expression: string): string {
return expression.replaceAll('(int)', '').replaceAll('(double)', '').trim()
}
/** Für jedes Zeichen: liegt es außerhalb von Klammern und String-Literalen? */
function topLevelMask(chars: string[]): boolean[] {
const mask = new Array<boolean>(chars.length).fill(false)
let depth = 0
let inString = false
let escaped = false
chars.forEach((c, i) => {
if (inString) {
if (escaped) escaped = false
else if (c === '\\') escaped = true
else if (c === '"') inString = false
return
}
switch (c) {
case '"': inString = true; break
case '(': case '[': depth += 1; break
case ')': case ']': depth -= 1; break
default: mask[i] = depth === 0
}
})
return mask
}
function splitTopLevel(expression: string, separator: string): string[] {
const chars = Array.from(expression)
const sep = Array.from(separator)
const mask = topLevelMask(chars)
const parts: string[] = []
let current: string[] = []
let i = 0
while (i < chars.length) {
const end = i + sep.length
if (end <= chars.length && sep.every((s, k) => chars[i + k] === s) && mask.slice(i, end).every(Boolean)) {
parts.push(current.join('').trim())
current = []
i = end
continue
}
current.push(chars[i])
i += 1
}
parts.push(current.join('').trim())
return parts
}
/** Erster Vergleichsoperator außerhalb von Klammern und Strings. */
function splitComparison(expression: string): { lhs: string; op: string; rhs: string } | undefined {
const chars = Array.from(expression)
const mask = topLevelMask(chars)
for (let i = 0; i < chars.length; i++) {
if (!mask[i]) continue
let op: string | undefined
if (i + 1 < chars.length && mask[i + 1]) {
const pair = chars[i] + chars[i + 1]
if (['>=', '<=', '==', '!='].includes(pair)) op = pair
}
if (op === undefined && (chars[i] === '<' || chars[i] === '>')) op = chars[i]
if (op === undefined) continue
const lhs = chars.slice(0, i).join('').trim()
const rhs = chars.slice(i + op.length).join('').trim()
return { lhs, op, rhs }
}
return undefined
}
/** Index der `)`, die die `(` bei `openIndex` schließt. */
function matchingCloseParenthesis(chars: string[], openIndex: number): number | undefined {
let depth = 0
let inString = false
let escaped = false
for (let i = openIndex; i < chars.length; i++) {
const c = chars[i]
if (inString) {
if (escaped) escaped = false
else if (c === '\\') escaped = true
else if (c === '"') inString = false
continue
}
if (c === '"') inString = true
else if (c === '(') depth += 1
else if (c === ')') {
depth -= 1
if (depth === 0) return i
}
}
return undefined
}
/** `(a || b)` → `a || b`; `(a) && (b)` bleibt unverändert. */
function innerOfOuterParentheses(text: string): string | undefined {
const chars = Array.from(text)
if (chars[0] !== '(' || chars[chars.length - 1] !== ')' || matchingCloseParenthesis(chars, 0) !== chars.length - 1) {
return undefined
}
return chars.slice(1, -1).join('').trim()
}
/** Java-Stil `name.equals("Anna")`. */
function parseEqualsCall(text: string): { lhs: string; rhs: string } | undefined {
const chars = Array.from(text)
const marker = Array.from('.equals(')
if (chars[chars.length - 1] !== ')') return undefined
const mask = topLevelMask(chars)
for (let i = 0; i < chars.length; i++) {
if (!mask[i] || i + marker.length > chars.length) continue
if (!marker.every((m, k) => chars[i + k] === m)) continue
const openIndex = i + marker.length - 1
if (matchingCloseParenthesis(chars, openIndex) !== chars.length - 1) continue
return {
lhs: chars.slice(0, i).join('').trim(),
rhs: chars.slice(openIndex + 1, -1).join('').trim(),
}
}
return undefined
}
function stripConditionKeyword(text: string): string {
const trimmed = text.trim()
for (const keyword of ['if', 'while', 'until', 'switch']) {
if (!trimmed.startsWith(keyword)) continue
const after = trimmed.slice(keyword.length)
if (!(after === '' || isWhitespace(after[0]) || after[0] === '(')) continue
let stripped = after.trim()
const inner = innerOfOuterParentheses(stripped)
if (inner !== undefined) stripped = inner
return stripped === '' ? 'true' : stripped
}
return trimmed === '' ? 'true' : trimmed
}
interface ArrayElementAccess {
arrayName: string
/** Ein Index bei `a[i]`, zwei bei `a[i][j]`. */
indexExpressions: string[]
}
/** `name[…]` oder `name[…][…]`, und zwar der ganze Text (nicht etwa `a[i] > a[i + 1]`). */
function parseArrayElementAccess(text: string): ArrayElementAccess | undefined {
const trimmed = text.trim()
const open = trimmed.indexOf('[')
if (!trimmed.endsWith(']') || open < 0) return undefined
const name = trimmed.slice(0, open).trim()
if (!isIdentifier(name)) return undefined
const indexExpressions: string[] = []
let i = open
while (i < trimmed.length) {
if (trimmed[i] !== '[') return undefined
let depth = 0
let close = -1
for (let k = i; k < trimmed.length; k++) {
if (trimmed[k] === '[') depth += 1
else if (trimmed[k] === ']' && --depth === 0) {
close = k
break
}
}
if (close < 0) return undefined
indexExpressions.push(trimmed.slice(i + 1, close))
i = close + 1
while (i < trimmed.length && isWhitespace(trimmed[i])) i += 1
}
if (indexExpressions.length > 2) return undefined
return { arrayName: name, indexExpressions }
}
/** `ziel.methode(arg, arg)` als Ganzes; das Ziel ist ein Name, ein Arrayfach oder ein String-Literal. */
function parseMethodCall(text: string): { target: string; method: string; args: string[] } | undefined {
const trimmed = text.trim()
if (!trimmed.endsWith(')')) return undefined
const m = /^([A-Za-z_]\w*(?:\s*\[[^\[\]]*\])*|"(?:[^"\\]|\\.)*")\s*\.\s*([A-Za-z_]\w*)\s*\(/u.exec(trimmed)
if (!m) return undefined
const chars = Array.from(trimmed)
const open = Array.from(m[0]).length - 1
if (matchingCloseParenthesis(chars, open) !== chars.length - 1) return undefined
const inner = chars.slice(open + 1, -1).join('').trim()
return { target: m[1], method: m[2], args: inner === '' ? [] : splitTopLevel(inner, ',') }
}
function isAssignableTarget(text: string): boolean {
return isIdentifier(text) || parseArrayElementAccess(text) !== undefined
}
function splitByPlusOutsideQuotes(expression: string): string[] {
const parts: string[] = []
let current = ''
let inString = false
let escaped = false
let depth = 0
for (const c of expression) {
if (escaped) {
current += c
escaped = false
continue
}
if (c === '\\') {
current += c
escaped = true
continue
}
if (c === '"') {
inString = !inString
current += c
continue
}
if (!inString && c === '(') depth += 1
if (!inString && c === ')') depth -= 1
if (c === '+' && !inString && depth === 0) {
parts.push(current)
current = ''
continue
}
current += c
}
if (inString) throw invalid(expression)
parts.push(current)
return parts
}
/** Teilt an Kommas, die nicht in geschweiften Klammern stehen: `{1, 2}, {3, 4}` → zwei Teile. */
function splitTopLevelBraces(text: string): string[] {
const parts: string[] = []
let depth = 0
let current = ''
for (const c of text) {
if (c === '{') depth += 1
if (c === '}') depth -= 1
if (c === ',' && depth === 0) {
parts.push(current)
current = ''
continue
}
current += c
}
if (current.trim() !== '') parts.push(current)
return parts
}
// MARK: - Zahlenausdrücke
type Token =
| { t: 'number'; literal: string; value: number }
| { t: 'identifier'; name: string }
| { t: '+' | '-' | '*' | '/' | '%' | '.' | '(' | ')' | '[' | ']' }
function tokenize(expression: string): Token[] {
const chars = Array.from(expression)
const tokens: Token[] = []
let i = 0
while (i < chars.length) {
const c = chars[i]
if (isWhitespace(c)) {
i += 1
continue
}
if (isNumberChar(c) || (c === '.' && i + 1 < chars.length && isNumberChar(chars[i + 1]))) {
const start = i
let dots = 0
while (i < chars.length) {
if (chars[i] === '.') {
dots += 1
if (dots > 1) throw invalid(expression)
} else if (!isNumberChar(chars[i])) {
break
}
i += 1
}
const literal = chars.slice(start, i).join('')
if (literal === '.' || !/^[0-9]*\.?[0-9]*$/.test(literal)) throw invalid(expression)
tokens.push({ t: 'number', literal, value: Number(literal) })
continue
}
if (isLetter(c) || c === '_') {
const start = i
while (i < chars.length && (isLetter(chars[i]) || isNumberChar(chars[i]) || chars[i] === '_')) i += 1
tokens.push({ t: 'identifier', name: chars.slice(start, i).join('') })
continue
}
// Zeichenliteral wie in Java: in einer Rechnung zählt sein Zeichencode, also 'A' = 65
if (c === "'" && chars[i + 2] === "'" && chars[i + 1] !== undefined) {
const code = chars[i + 1].codePointAt(0)!
tokens.push({ t: 'number', literal: String(code), value: code })
i += 3
continue
}
if ('+-*/%.()[]'.includes(c)) {
tokens.push({ t: c as '+' })
i += 1
continue
}
throw invalid(expression)
}
return tokens
}
type Num = { v: number; int: boolean }
/** Zeichencode eines `char` (String mit genau einem Zeichen) wie in Java, wenn damit gerechnet wird; sonst `undefined`. */
function charCode(text: string | undefined): number | undefined {
const chars = text === undefined ? [] : Array.from(text)
return chars.length === 1 ? chars[0].codePointAt(0) : undefined
}
class NumericParser {
private index = 0
constructor(private tokens: Token[], private variables: Map<string, SimValue>) {}
parseInt(): number {
const value = this.expression().v
if (this.index !== this.tokens.length) throw invalid('')
if (!Number.isFinite(value)) throw invalid('')
return Math.trunc(value)
}
parseDouble(): number {
return this.parseNumber().v
}
/** Wert samt Angabe, ob er wie in Java ganzzahlig ist (nur `int`-Werte und Literale ohne Punkt). */
parseNumber(): Num {
const value = this.expression()
if (this.index !== this.tokens.length) throw invalid('')
return value
}
private get current(): Token | undefined {
return this.tokens[this.index]
}
/** Wie `current`, aber ohne Typverengung durch TypeScript nach vorherigen Prüfungen. */
private kind(): Token['t'] | undefined {
return this.tokens[this.index]?.t
}
private isIdent(name: string): boolean {
const c = this.current
return c?.t === 'identifier' && c.name === name
}
private expression(): Num {
let value = this.term()
for (let tok = this.current; tok && (tok.t === '+' || tok.t === '-'); tok = this.current) {
this.index += 1
const rhs = this.term()
value = { v: tok.t === '+' ? value.v + rhs.v : value.v - rhs.v, int: value.int && rhs.int }
}
return value
}
private term(): Num {
let value = this.factor()
for (let tok = this.current; tok && (tok.t === '*' || tok.t === '/' || tok.t === '%'); tok = this.current) {
this.index += 1
const rhs = this.factor()
const bothInt = value.int && rhs.int
if (tok.t === '*') {
value = { v: value.v * rhs.v, int: bothInt }
} else {
if (rhs.v === 0) throw divByZero()
// Wie in Java: int / int schneidet Richtung null ab (7 / 2 = 3, -7 / 2 = -3)
const v = tok.t === '/' ? (bothInt ? Math.trunc(value.v / rhs.v) : value.v / rhs.v) : value.v % rhs.v
value = { v, int: bothInt }
}
}
return value
}
private factor(): Num {
const token = this.current
if (!token) throw invalid('')
this.index += 1
switch (token.t) {
case 'number':
return { v: token.value, int: !token.literal.includes('.') }
case 'identifier': {
const name = token.name
if (name === 'Math' && this.kind() === '.') {
this.index += 1
if (!this.isIdent('random')) throw invalid(name)
this.index += 1
if (this.kind() !== '(') throw invalid('Math.random')
this.index += 1
if (this.kind() !== ')') throw invalid('Math.random')
this.index += 1
return { v: Math.random(), int: false }
}
const value = this.variables.get(name)
if (!value) throw unknownVar(name)
if (this.kind() === '.') {
this.index += 1
if (!this.isIdent('length')) throw invalid(name)
this.index += 1
if (this.kind() === '(') {
this.index += 1
if (this.kind() !== ')') throw invalid(`${name}.length`)
this.index += 1
}
if (isArrayValue(value)) return { v: ((value as { value: unknown[] }).value).length, int: true }
throw invalid(name)
}
if (this.kind() === '[') {
this.index += 1
const elementIndex = Math.trunc(this.expression().v)
if (this.kind() !== ']') throw invalid(name)
this.index += 1
if (value.kind === 'grid') {
if (!(elementIndex >= 0 && elementIndex < value.value.length)) throw invalid(`${name}[${elementIndex}]`)
const row = value.value[elementIndex]
if (this.kind() === '.') {
// `sitze[0].length`: Anzahl der Spalten in dieser Zeile
this.index += 1
if (!this.isIdent('length')) throw invalid(name)
this.index += 1
if (this.kind() === '(') {
this.index += 1
if (this.kind() !== ')') throw invalid(`${name}.length`)
this.index += 1
}
return { v: row.length, int: true }
}
if (this.kind() !== '[') throw invalid(name)
this.index += 1
const column = Math.trunc(this.expression().v)
if (this.kind() !== ']') throw invalid(name)
this.index += 1
if (!(column >= 0 && column < row.length)) throw invalid(`${name}[${elementIndex}][${column}]`)
if (value.elementType !== 'int' && value.elementType !== 'double') throw invalid(name)
return { v: row[column] as number, int: value.elementType === 'int' }
}
if (value.kind === 'intArray' || value.kind === 'doubleArray') {
if (!(elementIndex >= 0 && elementIndex < value.value.length)) throw invalid(`${name}[${elementIndex}]`)
return { v: value.value[elementIndex], int: value.kind === 'intArray' }
}
if (value.kind === 'stringArray') {
const code = charCode(value.value[elementIndex])
if (code !== undefined) return { v: code, int: true }
}
throw invalid(name)
}
if (value.kind === 'string') {
const code = charCode(value.value)
if (code !== undefined) return { v: code, int: true }
}
const numeric = asDouble(value)
if (!Number.isFinite(numeric)) throw invalid(name)
return { v: numeric, int: value.kind === 'int' }
}
case '-': {
const inner = this.factor()
return { v: -inner.v, int: inner.int }
}
case '(': {
const value = this.expression()
if (this.kind() !== ')') throw invalid('')
this.index += 1
return value
}
default:
throw invalid('')
}
}
}
// MARK: - Schritte
/** Vergleich oder Verknüpfung außerhalb von Texten (`a < b`, `!fertig`, `x == 3 && y`): ergibt true oder false. */
function looksBoolean(expression: string): boolean {
const code = expression.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/gu, '""')
return /==|!=|<|>|&&|\|\||^\s*!/u.test(code)
}
function stripTrailingSemicolon(text: string): string {
let result = text.trim()
while (result.endsWith(';')) result = result.slice(0, -1).trim()
return result
}
function paddedForParts(parts: string[]): string[] {
const result = parts.slice(0, 3)
while (result.length < 3) result.push('')
return result
}
function normalizedForParts(rawParts: string[]): string[] {
const stripped = rawParts.map((p) => stripTrailingSemicolon(p).trim())
if (stripped.length === 1 && stripped[0].includes(';')) {
return paddedForParts(stripped[0].split(';').map((p) => p.trim()))
}
return paddedForParts(stripped)
}
type StepContext = Pick<SimStep, 'frame' | 'callPath'>
/** Aufrufebene eines Schritts, damit Rümpfe und Zweige im selben Unterprogramm bleiben. */
const contextOf = (step: SimStep): StepContext => (step.frame ? { frame: step.frame, callPath: step.callPath } : {})
function buildSteps(elements: VSElement[], pathPrefix: number[] = [], context: StepContext = {}): SimStep[] {
const steps: SimStep[] = []
const push = (step: SimStep) => steps.push(context.frame ? { ...step, ...context } : step)
elements.forEach((element, index) => {
const path = [...pathPrefix, index]
const text = element.textLines.join(' ').trim()
switch (element.type) {
case ElementType.anweisung:
// Leere Anweisung und Platzhalter „ø“ werden übersprungen
if (text !== '' && text !== 'ø') push({ path, text, kind: 'statement' })
break
case ElementType.verzweigung:
push({ path, text: text || 'true', kind: 'branch', cases: element.cases })
break
case ElementType.fallauswahl:
push({ path, text: text || '0', kind: 'switchSelection', cases: element.cases })
break
case ElementType.forSchleife:
push({
path,
text,
kind: 'forLoopStart',
loopBody: element.loopBody,
forParts: normalizedForParts(element.textLines),
})
break
case ElementType.whileSchleife:
push({ path, text: text || 'true', kind: 'whileLoop', loopBody: element.loopBody })
break
case ElementType.doUntilSchleife:
push({ path, text: text || 'true', kind: 'doUntilLoop', loopBody: element.loopBody })
break
case ElementType.endlosschleife:
push({ path, text: text || 'true', kind: 'infiniteLoop', loopBody: element.loopBody })
break
case ElementType.aussprung:
push({ path, text, kind: 'jump' })
break
case ElementType.aufruf:
if (text !== '' && text !== 'ø') push({ path, text, kind: 'call' })
break
}
})
return steps
}
function parseInputValue(rawValue: string, valueType: SimValueType): SimValue {
const trimmed = rawValue.trim().replaceAll(',', '.')
switch (valueType) {
case 'int':
if (!/^[+-]?[0-9]+$/.test(trimmed)) throw new SimulationError({ kind: 'wholeNumberExpected' })
return int(Number(trimmed))
case 'double':
if (!/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][+-]?[0-9]+)?$/.test(trimmed)) {
throw new SimulationError({ kind: 'numberExpected' })
}
return dbl(Number(trimmed))
case 'string':
return { kind: 'string', value: rawValue }
case 'boolean':
switch (trimmed.toLowerCase()) {
case 'true': case 'wahr': return { kind: 'boolean', value: true }
case 'false': case 'falsch': return { kind: 'boolean', value: false }
default: throw new SimulationError({ kind: 'booleanExpected' })
}
}
}
function freshState(): SimState {
return { stepIndex: 0, variables: new Map(), outputLines: [], isHalted: false, files: new Map(), robotActions: [] }
}
type SwitchSelector = { kind: 'int'; value: number } | { kind: 'text'; value: string }
function matchingCaseIndex(selector: SwitchSelector, cases: VSCase[]): number | undefined {
for (let i = 0; i < cases.length; i++) {
const label = cases[i].name.trim()
if (label.toLowerCase() === 'default') continue
if (selector.kind === 'int') {
if (/^[+-]?[0-9]+$/.test(label) && Number(label) === selector.value) return i
} else if (unquotedString(label) === selector.value || label === selector.value) {
return i
}
}
return undefined
}
function isLoopContinuation(kind: StepKind): boolean {
return (
kind === 'forLoopIncrement' ||
kind === 'forLoopCondition' ||
kind === 'whileLoop' ||
kind === 'doUntilCondition' ||
kind === 'infiniteLoop'
)
}
function sameStep(a: SimStep, b: SimStep): boolean {
return (a.frame ?? 0) === (b.frame ?? 0) && a.path.length === b.path.length && a.path.every((v, i) => v === b.path[i])
}
/** Kopfzeile eines Unterprogramms im Titel, z. B. `int quadrat(int x)` oder `void zeigeSumme(int a, int b)`. */
export interface SubprogramHeader {
/** Fehlt bei `void`. */
returnType?: SimValueType
name: string
/** `dims` steht bei Array-Parametern wie `int[] zahlen` (1) oder `boolean[][] sitze` (2). */
params: { type: SimValueType; name: string; dims?: 1 | 2 }[]
}
export function parseSubprogramHeader(text: string): SubprogramHeader | undefined {
const m = /^(void|int|double|String|boolean)\s+([A-Za-z_]\w*)\s*\((.*)\)$/u.exec(stripTrailingSemicolon(text))
if (!m) return undefined
const params: SubprogramHeader['params'] = []
if (m[3].trim() !== '') {
for (const part of m[3].split(',')) {
const p = /^(int|double|String|boolean|char)\s*((?:\[\s*\]){0,2})\s+([A-Za-z_]\w*)$/u.exec(part.trim())
if (!p) return undefined
const dims = (p[2].match(/\[/gu) ?? []).length
params.push({ type: valueTypeKeyword(p[1])!, name: p[3], ...(dims > 0 ? { dims: dims as 1 | 2 } : {}) })
}
}
return { returnType: valueTypeKeyword(m[1]), name: m[2], params }
}
/** Text eines Aufruf-Kastens, z. B. `zeigeTitel()`, `zeigeSumme(3, 4)` oder `int y = quadrat(5)`. */
interface CallText {
target?: string
targetType?: SimValueType
name: string
args: string[]
}
function parseCallText(text: string): CallText | undefined {
const m = /^(?:(?:(int|double|String|boolean)\s+)?([A-Za-z_]\w*)\s*=\s*)?([A-Za-z_]\w*)\s*\((.*)\)$/u.exec(
stripTrailingSemicolon(text),
)
if (!m) return undefined
return {
targetType: m[1] ? valueTypeKeyword(m[1]) : undefined,
target: m[2],
name: m[3],
args: m[4].trim() === '' ? [] : splitTopLevel(m[4], ','),
}
}
/** `zeigeTitel()`, `zeigeTitel;`, `int y = quadrat(5)` und die Kopfzeile `int quadrat(int x)` liefern den Namen. */
export function subprogramName(text: string): string {
const t = stripTrailingSemicolon(text)
return parseSubprogramHeader(t)?.name ?? parseCallText(t)?.name ?? t.replace(/\(\s*\)$/u, '').trim()
}
/** Ein laufendes Unterprogramm mit Kopfzeile: eigene Variablen, die des Aufrufers warten in `saved`. */
interface CallFrame {
saved: Map<string, SimValue>
header: SubprogramHeader
call?: CallText
returnValue?: SimValue
/** Array-Parameter: Änderungen gehen am Ende an diese Variablen des Aufrufers zurück (Referenzübergabe). */
references: { param: string; callerName: string }[]
}
// MARK: - Engine
export class SimulationEngine {
steps: SimStep[]
state: SimState = freshState()
private nextFrame = 1
private callDepth = 0
private frames = new Map<number, CallFrame>()
/** Beim Aufbereiten der Anzeige (`lastTrace`) lesen `nextLine()`/`readLine()` nur nach, ohne weiterzugehen. */
private peeking = false
/** Messwerte des echten mBot2; fehlt ein Wert, gilt der simulierte aus `MBOT_SENSORS`. */
robotSensors: MBotSensorValues = {}
/** Pseudocode: Kästen werden nur der Reihe nach gezeigt, Bedingungen beantwortet man selbst. */
private pseudocode: boolean
/** Pseudocode: Antwort auf die gerade gestellte Frage (Bedingung: true/false, Fallauswahl: Name des Falls). */
private decided?: boolean | string
constructor(
document: VSDocument,
private resolveSubprogram: SubprogramResolver = () => undefined,
) {
this.steps = buildSteps(document.elements)
this.pseudocode = !!document.pseudocode
}
/** Im Unterprogramm bleibt der Aufruf-Kasten im Hauptprogramm markiert. */
get currentStepPath(): number[] | undefined {
const step = this.steps[this.state.stepIndex]
return step?.callPath ?? step?.path
}
get canStep(): boolean {
return !this.state.isHalted && !this.state.inputRequest && this.state.stepIndex < this.steps.length
}
/** Englischer Text von `notice` (Tests). */
get message(): string | undefined {
return this.state.notice && noticeEnglish(this.state.notice)
}
reset(document?: VSDocument): void {
if (document) {
this.steps = buildSteps(document.elements)
this.pseudocode = !!document.pseudocode
}
this.decided = undefined
this.state = freshState()