This repository was archived by the owner on Nov 7, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathcodeGenerator.ts
More file actions
1842 lines (1698 loc) · 76.7 KB
/
Copy pathcodeGenerator.ts
File metadata and controls
1842 lines (1698 loc) · 76.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 `VisuStructCodeGenerator.swift` und `CodeGeneration/*.swift`:
* Quellcode (Java, Python, JavaScript) aus dem Struktogramm.
*/
import { ElementType, type VSDocument, type VSElement } from './model'
import { parseSubprogramHeader, type SubprogramHeader } from './simulation'
export type CodeTarget = 'java' | 'python' | 'javascript'
export interface CodeOptions {
baseIndent: number
indentPerLevel: number
/** Diagramm-Texte zusätzlich als Kommentar (`/* … *\/` bzw. `""" … """`). */
includeDiagramTextAsComments: boolean
/** `else` auch ausgeben, wenn der Nein-Zweig nur leer (ø) ist. */
includeEmptyElseBranch: boolean
/** Kommentar über dem Code, wenn das Diagramm als Pseudocode markiert ist. */
pseudocodeNote: string
/** Interner Heuristik-Kontext für JavaScript und Python (Ganzzahldivision). */
jsIntVariables?: Set<string>
/** Elementtyp deklarierter Arrays (`int[] zahlen` → `int`), für Eingaben in `zahlen[i]`. */
arrayElementTypes?: Map<string, string>
/** Text-Variablen: In Python ohne `str(…)` verketten. */
stringVariables?: Set<string>
/** Python ohne `match` (MicroPython auf dem mBot2 kennt es nicht): Fallauswahl als `if`/`elif`/`else`. */
pythonWithoutMatch?: boolean
/** Nur für die Ansicht „Code live“: graue Platzhalter statt `true`/„empty element“, Zeilen je Element. */
live?: LiveContext
}
export const defaultCodeOptions: CodeOptions = {
baseIndent: 0,
indentPerLevel: 4,
includeDiagramTextAsComments: false,
includeEmptyElseBranch: true,
pseudocodeNote: 'Pseudocode – not a runnable program',
}
/**
* `subprograms`: Unterprogramme mit Kopfzeile aus anderen Reitern. Python und JavaScript stellen ihre
* Definitionen vor das Hauptprogramm; in Java gehören sie als Methoden in die Klasse (`generateJavaClassFile`).
*/
export function generateCode(
document: VSDocument,
target: CodeTarget,
options: Partial<CodeOptions> = {},
subprograms: VSDocument[] = [],
): string {
const opts = documentOptions(document, target, options)
let out = ''
// Schul-tauglich: Strict-Modus immer am Anfang des Snippets.
if (target === 'javascript') out += '"use strict";\n\n'
const all = [document, ...(target === 'java' ? [] : subprograms)]
if (target === 'python' && all.some(documentContainsJavaMathRandom)) out += 'import random\n\n'
if (target !== 'java') out += fileHelperClasses(all, target)
if (target === 'java' && documentContainsJavaInput(document)) {
// Snippet-Modus: Import als Kommentar (damit es auch beim Einfügen in `main` nicht „falsch“ steht).
out += '// import java.util.Scanner;\n'
out += 'Scanner scanner = new Scanner(System.in);\n\n'
}
// Nach Import/Scanner, damit die Java-Klasse den Vorspann weiterhin erkennt.
if (document.pseudocode) out += (target === 'python' ? '# ' : '// ') + opts.pseudocodeNote + '\n\n'
if (target !== 'java') {
for (const sub of subprograms) {
if (sub === document) continue
const header = parseSubprogramHeader(sub.caption)
if (header) out += subprogramDefinition(sub, header, target, options, 0) + '\n'
}
}
const header = parseSubprogramHeader(document.caption)
const sink = { out: '' }
if (header) sink.out = subprogramDefinition(document, header, target, options, opts.baseIndent)
else for (const el of document.elements) emit(el, target, opts, opts.baseIndent, sink)
out += sink.out
if (out.trim() === '') {
const empty = commentPrefix(target, true)
return target === 'javascript' ? '"use strict";\n\n' + empty : empty
}
return postProcessLengthSyntax(out.replace(/^[\n\r]+|[\n\r]+$/g, ''), target)
}
function documentOptions(document: VSDocument, target: CodeTarget, options: Partial<CodeOptions>): CodeOptions {
const opts: CodeOptions = {
...defaultCodeOptions,
...options,
jsIntVariables: new Set(),
arrayElementTypes: inferArrayElementTypes(document),
stringVariables: inferStringVariables(document),
}
if (target !== 'java') opts.jsIntVariables = inferIntegerVariables(document)
return opts
}
const javaTypeName = (type: SubprogramHeader['returnType']) =>
type === 'string' ? 'String' : type === undefined ? 'void' : type
function javaMethodHeader(header: SubprogramHeader): string {
const params = header.params.map((p) => `${javaTypeName(p.type)}${'[]'.repeat(p.dims ?? 0)} ${p.name}`).join(', ')
return `public static ${javaTypeName(header.returnType)} ${header.name}(${params}) {`
}
/** Kopfzeile wie `int quadrat(int x)` als Java-Methode, Python-`def` oder JavaScript-`function`. */
function subprogramDefinition(
document: VSDocument,
header: SubprogramHeader,
target: CodeTarget,
options: Partial<CodeOptions>,
indent: number,
): string {
const opts = documentOptions(document, target, options)
for (const p of header.params) {
if (p.dims) continue
if (p.type === 'int') opts.jsIntVariables!.add(p.name)
if (p.type === 'string') opts.stringVariables!.add(p.name)
}
const names = header.params.map((p) => p.name).join(', ')
const sink = { out: '' }
for (const el of document.elements) emit(el, target, opts, indent + opts.indentPerLevel, sink)
if (sink.out.trim() === '') sink.out = sp(indent + opts.indentPerLevel) + (target === 'python' ? 'pass\n' : '\n')
switch (target) {
case 'java':
return `${sp(indent)}${javaMethodHeader(header)}\n${sink.out}${sp(indent)}}\n`
case 'python':
return `${sp(indent)}def ${header.name}(${names}):\n${sink.out}`
case 'javascript':
return `${sp(indent)}function ${header.name}(${names}) {\n${sink.out}${sp(indent)}}\n`
}
}
// MARK: - Hilfen
type Sink = { out: string }
const sp = (n: number) => (n > 0 ? ' '.repeat(n) : '')
/** Wie Swift `regexGroups`: alle Gruppen, fehlende als "". */
function groups(re: RegExp, s: string): string[] | undefined {
const m = re.exec(s)
return m ? Array.from(m, (g) => g ?? '') : undefined
}
function commentPrefix(target: CodeTarget, forEmpty: boolean): string {
if (!forEmpty) return ''
return target === 'python' ? '# empty element' : '// empty element'
}
const isDiagramEmptyPlaceholderText = (s: string) => s.trim() === 'ø'
function emptyElementCommentLine(indent: number, target: CodeTarget): string {
return sp(indent) + (target === 'python' ? '# empty element\n' : '// empty element\n')
}
function isElementVisuallyEmptyPlaceholderOnly(el: VSElement): boolean {
switch (el.type) {
case ElementType.leerElement:
return true
case ElementType.anweisung:
case ElementType.aufruf:
return el.textLines.map((l) => l.trim()).every((l) => l === '' || isDiagramEmptyPlaceholderText(l))
default:
return false
}
}
function isIfElseFalseBranchVisuallyEmpty(elements: VSElement[]): boolean {
return elements.every(isElementVisuallyEmptyPlaceholderOnly)
}
function blockComment(lines: string[], target: CodeTarget, indent: number): string {
const trimmed = lines.map((l) => l.replace(/^[ \t]+|[ \t]+$/g, '')).filter((l) => l !== '')
if (trimmed.length === 0) return ''
if (target === 'python') {
return sp(indent) + '"""\n' + trimmed.map((t) => sp(indent) + t + '\n').join('') + sp(indent) + '"""\n'
}
if (trimmed.length === 1) return sp(indent) + '/* ' + trimmed[0] + ' */\n'
return sp(indent) + '/*\n' + trimmed.map((t) => sp(indent) + ' * ' + t + '\n').join('') + sp(indent) + ' */\n'
}
const isCStyleSemicolonTarget = (t: CodeTarget) => t === 'java' || t === 'javascript'
/** Semikolon-Heuristik für Java/JavaScript: ergänzt `;`, wenn sinnvoll und noch nicht vorhanden. */
export function formatCStyleStatementLine(rawLine: string): string {
const line = rawLine.trim()
if (line === '') return ''
if (line.startsWith('//') || line.startsWith('/*') || line.startsWith('*') || line.startsWith('#')) return line
if (line.startsWith('{') || line.startsWith('}')) return line
if (line.endsWith('{')) return line
if (line.endsWith(';')) return line
const lower = line.toLowerCase()
for (const kw of ['if ', 'else', 'for ', 'while ', 'do ', 'switch ', 'case ', 'default']) {
if (lower.startsWith(kw)) return line
}
return line + ';'
}
/** Bedingung/Ausdruck für Klammern: mehrzeilig mit Leerzeichen zusammenfassen. */
function conditionText(lines: string[]): string {
const parts = lines.map((l) => l.trim()).filter((l) => l !== '')
return stripStructureKeywordPrefix(parts.length === 0 ? 'true' : parts.join(' '))
}
function stripStructureKeywordPrefix(text: string): string {
const trimmed = text.trim()
for (const keyword of ['if', 'while', 'until', 'switch']) {
const stripped = stripKeywordPrefix(keyword, trimmed)
if (stripped !== undefined) return stripped === '' ? 'true' : stripped
}
return trimmed
}
function stripKeywordPrefix(keyword: string, text: string): string | undefined {
if (!text.toLowerCase().startsWith(keyword)) return undefined
const after = text.slice(keyword.length)
if (!(after === '' || /^\s/.test(after) || after[0] === '(')) return undefined
let content = after.trim()
if (content.startsWith('(') && content.endsWith(')') && content.length >= 2) content = content.slice(1, -1).trim()
return content
}
function stripTrailingSemicolon(s: string): string {
let x = s.trim()
while (x.endsWith(';')) x = x.slice(0, -1).trim()
return x
}
// MARK: - Ein-/Ausgabe
/** Diagramm-Präfixe für Ausgabe: `output:` bzw. älteres `print:`. */
function expressionAfterOutputDiagramPrefix(raw: string): string | undefined {
const t = raw.trim()
const lower = t.toLowerCase()
let expr: string
if (lower.startsWith('output:')) expr = t.slice(7).trim()
else if (lower.startsWith('print:')) expr = t.slice(6).trim()
else return undefined
return expr === '' ? undefined : expr
}
interface InputLineParse {
type: string
name: string
/** Optionaler Eingabe-Hinweis in `"…"`. */
customPrompt?: string
}
const isIndexedTarget = (p: InputLineParse) => p.name.includes('[') && p.name.includes(']')
/** `input:`-Rest: `int pin`, `int pin "Hinweis"`, Kurzform `pin "Hinweis"` (implizit `int`), bisher `zahl` / `int zahl`. */
function parseInputLineAfterColon(rest: string): InputLineParse | undefined {
const trimmed = rest.trim()
if (trimmed === '') return undefined
const typed = groups(
/^\s*(integer|int|long|float|double|string|boolean|char|bool)\s+([a-zA-Z_]\w*(?:\s*\[[^\]]+\])?)(?:\s+"([^"]*)")?\s*$/i,
trimmed,
)
if (typed) {
const name = typed[2].replaceAll(' ', '')
if (name === '') return undefined
const c = (typed[3] ?? '').trim()
return { type: normalizeInputTypeKeyword(typed[1]), name, customPrompt: c === '' ? undefined : c }
}
const quoted = groups(/^\s*([a-zA-Z_]\w*(?:\s*\[[^\]]+\])?)\s+"([^"]*)"\s*$/i, trimmed)
if (quoted) {
const target = quoted[1].replaceAll(' ', '')
const notName = ['int', 'integer', 'long', 'float', 'double', 'string', 'boolean', 'char', 'bool', 'void']
if (notName.includes(target.toLowerCase())) return undefined
return { type: target.includes('[') ? 'String' : 'int', name: target, customPrompt: quoted[2].trim() }
}
const pair = parseInputTypeAndName(trimmed)
if (pair) return { type: normalizeInputTypeKeyword(pair[0]), name: pair[1] }
return undefined
}
function normalizeInputTypeKeyword(raw: string): string {
switch (raw.trim().toLowerCase()) {
case 'integer':
case 'int':
return 'int'
case 'long': return 'long'
case 'float': return 'float'
case 'double': return 'double'
case 'string': return 'String'
case 'boolean':
case 'bool':
return 'boolean'
case 'char': return 'char'
default: return raw
}
}
/** Nach `input:`: `int zahl` wie bisher, oder Kurzform `zahl` → Typ `int`. */
function parseInputTypeAndName(rest: string): [string, string] | undefined {
const parts = rest.split(/[ \t]+/).filter(Boolean)
if (parts.length === 0) return undefined
if (parts.length >= 2) return [parts[0], parts[1]]
const incomplete = ['int', 'double', 'string', 'boolean', 'char', 'long', 'float', 'short', 'byte', 'void', 'bool', 'integer']
if (incomplete.includes(parts[0].toLowerCase())) return undefined
return ['int', parts[0]]
}
/** Ohne `output:`/`print:`-Präfix: Zeile beginnt mit `"…"` → Ausgabe. */
function emitBareLeadingStringAsPrintIfNeeded(
raw: string,
target: CodeTarget,
indent: number,
intVariables: Set<string>,
stringVariables: Set<string>,
): string | undefined {
const t = stripTrailingSemicolon(raw).trim()
if (!t.startsWith('"')) return undefined
switch (target) {
case 'java': return sp(indent) + 'System.out.println(' + t + ');\n'
case 'javascript': return sp(indent) + 'console.log(' + t + ');\n'
case 'python': return sp(indent) + 'print(' + pythonConcatenation(t, intVariables, stringVariables) + ')\n'
}
}
/** Zeichenkette für `"…"`-Literale (Java, JavaScript und Python escapen gleich). */
function escapeForDoubleQuotedLiteral(s: string): string {
return s.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('\n', '\\n').replaceAll('\r', '\\r')
}
function inputParseFrom(raw: string, arrayTypes: Map<string, string>): InputLineParse | undefined {
const t = raw.trim()
if (!t.toLowerCase().startsWith('input:')) return undefined
const rest = t.slice(6).trim()
if (rest === '') return undefined
const p = parseInputLineAfterColon(rest)
// Kurzform `input: zahlen[i]`: Typ aus der Array-Deklaration statt immer `String`.
if (p && isIndexedTarget(p) && !/^\s*(integer|int|long|float|double|string|boolean|char|bool)\s/i.test(rest)) {
const declared = arrayTypes.get(p.name.slice(0, p.name.indexOf('[')).trim())
if (declared) return { ...p, type: declared }
}
return p
}
function inferStringVariables(doc: VSDocument): Set<string> {
const out = new Set<string>()
walkElements(doc.elements, (e) => {
for (const raw of e.textLines) {
const t = raw.trim()
if (t.toLowerCase().startsWith('input:')) {
const p = parseInputLineAfterColon(t.slice(6).trim())
if (p?.type === 'String' && !isIndexedTarget(p)) out.add(p.name)
continue
}
const g = groups(/^\s*(?:const\s+)?string\s+([a-zA-Z_]\w*)\s*=/i, t)
if (g) out.add(g[1])
// String-Arrays als `name[]`, damit `spalten[i] + 1` in Python Text bleibt.
const a = groups(/^\s*string\s*\[\s*\]\s*([a-zA-Z_]\w*)\s*=/i, t)
if (a) out.add(a[1] + '[]')
}
})
return out
}
function inferArrayElementTypes(doc: VSDocument): Map<string, string> {
const out = new Map<string, string>()
walkElements(doc.elements, (e) => {
for (const raw of e.textLines) {
const g =
groups(/^\s*(integer|int|long|float|double|string|boolean|char|bool)\s*\[\s*\]\s*([a-zA-Z_]\w*)/i, raw) ??
groups(/^\s*(integer|int|long|float|double|string|boolean|char|bool)\s+([a-zA-Z_]\w*)\s*\[\s*\]/i, raw)
if (g) out.set(g[2], normalizeInputTypeKeyword(g[1]))
}
})
return out
}
function emitJavaInputLineIfNeeded(raw: string, indent: number, arrayTypes: Map<string, string>): string | undefined {
const p = inputParseFrom(raw, arrayTypes)
if (!p) return undefined
const promptText = p.customPrompt ? p.customPrompt : p.name + ': '
const promptOut = sp(indent) + 'System.out.println("' + escapeForDoubleQuotedLiteral(promptText) + '");\n'
const decl = (type: string) => (isIndexedTarget(p) ? p.name : `${type} ${p.name}`)
switch (p.type) {
case 'int': return promptOut + sp(indent) + `${decl('int')} = scanner.nextInt();\n`
case 'double': return promptOut + sp(indent) + `${decl('double')} = scanner.nextDouble();\n`
// `next()` statt `nextLine()` (vermeidet die Newline-Falle nach `nextInt()`).
case 'String': return promptOut + sp(indent) + `${decl('String')} = scanner.next();\n`
case 'boolean': return promptOut + sp(indent) + `${decl('boolean')} = scanner.nextBoolean();\n`
default: return undefined
}
}
function emitJavaScriptInputLineIfNeeded(raw: string, indent: number, arrayTypes: Map<string, string>): string | undefined {
const p = inputParseFrom(raw, arrayTypes)
if (!p) return undefined
const useCustom = !!p.customPrompt
// `prompt` trägt den eigenen Hinweis; sonst zusätzlich `console.log`.
const hint = useCustom ? '' : sp(indent) + 'console.log("' + escapeForDoubleQuotedLiteral(p.name + ': ') + '");\n'
const promptExpr = (fallback: string) => {
const label = useCustom ? p.customPrompt! : p.name + ': '
return `(prompt("${escapeForDoubleQuotedLiteral(label)}") ?? "${fallback}")`
}
const target = isIndexedTarget(p) ? p.name : `let ${p.name}`
switch (p.type) {
case 'int': return hint + sp(indent) + `${target} = parseInt(${promptExpr('0')}, 10);\n`
case 'double': return hint + sp(indent) + `${target} = Number(${promptExpr('0')});\n`
case 'String': return hint + sp(indent) + `${target} = ${promptExpr('')};\n`
case 'boolean': return hint + sp(indent) + `${target} = ${promptExpr('')}.trim().toLowerCase() === "true";\n`
default: return undefined
}
}
function emitPythonInputLineIfNeeded(raw: string, indent: number, arrayTypes: Map<string, string>): string | undefined {
const p = inputParseFrom(raw, arrayTypes)
if (!p) return undefined
const useCustom = !!p.customPrompt
const hint = useCustom ? '' : sp(indent) + 'print("' + escapeForDoubleQuotedLiteral(p.name + ': ') + '")\n'
const input = `input("${escapeForDoubleQuotedLiteral(useCustom ? p.customPrompt! : p.name + ': ')}")`
switch (p.type) {
case 'int': return hint + sp(indent) + `${p.name} = int(${input})\n`
case 'double': return hint + sp(indent) + `${p.name} = float(${input})\n`
case 'String': return hint + sp(indent) + `${p.name} = ${input}\n`
case 'boolean': return hint + sp(indent) + `${p.name} = ${input}.strip().lower() in ("true", "wahr")\n`
default: return undefined
}
}
// MARK: - Dateien
const fileName = String.raw`("(?:[^"\\]|\\.)*"|[A-Za-z_]\w*)`
const fileReaders: [RegExp, string][] = [
[new RegExp(String.raw`^new\s+Scanner\s*\(\s*new\s+File\s*\(\s*${fileName}\s*\)\s*\)$`), 'Scanner'],
[new RegExp(String.raw`^new\s+BufferedReader\s*\(\s*new\s+FileReader\s*\(\s*${fileName}\s*\)\s*\)$`), 'BufferedReader'],
[new RegExp(String.raw`^new\s+PrintWriter\s*\(\s*(?:new\s+(?:File|FileWriter)\s*\(\s*)?${fileName}\s*\)?\s*\)$`), 'PrintWriter'],
]
/** `new Scanner(new File("a.txt"))` → `Scanner`, `"a.txt"`; ebenso `BufferedReader` und `PrintWriter`. */
export function fileConstructor(rhs: string): { kind: 'Scanner' | 'BufferedReader' | 'PrintWriter'; name: string } | undefined {
const t = rhs.trim()
for (const [re, kind] of fileReaders) {
const m = re.exec(t)
if (m) return { kind: kind as 'Scanner', name: m[1] }
}
return undefined
}
/**
* Python und JavaScript kennen `Scanner`, `BufferedReader` und `PrintWriter` nicht; der erzeugte Code bekommt kleine
* Klassen mit denselben Methodennamen (siehe `fileHelperClasses`). Hier: Anlegen, `println`/`print` und `Files.writeString`.
*/
function emitFileLineIfNeeded(
raw: string,
target: CodeTarget,
indent: number,
intVariables: Set<string>,
stringVariables: Set<string>,
): string | undefined {
if (target === 'java') return undefined
const t = stripTrailingSemicolon(raw).trim()
const decl = /^(?:(?:Scanner|BufferedReader|PrintWriter)\s+)?([A-Za-z_]\w*)\s*=\s*(new\s[\s\S]+)$/.exec(t)
const made = decl && fileConstructor(decl[2])
if (decl && made) {
const declared = /^(?:Scanner|BufferedReader|PrintWriter)\s/.test(t)
return target === 'python'
? sp(indent) + `${decl[1]} = ${made.kind}(${made.name})\n`
: sp(indent) + `${declared ? 'let ' : ''}${decl[1]} = new ${made.kind}(${made.name});\n`
}
const write = /^([A-Za-z_]\w*)\.(println|print)\s*\(([\s\S]*)\)$/.exec(t)
if (write && write[1] !== 'System') {
const expr = write[3].trim()
const value = target === 'python' && expr !== '' ? pythonConcatenation(expr, intVariables, stringVariables) : expr
return sp(indent) + `${write[1]}.${write[2]}(${value})${target === 'javascript' ? ';' : ''}\n`
}
const files = /^Files\.writeString\s*\(\s*(?:Path\.of|Paths\.get)\s*\(\s*("(?:[^"\\]|\\.)*")\s*\)\s*,\s*([\s\S]+)\)$/.exec(t)
if (files) {
const text = files[2].trim()
return target === 'python'
? sp(indent) + `open(${files[1]}, "w", encoding="utf-8").write(${pythonConcatenation(text, intVariables, stringVariables)})\n`
: sp(indent) + `require("fs").writeFileSync(${files[1]}, ${text});\n`
}
return undefined
}
/** Welche Datei-Klassen ein Diagramm anlegt. */
function usedFileClasses(docs: VSDocument[]): Set<'Scanner' | 'BufferedReader' | 'PrintWriter'> {
const used = new Set<'Scanner' | 'BufferedReader' | 'PrintWriter'>()
for (const doc of docs) {
walkElements(doc.elements, (e) => {
for (const l of e.textLines) {
const m = /=\s*(new\s.+?);?\s*$/.exec(l)
const made = m && fileConstructor(m[1])
if (made) used.add(made.kind)
}
})
}
return used
}
const pythonFileHelpers: Record<string, string> = {
Scanner: `class Scanner:
def __init__(self, name):
self.lines = open(name, encoding="utf-8").read().splitlines()
def hasNextLine(self):
return len(self.lines) > 0
def nextLine(self):
return self.lines.pop(0)
def close(self):
pass
`,
BufferedReader: `class BufferedReader:
def __init__(self, name):
self.lines = open(name, encoding="utf-8").read().splitlines()
def readLine(self):
return self.lines.pop(0) if self.lines else None
def close(self):
pass
`,
PrintWriter: `class PrintWriter:
def __init__(self, name):
self.file = open(name, "w", encoding="utf-8")
def println(self, text=""):
self.file.write(str(text) + "\\n")
def print(self, text):
self.file.write(str(text))
def close(self):
self.file.close()
`,
}
const javaScriptFileHelpers: Record<string, string> = {
Scanner: `class Scanner {
constructor(name) { this.lines = require("fs").readFileSync(name, "utf8").split(/\\r?\\n/); if (this.lines.at(-1) === "") this.lines.pop(); }
hasNextLine() { return this.lines.length > 0; }
nextLine() { return this.lines.shift(); }
close() {}
}
`,
BufferedReader: `class BufferedReader {
constructor(name) { this.lines = require("fs").readFileSync(name, "utf8").split(/\\r?\\n/); if (this.lines.at(-1) === "") this.lines.pop(); }
readLine() { return this.lines.length > 0 ? this.lines.shift() : null; }
close() {}
}
`,
PrintWriter: `class PrintWriter {
constructor(name) { this.name = name; this.text = ""; }
println(text = "") { this.text += text + "\\n"; }
print(text) { this.text += text; }
close() { require("fs").writeFileSync(this.name, this.text); }
}
`,
}
/** Kleine Klassen für Python und JavaScript, die wie Javas `Scanner`, `BufferedReader` und `PrintWriter` heißen. */
function fileHelperClasses(docs: VSDocument[], target: 'python' | 'javascript'): string {
const used = usedFileClasses(docs)
if (used.size === 0) return ''
const helpers = target === 'python' ? pythonFileHelpers : javaScriptFileHelpers
return [...used].map((k) => helpers[k]).join('\n') + '\n'
}
function emitPrintLineIfNeeded(
raw: string,
target: CodeTarget,
indent: number,
intVariables: Set<string>,
stringVariables: Set<string>,
): string | undefined {
// `System.out.print(…)`: Ausgabe ohne neue Zeile.
const print = /^System\s*\.\s*out\s*\.\s*print\s*\(([\s\S]*)\)$/.exec(stripTrailingSemicolon(raw).trim())
if (print) {
const value = print[1].trim()
switch (target) {
case 'java': return sp(indent) + 'System.out.print(' + value + ');\n'
case 'javascript': return sp(indent) + 'process.stdout.write(String(' + value + '));\n'
case 'python': return sp(indent) + 'print(' + (value === '' ? '' : pythonConcatenation(value, intVariables, stringVariables) + ', ') + 'end="")\n'
}
}
const expr = expressionAfterOutputDiagramPrefix(raw)
if (expr === undefined) {
// Leere Ausgabe (`output:` ohne Text): eine Leerzeile.
if (!/^\s*(?:output|print):\s*$/i.test(raw)) return undefined
return sp(indent) + { java: 'System.out.println();', javascript: 'console.log();', python: 'print()' }[target] + '\n'
}
switch (target) {
case 'java': return sp(indent) + 'System.out.println(' + expr + ');\n'
case 'javascript': return sp(indent) + 'console.log(' + expr + ');\n'
case 'python': return sp(indent) + 'print(' + pythonConcatenation(expr, intVariables, stringVariables) + ')\n'
}
}
// MARK: - Java-ähnliche Zeilen
/** Kopf einer C-`for`-Schleife: mehrere Felder mit `; `. Eine Zeile bleibt unverändert. */
function cStyleForLoopHeaderText(lines: string[]): string {
const parts = lines.map(stripTrailingSemicolon).filter((p) => p !== '')
if (parts.length === 0) return ';;'
return parts.join('; ')
}
function javaScriptForLoopHeaderText(lines: string[]): string {
const header = cStyleForLoopHeaderText(lines)
const parts = header.split(';')
const translated = javaScriptForInitializerFromJavaTypedDeclaration(parts[0])
if (translated !== undefined) parts[0] = translated
return parts.join(';')
}
function javaScriptForInitializerFromJavaTypedDeclaration(raw: string): string | undefined {
const g = groups(/^(\s*)(?:integer|int|long|float|double|string|boolean|char|bool)\s+(\w+)(?:\s*=\s*(.*))?\s*$/i, raw)
if (!g) return undefined
const name = g[2].trim()
if (name === '') return undefined
const rhs = (g[3] ?? '').trim()
if (raw.includes('=') && rhs !== '') return g[1] + `let ${name} = ${rhs}`
return g[1] + `let ${name}`
}
/** Felder einer `for`-Schleife: drei Zeilen oder eine Zeile `int i = 0; i < n; i++` (auch mit `for (…)`). */
function forLoopFields(lines: string[]): [string, string, string] | undefined {
const raw = lines.map((l) => stripTrailingSemicolon(l).trim()).filter((l) => l !== '')
let parts = raw
if (raw.length === 1) {
let one = raw[0]
const kw = stripKeywordPrefix('for', one)
if (kw !== undefined) one = kw
parts = one.split(';').map((p) => p.trim())
}
if (parts.length !== 3 || parts.some((p) => p === '')) return undefined
return [parts[0], parts[1], parts[2]]
}
interface PythonForLoop {
/** `for i in range(…):` – oder `undefined`, wenn nur eine `while`-Schleife passt. */
rangeLine?: string
variable: string
init: string
condition: string
increment: string
}
/** Schrittweite aus `i++`, `i--`, `i += 2`, `i -= 2`, `i = i + 2`, `i = i - 2`. */
function forLoopStepSize(s: string, name: string): number | undefined {
let g = groups(/^\s*(\w+)\s*(\+\+|--)\s*$/, s) ?? groups(/^\s*(\+\+|--)\s*(\w+)\s*$/, s)
if (g) {
const [v, op] = g[1] === '++' || g[1] === '--' ? [g[2], g[1]] : [g[1], g[2]]
return v === name ? (op === '++' ? 1 : -1) : undefined
}
g = groups(/^\s*(\w+)\s*(\+|-)=\s*(\d+)\s*$/, s)
if (g) return g[1] === name ? (g[2] === '+' ? 1 : -1) * Number(g[3]) : undefined
g = groups(/^\s*(\w+)\s*=\s*(\w+)\s*(\+|-)\s*(\d+)\s*$/, s)
if (g) return g[1] === name && g[2] === name ? (g[3] === '+' ? 1 : -1) * Number(g[4]) : undefined
return undefined
}
/** `n` → `n + 1`, `10` → `11`. */
function shiftedBound(bound: string, by: number): string {
if (/^-?\d+$/.test(bound)) return String(Number(bound) + by)
const simple = /^[\w.()[\]]+$/.test(bound) ? bound : `(${bound})`
return by > 0 ? `${simple} + ${by}` : `${simple} - ${-by}`
}
/** Zählschleife für Python: `range(…)`, wenn Kopf und Schritt passen; sonst Bausteine für `while`. */
function pythonForLoop(lines: string[], intVariables: Set<string>): PythonForLoop | undefined {
const fields = forLoopFields(lines)
if (!fields) return undefined
const [initS, condS, stepS] = fields
const init = groups(/^\s*(?:integer|int|long|short|byte|double|float)?\s*([a-zA-Z_]\w*)\s*=\s*(.+)$/i, initS)
if (!init) return undefined
const name = init[1]
const loop: PythonForLoop = { variable: name, init: `${name} = ${pythonExpression(init[2], intVariables)}`, condition: condS, increment: stepS }
const cond = groups(/^\s*(\w+)\s*(<=|<|>=|>)\s*(.+)$/, condS)
const step = forLoopStepSize(stepS, name)
if (!cond || cond[1] !== name || step === undefined || step === 0) return loop
const start = pythonExpression(init[2], intVariables)
let stop = pythonExpression(cond[3], intVariables)
const op = cond[2]
if (step > 0 && op === '<=') stop = shiftedBound(stop, 1)
else if (step < 0 && op === '>=') stop = shiftedBound(stop, -1)
else if (!(step > 0 && op === '<') && !(step < 0 && op === '>')) return loop
const args = step === 1 ? (start === '0' ? [stop] : [start, stop]) : [start, stop, String(step)]
loop.rangeLine = `for ${name} in range(${args.join(', ')}):`
return loop
}
interface ConstTypedLineParse {
rawType: string
name: string
rhs?: string
}
/** `const int PIN` bzw. `const double PI = 3.14`. */
function parseConstTypedLine(rawLine: string): ConstTypedLineParse | undefined {
const line = stripTrailingSemicolon(rawLine).trim()
if (line === '') return undefined
const g = groups(/^\s*const\s+(integer|int|long|float|double|string|boolean|char|bool)\s+(\w+)(?:\s*=\s*(.*))?$/i, line)
if (!g) return undefined
const name = g[2].trim()
if (name === '') return undefined
if (!line.includes('=')) return { rawType: g[1].trim(), name }
const rhs = (g[3] ?? '').trim()
if (rhs === '') return undefined
return { rawType: g[1].trim(), name, rhs }
}
function emitConstTypedLineIfNeeded(
raw: string,
target: CodeTarget,
indent: number,
intVariables: Set<string>,
): string | undefined {
const p = parseConstTypedLine(raw)
if (!p) return undefined
const jt = normalizeInputTypeKeyword(p.rawType)
const r = p.rhs?.trim()
switch (target) {
case 'java':
return sp(indent) + formatCStyleStatementLine(r ? `final ${jt} ${p.name} = ${r}` : `final ${jt} ${p.name}`) + '\n'
case 'javascript':
if (r) return sp(indent) + formatCStyleStatementLine(`const ${p.name} = ${r}`) + '\n'
// `const` verlangt in JS einen Initialwert.
return sp(indent) + `let ${p.name}; // from diagram: const ${jt} ${p.name}\n`
case 'python':
if (r) return sp(indent) + `${p.name} = ${pythonRhsFromJavaRhs(r, intVariables)} # const ${jt}\n`
return sp(indent) + `${p.name} = None # const ${jt}, uninitialized\n`
}
}
/** Eine Zeile `Typ name = ausdruck` (Schulsyntax). */
function parseJavaStyleSimpleAssignment(rawLine: string): { name: string; rhs: string; isArray: boolean } | undefined {
const line = stripTrailingSemicolon(rawLine).trim()
if (line === '') return undefined
if (parseGridDeclaration(line)) return undefined
// `integer` vor `int`, damit nicht nur der Präfix `int` von `integer` passt.
const g = groups(
/^\s*(?:integer|int|long|float|double|string|boolean|char|bool)(?:\s*\[\s*\]\s+(\w+)|\s+(\w+)(\s*\[\s*\])?)\s*=\s*(.*)$/i,
line,
)
if (!g) return undefined
const name = g[1] === '' ? g[2] : g[1]
const rhs = g[4].trim()
if (rhs === '') return undefined
return { name, rhs, isArray: g[1] !== '' || g[3] !== '' }
}
function javaIntCastExpression(rhs: string): string | undefined {
const g = groups(/^\s*\(\s*int(?:eger)?\s*\)\s*(.+?)\s*$/i, rhs)
const e = g?.[1].trim()
// `(int) wort.charAt(i)` liefert den Zeichencode, das übernimmt `convertCharCasts`.
if (!e || isCharOperand(e)) return undefined
return e.startsWith('(') && matchingClose(e, 0) === e.length - 1 ? e.slice(1, -1).trim() : e
}
/** Index der schließenden Klammer zu `s[open]` (rund oder eckig), sonst -1. */
function matchingClose(s: string, open: number): number {
let depth = 0
for (let i = open; i < s.length; i++) {
if (s[i] === '(' || s[i] === '[') depth++
else if ((s[i] === ')' || s[i] === ']') && --depth === 0) return i
}
return -1
}
/** Ein einzelnes Zeichen: `'A'` oder `wort.charAt(i)`. */
const isCharOperand = (e: string) => /^'.'$/u.test(e) || /\.charAt\(.*\)$/.test(e)
/** Ende des Operanden ab `start`: `(…)`, `'A'`, eine Zahl oder ein Name mit `.methode(…)` und `[…]`; sonst -1. */
function operandEnd(s: string, start: number): number {
if (s[start] === '(') {
const close = matchingClose(s, start)
return close < 0 ? -1 : close + 1
}
if (s[start] === "'") return s[start + 2] === "'" ? start + 3 : -1
const head = /^(?:[A-Za-z_]\w*|\d+)/.exec(s.slice(start))
if (!head) return -1
let i = start + head[0].length
for (;;) {
const member = /^\.[A-Za-z_]\w*/.exec(s.slice(i))
if (member) i += member[0].length
else if (s[i] === '(' || s[i] === '[') {
const close = matchingClose(s, i)
if (close < 0) return -1
i = close + 1
} else return i
}
}
/**
* Umwandlungen zwischen Zeichen und Zeichencode wie in Java: `(int) wort.charAt(i)` → Python `ord(…)`,
* JavaScript `….charCodeAt(0)`; `(char) code` → Python `chr(code)`, JavaScript `String.fromCharCode(code)`.
*/
function convertCharCasts(s: string, target: 'python' | 'javascript'): string {
return mapOutsideStringLiterals(s, (code) => {
const re = /\(\s*(int|char)\s*\)\s*/g
let out = ''
let last = 0
for (let m = re.exec(code); m; m = re.exec(code)) {
const start = m.index + m[0].length
const end = operandEnd(code, start)
if (end < 0) continue
const operand = code.slice(start, end)
if (m[1] === 'int' && !isCharOperand(operand)) continue
const inner = convertCharCasts(operand.startsWith('(') ? operand.slice(1, -1).trim() : operand, target)
const replacement = m[1] === 'int'
? (target === 'python' ? `ord(${inner})` : `${inner}.charCodeAt(0)`)
: (target === 'python' ? `chr(${inner})` : `String.fromCharCode(${inner})`)
out += code.slice(last, m.index) + replacement
last = end
re.lastIndex = end
}
return out + code.slice(last)
})
}
function pythonRhsFromJavaRhs(rhs: string, intVariables: Set<string> = new Set()): string {
const t = rhs.trim()
if (t === 'null') return 'None'
const cast = javaIntCastExpression(t)
if (cast !== undefined) return `int(${pythonRhsFromJavaRhs(cast, intVariables)})`
return pythonExpression(t, intVariables)
}
/** Teile außerhalb von `"…"`-Literalen umwandeln, Literale unverändert lassen. */
function mapOutsideStringLiterals(s: string, f: (code: string) => string): string {
let out = ''
let code = ''
let i = 0
while (i < s.length) {
if (s[i] !== '"') {
code += s[i++]
continue
}
out += f(code)
code = ''
let j = i + 1
while (j < s.length && s[j] !== '"') j += s[j] === '\\' ? 2 : 1
out += s.slice(i, j + 1)
i = j + 1
}
return out + f(code)
}
/**
* Java-Schreibweise in einem Ausdruck nach Python: `&&` → `and`, `||` → `or`, `!` → `not`, `true` → `True`,
* `a.equals(b)` → `a == b`, `Math.random()` → `random.random()`, `/` zwischen ganzen Zahlen → `//`.
*/
function pythonExpression(expression: string, intVariables: Set<string>): string {
const withEquals = expression.replace(/\.equals\(\s*("(?:[^"\\]|\\.)*"|[^()"]*?)\s*\)/g, ' == $1')
const isInt = (operand: string) => /^\d+$/.test(operand) || intVariables.has(operand)
return mapOutsideStringLiterals(withEquals, (code) =>
code
.replace(/\bMath\.random\s*\(\s*\)/gi, 'random.random()')
.replace(/===/g, '==')
.replace(/!==/g, '!=')
.replace(/\s*&&\s*/g, ' and ')
.replace(/\s*\|\|\s*/g, ' or ')
.replace(/!(?!=)\s*/g, 'not ')
.replace(/\btrue\b/g, 'True')
.replace(/\bfalse\b/g, 'False')
.replace(/\bnull\b/g, 'None')
.replace(/(?<![\w.])([a-zA-Z_]\w*|\d+)\s*\/\s*([a-zA-Z_]\w*|\d+)(?![\w.(\[])/g, (m, a: string, b: string) =>
isInt(a) && isInt(b) ? `${a} // ${b}` : m,
),
)
}
/** Teile einer Verkettung mit `+` außerhalb von Klammern und Strings. */
function splitTopLevelPlus(expression: string): string[] {
const parts: string[] = []
let depth = 0
let current = ''
let inString = false
for (let i = 0; i < expression.length; i++) {
const c = expression[i]
if (inString) {
current += c
if (c === '\\' && i + 1 < expression.length) current += expression[++i]
else if (c === '"') inString = false
continue
}
if (c === '"') inString = true
else if (c === '(' || c === '[') depth++
else if (c === ')' || c === ']') depth--
else if (c === '+' && depth === 0) {
parts.push(current.trim())
current = ''
continue
}
current += c
}
parts.push(current.trim())
return parts
}
const isDoubleQuotedLiteral = (s: string) => /^"(?:[^"\\]|\\.)*"$/.test(s)
/** `"Summe: " + summe` → `"Summe: " + str(summe)`: Python verkettet Text nicht mit Zahlen. Sonst nur übersetzt. */
function pythonConcatenation(expression: string, intVariables: Set<string>, stringVariables: Set<string>): string {
const parts = splitTopLevelPlus(expression)
const isText = (p: string) =>
isDoubleQuotedLiteral(p) || stringVariables.has(p) || stringVariables.has(p.replace(/^([A-Za-z_]\w*)\[[^[\]]*\]$/u, '$1[]'))
if (parts.length < 2 || !parts.some(isText) || parts.some((p) => p === '')) {
return pythonExpression(expression, intVariables)
}
return parts.map((p) => (isText(p) ? p : `str(${pythonExpression(p, intVariables)})`)).join(' + ')
}
/** Python: `i++` → `i += 1`, `x /= 2` → `x //= 2` (ganze Zahl), sonst der Ausdruck übersetzt. */
function pythonStatementLine(raw: string, intVariables: Set<string>, stringVariables: Set<string> = new Set()): string {
const t = stripTrailingSemicolon(raw).trim()
const inc = groups(/^(\w+(?:\[[^\]]*\])?)\s*(\+\+|--)$/, t) ?? groups(/^(\+\+|--)\s*(\w+(?:\[[^\]]*\])?)$/, t)
if (inc) {
const [target, op] = inc[1] === '++' || inc[1] === '--' ? [inc[2], inc[1]] : [inc[1], inc[2]]
return `${pythonExpression(target, intVariables)} ${op === '++' ? '+=' : '-='} 1`
}
const div = groups(/^(\w+)\s*\/=\s*(.+)$/, t)
if (div && intVariables.has(div[1])) return `${div[1]} //= ${pythonExpression(div[2], intVariables)}`
const assign = groups(/^([\w[\]. ]+?)\s*(=|\+=|-=|\*=|\/=|%=)\s*(.+)$/, t)
if (assign && !assign[3].startsWith('=')) {
const [, target, op, rhs] = assign
let value: string
if (op === '+=' && stringVariables.has(target.trim())) {
const parts = splitTopLevelPlus(rhs)
value = pythonConcatenation(`"" + ${rhs}`, intVariables, stringVariables).replace(/^"" \+ /, '')
if (parts.length === 1 && !isDoubleQuotedLiteral(rhs.trim()) && !stringVariables.has(rhs.trim())) {
value = `str(${pythonExpression(rhs, intVariables)})`
}
} else if (op === '=' && javaIntCastExpression(rhs) === undefined && rhs.trim() !== 'null') {
value = pythonConcatenation(rhs, intVariables, stringVariables)
} else {
value = op === '=' ? pythonRhsFromJavaRhs(rhs, intVariables) : pythonExpression(rhs, intVariables)
}
return `${target} ${op} ${value}`
}
return pythonExpression(t, intVariables)
}
const normalizeJavaScriptMathRandomCall = (s: string) => s.replace(/\bMath\.random\b(?!\s*\()/gi, 'Math.random()')
function arrayLiteralFromJavaInitializer(rhs: string): string {
const t = rhs.trim()
return t.startsWith('{') && t.endsWith('}') ? '[' + t.slice(1, -1) + ']' : rhs
}
function javaNewArraySizeExpression(rhs: string): string | undefined {
const g = groups(/^\s*new\s+(?:byte|short|int|long|float|double|boolean|char|string)\s*\[\s*(.+)\s*\]\s*$/i, rhs)
const size = g?.[1].trim()
return size ? size : undefined
}
interface GridDeclaration {
elementType: string
name: string
rhs: string
}
/** `boolean[][] sitze = …` (2D-Array). */
function parseGridDeclaration(line: string): GridDeclaration | undefined {
const g = groups(/^\s*(int|double|string|boolean)\s*\[\s*\]\s*\[\s*\]\s*([a-zA-Z_]\w*)\s*=\s*(.+)$/i, stripTrailingSemicolon(line).trim())
return g ? { elementType: g[1].toLowerCase(), name: g[2], rhs: g[3].trim() } : undefined
}
/** `new boolean[3][4]` → `['3', '4']`. */
function gridSizeExpressions(rhs: string): [string, string] | undefined {
const g = groups(/^\s*new\s+(?:int|double|string|boolean)\s*\[\s*(.+?)\s*\]\s*\[\s*(.+?)\s*\]\s*$/i, rhs)
return g ? [g[1], g[2]] : undefined
}
const nestedArrayLiteral = (rhs: string) => rhs.replaceAll('{', '[').replaceAll('}', ']')
function gridDefault(elementType: string, target: 'python' | 'javascript'): string {
if (elementType === 'boolean') return target === 'python' ? 'False' : 'false'
if (elementType === 'string') return '""'
if (elementType === 'double') return '0.0'
return '0'
}
function gridRhs(d: GridDeclaration, target: 'python' | 'javascript', intVariables: Set<string>): string {
const size = gridSizeExpressions(d.rhs)
if (target === 'javascript') {
return size
? `Array.from({ length: ${size[0]} }, () => new Array(${size[1]}).fill(${gridDefault(d.elementType, target)}))`
: nestedArrayLiteral(d.rhs)
}
return size
? `[[${gridDefault(d.elementType, target)}] * ${pythonExpression(size[1], intVariables)} for _ in range(${pythonExpression(size[0], intVariables)})]`
: pythonExpression(nestedArrayLiteral(d.rhs), intVariables)
}
function javaScriptRhsFromJavaRhs(rhs: string, isArray: boolean): string {
const t = rhs.trim()
if (isArray) {
const size = javaNewArraySizeExpression(t)
return size !== undefined ? `new Array(${size})` : arrayLiteralFromJavaInitializer(t)
}
const cast = javaIntCastExpression(t)
if (cast !== undefined) return `Math.floor(${javaScriptRhsFromJavaRhs(cast, false)})`
return normalizeJavaScriptMathRandomCall(t)
}
function pythonRhsFromJavaRhsArray(rhs: string, isArray: boolean, intVariables: Set<string>): string {
const t = rhs.trim()
if (isArray) {
const size = javaNewArraySizeExpression(t)
return size !== undefined ? `[None] * ${size}` : pythonExpression(arrayLiteralFromJavaInitializer(t), intVariables)
}
return pythonRhsFromJavaRhs(t, intVariables)
}