Skip to content
This repository was archived by the owner on Nov 7, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
179 changes: 166 additions & 13 deletions web/src/core/codeGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ export interface CodeOptions {
arrayElementTypes?: Map<string, string>
/** Text-Variablen: In Python ohne `str(…)` verketten. */
stringVariables?: Set<string>
/** Nur für die Ansicht „Code live“: graue Platzhalter statt `true`/„empty element“, Zeilen je Element. */
live?: LiveContext
}

export const defaultCodeOptions: CodeOptions = {
Expand Down Expand Up @@ -89,6 +91,11 @@ function documentOptions(document: VSDocument, target: CodeTarget, options: Part
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,
Expand All @@ -108,10 +115,8 @@ function subprogramDefinition(
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': {
const params = header.params.map((p) => `${javaTypeName(p.type)}${'[]'.repeat(p.dims ?? 0)} ${p.name}`).join(', ')
return `${sp(indent)}public static ${javaTypeName(header.returnType)} ${header.name}(${params}) {\n${sink.out}${sp(indent)}}\n`
}
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':
Expand Down Expand Up @@ -906,15 +911,19 @@ function forcedCaseComment(name: string, target: CodeTarget): string {

function emitInstructionLike(textLines: string[], target: CodeTarget, options: CodeOptions, indent: number, sink: Sink) {
const body = textLines.map((l) => l.trim())
if (body.every((l) => l === '')) return
if (body.every((l) => l === '')) {
// Neue, noch leere Anweisung: in Java eine leere Anweisung.
if (options.live) sink.out += sp(indent) + ';\n'
return
}
if (options.includeDiagramTextAsComments) {
const forDiagram = body.filter((l) => l !== '' && !isDiagramEmptyPlaceholderText(l))
if (forDiagram.length > 0) sink.out += blockComment(forDiagram, target, indent)
}
for (const raw of body) {
if (raw === '') continue
if (isDiagramEmptyPlaceholderText(raw)) {
sink.out += emptyElementCommentLine(indent, target)
sink.out += options.live ? livePlaceholderLine(indent, options.live) : emptyElementCommentLine(indent, target)
continue
}
const ints = options.jsIntVariables ?? new Set<string>()
Expand Down Expand Up @@ -951,8 +960,13 @@ function emitConditionHeader(
options: CodeOptions,
indent: number,
sink: Sink,
livePlaceholder = options.live?.labels.condition,
) {
if (options.includeDiagramTextAsComments) sink.out += blockComment(textLines, target, indent)
if (livePlaceholder !== undefined && isBlank(textLines)) {
sink.out += sp(indent) + prefix + livePlaceholderText(livePlaceholder) + suffix
return
}
const condition = conditionText(textLines)
const ints = options.jsIntVariables ?? new Set<string>()
const text =
Expand All @@ -968,6 +982,7 @@ function emitConditionHeader(
function emitBlockBody(elements: VSElement[], target: CodeTarget, options: CodeOptions, indent: number, sink: Sink) {
const before = sink.out.length
for (const el of elements) emit(el, target, options, indent, sink)
if (options.live && sink.out.length === before) sink.out += livePlaceholderLine(indent, options.live)
if (target !== 'python') return
// Nur Kommentare (z. B. „# empty element“) zählen in Python nicht als Anweisung.
const emitted = sink.out.slice(before).split('\n').map((l) => l.trim())
Expand Down Expand Up @@ -1001,8 +1016,11 @@ function emitIfChain(element: VSElement, target: CodeTarget, options: CodeOption
}
emitConditionHeader(isElseIf ? '} else if (' : 'if (', ') {\n', element.textLines, target, options, indent, sink)
emitBlockBody(cases[0].elements, target, options, inner, sink)
if (next) emitIfChain(next, target, options, indent, sink, true)
else if (omitElse) sink.out += sp(indent) + '}\n'
if (next) {
const start = sink.out.length
emitIfChain(next, target, options, indent, sink, true)
recordLiveSpan(options, next, sink, start)
} else if (omitElse) sink.out += sp(indent) + '}\n'
else {
sink.out += sp(indent) + '} else {\n'
emitBlockBody(cases[1].elements, target, options, inner, sink)
Expand All @@ -1011,6 +1029,12 @@ function emitIfChain(element: VSElement, target: CodeTarget, options: CodeOption
}

function emit(element: VSElement, target: CodeTarget, options: CodeOptions, indent: number, sink: Sink) {
const start = sink.out.length
emitElement(element, target, options, indent, sink)
recordLiveSpan(options, element, sink, start)
}

function emitElement(element: VSElement, target: CodeTarget, options: CodeOptions, indent: number, sink: Sink) {
const step = options.indentPerLevel
const py = target === 'python'
const body = (els: VSElement[], i: number) => emitBlockBody(els, target, options, i, sink)
Expand All @@ -1022,7 +1046,7 @@ function emit(element: VSElement, target: CodeTarget, options: CodeOptions, inde

switch (element.type) {
case ElementType.leerElement:
sink.out += emptyElementCommentLine(indent, target)
sink.out += options.live ? livePlaceholderLine(indent, options.live) : emptyElementCommentLine(indent, target)
return

case ElementType.anweisung:
Expand All @@ -1045,7 +1069,16 @@ function emit(element: VSElement, target: CodeTarget, options: CodeOptions, inde
case ElementType.fallauswahl: {
const cases = element.cases
if (!cases || cases.length === 0) return
header(py ? 'match ' : 'switch (', py ? ':\n' : ') {\n')
emitConditionHeader(
py ? 'match ' : 'switch (',
py ? ':\n' : ') {\n',
element.textLines,
target,
options,
indent,
sink,
options.live?.labels.selector,
)
cases.forEach((c, i) => {
const isLast = i === cases.length - 1
if (target === 'java') {
Expand Down Expand Up @@ -1074,7 +1107,8 @@ function emit(element: VSElement, target: CodeTarget, options: CodeOptions, inde
case ElementType.forSchleife:
if (target === 'java') {
commentIfWanted()
sink.out += sp(indent) + 'for (' + cStyleForLoopHeaderText(element.textLines) + ') {\n'
const head = options.live ? liveForLoopHeaderText(element.textLines, options.live.labels) : cStyleForLoopHeaderText(element.textLines)
sink.out += sp(indent) + 'for (' + head + ') {\n'
} else if (py) {
const ints = options.jsIntVariables ?? new Set<string>()
const loop = pythonForLoop(element.textLines, ints)
Expand All @@ -1094,7 +1128,10 @@ function emit(element: VSElement, target: CodeTarget, options: CodeOptions, inde
}
} else {
commentIfWanted()
sink.out += sp(indent) + 'for (' + javaScriptForLoopHeaderText(element.textLines) + ') {\n'
const head = options.live
? liveJavaScriptForLoopHeaderText(element.textLines, options.live.labels)
: javaScriptForLoopHeaderText(element.textLines)
sink.out += sp(indent) + 'for (' + head + ') {\n'
}
body(element.loopBody ?? [], indent + step)
if (!py) sink.out += sp(indent) + '}\n'
Expand All @@ -1107,7 +1144,10 @@ function emit(element: VSElement, target: CodeTarget, options: CodeOptions, inde
return

case ElementType.doUntilSchleife: {
const cond = conditionText(element.textLines)
const cond =
options.live && isBlank(element.textLines)
? livePlaceholderText(options.live.labels.condition)
: conditionText(element.textLines)
if (py) {
sink.out += sp(indent) + 'while True:\n'
const bodyStart = indent + step
Expand Down Expand Up @@ -1137,6 +1177,119 @@ function emit(element: VSElement, target: CodeTarget, options: CodeOptions, inde
}
}

// MARK: - Ansicht „Code live“

/** Platzhalter stehen zwischen diesen Zeichen; die Ansicht zeigt sie grau und ohne die Zeichen. */
export const livePlaceholderStart = '\uE000'
export const livePlaceholderEnd = '\uE001'

/** Platzhalter-Wörter in der Sprache der Oberfläche, z. B. „Bedingung“. */
export interface LiveLabels {
condition: string
selector: string
code: string
start: string
step: string
}

/** Zeilen eines Elements im erzeugten Code (ab 0, `to` einschließlich). */
export interface LiveSpan {
path: number[]
from: number
to: number
}

export interface LiveCode {
/** Code mit Platzhalter-Markierungen (`livePlaceholderStart` … `livePlaceholderEnd`). */
text: string
spans: LiveSpan[]
}

interface LiveContext {
labels: LiveLabels
paths: Map<VSElement, number[]>
spans: LiveSpan[]
}

const livePlaceholderText = (label: string) => livePlaceholderStart + label + livePlaceholderEnd
const livePlaceholderLine = (indent: number, live: LiveContext) => sp(indent) + livePlaceholderText('// ' + live.labels.code) + '\n'
const isBlank = (lines: string[]) => lines.every((l) => l.trim() === '')

/** `for (Startwert; Bedingung; Schritt)`: leere Felder werden zu Platzhaltern. */
function liveForLoopHeaderText(lines: string[], labels: LiveLabels): string {
if (isBlank(lines) || lines.length === 3) {
const placeholders = [labels.start, labels.condition, labels.step]
return placeholders
.map((label, i) => {
const field = stripTrailingSemicolon(lines[i] ?? '')
return field === '' ? livePlaceholderText(label) : field
})
.join('; ')
}
return cStyleForLoopHeaderText(lines)
}

/** Wie `javaScriptForLoopHeaderText`: `int i = 0` wird zu `let i = 0`, Platzhalter bleiben. */
function liveJavaScriptForLoopHeaderText(lines: string[], labels: LiveLabels): string {
const parts = liveForLoopHeaderText(lines, labels).split(';')
const translated = parts[0].includes(livePlaceholderStart) ? undefined : javaScriptForInitializerFromJavaTypedDeclaration(parts[0])
if (translated !== undefined) parts[0] = translated
return parts.join(';')
}

/** Pfade wie in `editing.ts`: `[i, Zweig, j, …]`, Schleifenrumpf = Zweig 0. */
function elementPaths(elements: VSElement[], prefix: number[] = [], out = new Map<VSElement, number[]>()) {
elements.forEach((e, i) => {
const path = [...prefix, i]
if (!out.has(e)) out.set(e, path)
if (e.loopBody) elementPaths(e.loopBody, [...path, 0], out)
e.cases?.forEach((c, k) => elementPaths(c.elements, [...path, k], out))
})
return out
}

function recordLiveSpan(options: CodeOptions, element: VSElement, sink: Sink, start: number) {
const live = options.live
const path = live?.paths.get(element)
if (!live || !path || sink.out.length === start) return
const lineAt = (offset: number) => sink.out.slice(0, offset).split('\n').length - 1
live.spans.push({ path, from: lineAt(start), to: lineAt(sink.out.length - 1) })
}

/** Zielsprachen der Ansicht „Code live“ (Python folgt). */
export type LiveTarget = 'java' | 'javascript'

/**
* Code für die Ansicht „Code live“: wie das Code-Snippet, aber für Anfänger lesbar, solange noch etwas fehlt
* (leere Anweisung `;`, `if (Bedingung)`, `// Dein Code` in leeren Blöcken), und mit den Zeilen jedes Elements.
*/
export function generateLiveCode(document: VSDocument, target: LiveTarget, labels: LiveLabels): LiveCode {
const live: LiveContext = { labels, paths: elementPaths(document.elements), spans: [] }
const opts = documentOptions(document, target, { includeEmptyElseBranch: true, live })
const header = parseSubprogramHeader(document.caption)
let prelude = ''
if (target === 'java') {
if (documentContainsJavaInput(document)) prelude += '// import java.util.Scanner;\nScanner scanner = new Scanner(System.in);\n\n'
if (header) prelude += javaMethodHeader(header) + '\n'
} else {
prelude += '"use strict";\n\n'
if (header) {
for (const p of header.params) if (!p.dims && p.type === 'int') opts.jsIntVariables!.add(p.name)
prelude += `function ${header.name}(${header.params.map((p) => p.name).join(', ')}) {\n`
}
}
const sink = { out: '' }
emitBlockBody(document.elements, target, opts, header ? opts.indentPerLevel : 0, sink)
if (header) sink.out += '}\n'
const offset = prelude.split('\n').length - 1
return {
text: postProcessLengthSyntax((prelude + sink.out).replace(/\n+$/, ''), target),
spans: live.spans.map((s) => ({ ...s, from: s.from + offset, to: s.to + offset })),
}
}

export const generateLiveJava = (document: VSDocument, labels: LiveLabels) => generateLiveCode(document, 'java', labels)

// MARK: - Nachbearbeitung: `.length` / `.length()` zielsprachentauglich (Heuristik)

function postProcessLengthSyntax(s: string, target: CodeTarget): string {
Expand Down
9 changes: 9 additions & 0 deletions web/src/i18n/ar.strings
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,12 @@
"web_site_home" = "الصفحة الرئيسية";
"web_site_imprint" = "بيانات الناشر";
"web_site_privacy" = "الخصوصية";

/* Code live */
"web_live_title" = "الشيفرة المباشرة";
"web_live_toggle_title" = "عرض شيفرة مباشرة بجانب المخطط";
"web_live_hide" = "إخفاء الشيفرة المباشرة";
"web_live_resize" = "تغيير عرض منطقة الشيفرة (نقر مزدوج: إعادة تعيين)";
"web_live_hint" = "تنمو الشيفرة مع مخططك. الرمادي = عنصر نائب: اكتب في المفتش ليظهر نصك هنا. انقر على سطر لتحديد عنصره.";
"web_live_ph_selector" = "المتغير";
"web_live_ph_code" = "شيفرتك";
9 changes: 9 additions & 0 deletions web/src/i18n/da.strings
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,12 @@
"web_site_home" = "Forside";
"web_site_imprint" = "Kolofon";
"web_site_privacy" = "Privatliv";

/* Code live */
"web_live_title" = "Live-kode";
"web_live_toggle_title" = "Vis kode live ved siden af diagrammet";
"web_live_hide" = "Skjul live-kode";
"web_live_resize" = "Skift kodeområdets bredde (dobbeltklik: nulstil)";
"web_live_hint" = "Koden vokser med dit diagram. Gråt = pladsholder: skriv i inspektøren, så vises teksten her. Klik på en linje for at vælge elementet.";
"web_live_ph_selector" = "variabel";
"web_live_ph_code" = "Din kode";
9 changes: 9 additions & 0 deletions web/src/i18n/de.strings
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,12 @@
"web_site_home" = "Startseite";
"web_site_imprint" = "Impressum";
"web_site_privacy" = "Datenschutz";

/* Code live */
"web_live_title" = "Code live";
"web_live_toggle_title" = "Code live neben dem Struktogramm anzeigen";
"web_live_hide" = "Code live ausblenden";
"web_live_resize" = "Breite des Codebereichs ändern (Doppelklick: zurücksetzen)";
"web_live_hint" = "Der Code wächst mit deinem Struktogramm. Grau = Platzhalter: Schreib im Objektinspektor, dann steht dort dein Text. Klick auf eine Zeile markiert das Element.";
"web_live_ph_selector" = "Variable";
"web_live_ph_code" = "Dein Code";
9 changes: 9 additions & 0 deletions web/src/i18n/el.strings
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,12 @@
"web_site_home" = "Αρχική σελίδα";
"web_site_imprint" = "Στοιχεία εκδότη";
"web_site_privacy" = "Απόρρητο";

/* Code live */
"web_live_title" = "Ζωντανός κώδικας";
"web_live_toggle_title" = "Εμφάνιση κώδικα ζωντανά δίπλα στο διάγραμμα";
"web_live_hide" = "Απόκρυψη ζωντανού κώδικα";
"web_live_resize" = "Αλλαγή πλάτους περιοχής κώδικα (διπλό κλικ: επαναφορά)";
"web_live_hint" = "Ο κώδικας μεγαλώνει μαζί με το διάγραμμα. Γκρι = σύμβολο κράτησης: γράψε στον επιθεωρητή και το κείμενό σου εμφανίζεται εδώ. Κάνε κλικ σε μια γραμμή για να επιλέξεις το στοιχείο.";
"web_live_ph_selector" = "μεταβλητή";
"web_live_ph_code" = "Ο κώδικάς σου";
9 changes: 9 additions & 0 deletions web/src/i18n/en.strings
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,12 @@
"web_site_home" = "Home page";
"web_site_imprint" = "Imprint";
"web_site_privacy" = "Privacy";

/* Code live */
"web_live_title" = "Live code";
"web_live_toggle_title" = "Show code live next to the diagram";
"web_live_hide" = "Hide live code";
"web_live_resize" = "Change width of the code area (double-click: reset)";
"web_live_hint" = "The code grows with your diagram. Grey = placeholder: type in the object inspector and your text appears there. Click a line to select its element.";
"web_live_ph_selector" = "variable";
"web_live_ph_code" = "Your code";
9 changes: 9 additions & 0 deletions web/src/i18n/es.strings
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,12 @@
"web_site_home" = "Página de inicio";
"web_site_imprint" = "Aviso legal";
"web_site_privacy" = "Privacidad";

/* Code live */
"web_live_title" = "Código en vivo";
"web_live_toggle_title" = "Mostrar el código en vivo junto al diagrama";
"web_live_hide" = "Ocultar código en vivo";
"web_live_resize" = "Cambiar el ancho del área de código (doble clic: restablecer)";
"web_live_hint" = "El código crece con tu diagrama. Gris = marcador: escribe en el inspector y tu texto aparecerá ahí. Haz clic en una línea para seleccionar su elemento.";
"web_live_ph_selector" = "variable";
"web_live_ph_code" = "Tu código";
9 changes: 9 additions & 0 deletions web/src/i18n/fr.strings
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,12 @@
"web_site_home" = "Accueil";
"web_site_imprint" = "Mentions légales";
"web_site_privacy" = "Confidentialité";

/* Code live */
"web_live_title" = "Code en direct";
"web_live_toggle_title" = "Afficher le code en direct à côté du diagramme";
"web_live_hide" = "Masquer le code en direct";
"web_live_resize" = "Modifier la largeur de la zone de code (double-clic : réinitialiser)";
"web_live_hint" = "Le code évolue avec ton diagramme. Gris = espace réservé : écris dans l’inspecteur et ton texte apparaît ici. Clique sur une ligne pour sélectionner son élément.";
"web_live_ph_selector" = "variable";
"web_live_ph_code" = "Ton code";
9 changes: 9 additions & 0 deletions web/src/i18n/he.strings
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,12 @@
"web_site_home" = "דף הבית";
"web_site_imprint" = "פרטי המפרסם";
"web_site_privacy" = "פרטיות";

/* Code live */
"web_live_title" = "קוד חי";
"web_live_toggle_title" = "הצגת קוד בזמן אמת ליד התרשים";
"web_live_hide" = "הסתרת קוד חי";
"web_live_resize" = "שינוי רוחב אזור הקוד (לחיצה כפולה: איפוס)";
"web_live_hint" = "הקוד גדל יחד עם התרשים. אפור = ממלא מקום: כתבו במפקח והטקסט יופיע כאן. לחצו על שורה כדי לבחור את הרכיב.";
"web_live_ph_selector" = "משתנה";
"web_live_ph_code" = "הקוד שלך";
Loading
Loading