From f1c4867ba25183c159c0c66d88ff971f67fbd1c4 Mon Sep 17 00:00:00 2001 From: "smalruby3-editor-bot[bot]" <297607354+smalruby3-editor-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:54:30 +0000 Subject: [PATCH 1/5] fix(ja-notation): tell the variables of the stage instead of writing them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Japanese mode is written for a program that runs alone, as on a terminal, and has no stage. Ruby → Japanese tells each `$a` (a variable or a list of the stage) at its name as `stage-variable`, which the editor says as "ステージの変数($a)は日本語モードでは書けません。Ruby モードでは書けます。", in place of the no-ja-form error of the whole statement. Closes #1706 Co-Authored-By: Claude Opus 5.5 --- docs/dncl/README.md | 11 ++- docs/dncl/design.md | 9 ++ packages/ja-notation/src/read-ruby.js | 50 +++++++++- .../ja-notation/test/data/ruby-to-ja.json | 96 +++++++++++++++++++ .../scratch-gui/src/containers/ruby-tab.jsx | 11 +++ .../src/lib/dncl/dncl-validator.js | 18 ++++ .../src/lib/dncl/ja-notation-errors.js | 11 ++- packages/scratch-gui/src/locales/en.js | 2 + packages/scratch-gui/src/locales/ja-Hira.js | 2 + packages/scratch-gui/src/locales/ja.js | 1 + .../fixtures/ja-notation/golden/ruby.json | 4 +- .../unit/lib/dncl/dncl-stage-variable.test.js | 39 ++++++++ 12 files changed, 247 insertions(+), 7 deletions(-) create mode 100644 packages/scratch-gui/test/unit/lib/dncl/dncl-stage-variable.test.js diff --git a/docs/dncl/README.md b/docs/dncl/README.md index c4ea4c64d3..b793f43e0a 100644 --- a/docs/dncl/README.md +++ b/docs/dncl/README.md @@ -178,18 +178,21 @@ prism の解析の関数は外から受けとり(`rubyToJa(source, { parse, .. 本体のほかの文が変数も増分も変えないときだけ `〜ずつ増やしながら繰り返す` にする。それ以外は `i = 1` と `i <= 10 の間繰り返す:` のまま。 `(a / b).to_i` は `a ÷ b`、`-((a / b).to_i)` は `-a ÷ b`(日本語では `-(a ÷ b)` と読むので、符号を `÷` の左に置く)。`((-a) / b).to_i` は `÷` にしない(`整数(-a / b)`)。 `!(...)` のかっこは残す(`not (a > 10)`)。`until 条件` は `not 条件 の間繰り返す:`、`wait until 条件` は中身の無い繰り返し。 -- 日本語に書きかえるものが無い Ruby(`with_screen_refresh do` / `loop do` / `list.each do |x|` などの `xxx do`、`unless`、後置の `if`、`begin … end while`、`$g`、`nil` など)は、 +- 日本語に書きかえるものが無い Ruby(`with_screen_refresh do` / `loop do` / `list.each do |x|` などの `xxx do`、`unless`、後置の `if`、`begin … end while`、`nil` など)は、 **書いてあるとおりの Ruby のまま**(`end` も)残す(JaAST の `RubyCode`)。中の命令と数の誤りは、そのまま Ruby の行に出す(日本語モードはこうした Ruby を切りかえで受け付けない)。 - それ自体が誤りでない Ruby(`case` / `when`、ハッシュ `{}`、シンボル `:a`、後置の `unless` / `if`、三項演算子、`nil`、`$g` など)も、黙って残さずに `no-ja-form` の誤りにする + それ自体が誤りでない Ruby(`case` / `when`、ハッシュ `{}`、シンボル `:a`、後置の `unless` / `if`、三項演算子、`nil` など)も、黙って残さずに `no-ja-form` の誤りにする (黙って残すと、日本語に戻したときに「「@」は使えません」「「{」が読めません」のような見当違いの誤りになるため)。誤りは残した Ruby のいちばん外のものに 1 つだけ出し、 キーワードで始まるものはキーワードの位置にキーワードの名前で(`unless`)、それ以外は先頭の位置に Ruby の字(1 行目の 20 字まで。長いものは `…`)で出す。 その Ruby に命令や `break` の誤りがすでに出ているときは足さない。prism が文法の誤りを出したときは足さない(立て直しのノードの誤りを並べないため)。 + ステージの変数・リスト(`$g`)は、日本語モードが想定しない([`design.md`](design.md) の「ステージの変数は書かない」)ので、 + 書いてあるとおりに残したうえで、`$g` の名前の位置(読むところ・代入・`+=`・多重代入の左辺・`$g.push(1)` の受け手)に `stage-variable` の誤りを出す + (`no-ja-form` や `push` の命令の誤りは足さない)。 表を渡さないとき(ほかの処理系)は、大文字の名前(Ruby の定数 `A`)も名前として読む(`buildRuby` がそう書くため)。 `N.times do` と `(a..b).step(s) do |i|` / `a.step(b, -s) do |i|` は `〜ずつ増やしながら繰り返す` にする。 - 書き方(`write-ja.js`): 下の「書き出しの形」。演算子は日本語の読み方(`parse.js`)の強さで、要るところだけかっこを付ける(Ruby に書いてあったかっこは残さない。`not` の後ろは上のとおり)。 空行は Ruby の空行の位置に残す(読み手が JaAST に `blankLines` を付ける)。行末のコメントは、その Ruby の行から作った日本語の行の末尾に付け直す。 - 誤り: 日本語モードに無い命令(`unknown-command`。`(` の付いた名前、括弧の無いメソッド、受け手のあるメソッド、`xxx do` の `xxx`、`break` / `next` / `redo` / `retry`)、 - 数の書き方(`bad-number`)、後判定の繰り返し(`post-test-loop`。`begin` と `end while` の行)、日本語に無い書き方(`no-ja-form`。上の `RubyCode`)、Ruby の文法の誤り(`ruby-syntax`)。行と列は Ruby の行。 + 数の書き方(`bad-number`)、後判定の繰り返し(`post-test-loop`。`begin` と `end while` の行)、日本語に無い書き方(`no-ja-form`。上の `RubyCode`)、ステージの変数(`stage-variable`)、Ruby の文法の誤り(`ruby-syntax`)。行と列は Ruby の行。 命令と取らないのは、表にある呼び出し、プログラムで `def` した名前、`dncl-keywords.js` の `RUBY_LITERALS`(`answer` / `ask` など)。ローカル変数は prism が変数と分かるので取らない。 - 構文木を歩く処理は、長い `and` / `+` の並び(左に深い木)をくり返しで歩くので、項が数千あってもスタックが尽きない。prism 自身はおよそ 5000 項の式を解析できないので、それより長い式は誤り (「プログラムが長すぎて日本語にできません」)にする。 @@ -214,6 +217,7 @@ ja-notation の誤りは `ja-notation-errors.js` が、生徒に見えている | `post-test-loop` | 後判定の繰り返しの文(`postTestLoop`) | | `unknown-command` | 「「move」は日本語モードでは書けない命令です。Ruby モードでは書けます。」、日本語の名前は「「差分」は定義されていない関数です。「関数 差分(…):」で定義してください。」(`unsupportedCommand`) | | `no-ja-form` | 「「case」は日本語モードでは書けません。Ruby モードでは書けます。」(`unsupportedNotation`。Ruby → 日本語だけ) | +| `stage-variable` | 「ステージの変数($a)は日本語モードでは書けません。Ruby モードでは書けます。」(`stageVariable`。Ruby → 日本語だけ) | | `unclosed` / `empty-block` / `block`(閉じのことば・`そうでなければ`) | 下の「閉じ忘れのエラー」の文 | | そのほか(読めない字句・式が要る など) | ja-notation の文のまま(「「//」が読めません」など) | @@ -549,6 +553,7 @@ Smalruby は **共通テスト用プログラム表記の形のプログラム - `dncl-standard-form.test.js` — 書き出しの標準の形(字下げと `:`・`and` / `or` / `not`・`%`・`を返す`・終端の行を残す場合)と、DNCL 風の形も読むこと - `dncl-loop-jump.test.js` — 繰り返しの中の `break` / `next`(後置の `if` / `unless` 付き・1 行だけ・`redo` / `retry`)がその行のエラーで止まり、`@break` のような Ruby にならないこと。同じ名前の変数は往復できること - `dncl-no-ja-form.test.js` — 日本語に無い書き方(`case` / `when`・ハッシュ・シンボル・後置の `unless` / `if`・三項演算子)が Ruby → 日本語でその場所の誤り(`unsupportedNotation`)になり、日本語モードにある Ruby は誤りにならないこと + - `dncl-stage-variable.test.js` — ステージの変数・リスト(`$a`)が Ruby → 日本語でその名前の位置の誤り(`stageVariable`)になり、スプライトの変数(`@a`)は日本語になること - `dncl-unsupported-command.test.js` — 日本語モードに無い命令(引数あり・なし・変数と同じ名前・式や条件の中・`xxx do` と `|x|`)がその行のエラーで止まり、定義した関数の呼び出しや組み込み関数は往復できること(DNCL → Ruby と Ruby → DNCL の両方) - `dncl-do-block.test.js` — 日本語にしない `xxx do ... end` が `を実行する` で閉じ、外側の `〜の間` / `もし` / `関数` の閉じのことばがずれないこと(入れ子・`until x do`・後判定の中・文字列やコメントの中の `do`) - `dncl-roundtrip.test.js` — DNCL ↔ Ruby round-trip 安定性 diff --git a/docs/dncl/design.md b/docs/dncl/design.md index 12c68e4ac2..f35a054e05 100644 --- a/docs/dncl/design.md +++ b/docs/dncl/design.md @@ -148,6 +148,15 @@ Ruby や日本語のプログラムの `表示する` は、キャラクター Ruby タブは Scratch の部分集合(Scratch でできることを Ruby で書く)なので、コンソールのブロックを Ruby で書く形は足さない。 - 将来の案: Ruby タブに「コンソールモード」のような切りかえを置き、そのときだけ `puts` / `gets` がコンソールを使う。いまは作らない。 +### ステージの変数は書かない + +- 日本語モードは、**ターミナルで動かすような、1 つで動くプログラム**を想定する。上のとおりステージはコンソールになり、 + ステージという考え方はできるだけ薄くする。ステージの変数・リストや、ほかのスプライトの変数は使わない。 +- そのため、Ruby の `$a`(ステージの変数・リスト)は日本語にしない。Ruby → 日本語では、`$a` の書いてある位置に + 「ステージの変数($a)は日本語モードでは書けません。Ruby モードでは書けます。」の誤りを出す(ほかの日本語にできない Ruby と同じく、 + 日本語に切りかえず Ruby タブにとどまる)。日本語の変数は、いつもそのスプライトの変数(Ruby の `@a`)になる。 +- ステージの変数を使うプログラムは Ruby タブで書く。 + ### 要素の追加 - 日本語の `A に 値 を追加する` で書けるようにする。 diff --git a/packages/ja-notation/src/read-ruby.js b/packages/ja-notation/src/read-ruby.js index 38140bf47b..4b0d638e8c 100644 --- a/packages/ja-notation/src/read-ruby.js +++ b/packages/ja-notation/src/read-ruby.js @@ -43,6 +43,20 @@ const WRITE_TYPES = new Set([ /** The statements that hold a body (they take the comments of their own lines). */ const BLOCK_TYPES = new Set(['If', 'While', 'For', 'FunctionDef']); +/** + * The nodes of a variable of the stage (`$a`, a variable or a list of the + * stage in Smalruby). The Japanese mode is written for a program that runs + * alone, as on a terminal, and has no stage: it does not write them (Issue #1706). + */ +const STAGE_VARIABLE_TYPES = new Set([ + 'GlobalVariableReadNode', + 'GlobalVariableWriteNode', + 'GlobalVariableOperatorWriteNode', + 'GlobalVariableOrWriteNode', + 'GlobalVariableAndWriteNode', + 'GlobalVariableTargetNode', +]); + /** The keywords that jump in a loop: the Japanese has no such statement. */ const JUMPS = { BreakNode: 'break', NextNode: 'next', RedoNode: 'redo', RetryNode: 'retry' }; @@ -61,6 +75,8 @@ class RubyReader { this.errors = []; // Where each error is (character index), to tell whether a RubyCode has one in it. this.errorStarts = []; + // The errors told already (code and place), so a node read twice is told once. + this.told = new Set(); // Ruby prism could not read has nodes of its recovery: only its first error is told. this.hasSyntaxErrors = (result.errors || []).length > 0; this.rawDepth = 0; @@ -187,7 +203,8 @@ class RubyReader { /** * Note an error at a node or a location. - * @param {string} code - `unknown-command`, `bad-number`, `post-test-loop`, `no-ja-form` or `ruby-syntax`. + * @param {string} code - `unknown-command`, `bad-number`, `post-test-loop`, `no-ja-form`, + * `stage-variable` or `ruby-syntax`. * @param {string} message - The message. * @param {object} at - The node or location. * @param {object} [detail] - More (`name`). @@ -195,11 +212,24 @@ class RubyReader { fail(code, message, at, detail = {}) { const loc = typeof at.startOffset === 'number' ? at : field(at, 'location'); const start = this.index.charAt(loc.startOffset); + const key = `${code}:${start}`; + if (this.told.has(key)) return; + this.told.add(key); const { line, column } = this.index.place(start); this.errors.push({ code, message, line, column, ...detail }); this.errorStarts.push(start); } + /** + * Note a variable of the stage (`$a`; Issue #1706), at its name. + * @param {object} node - A node of `STAGE_VARIABLE_TYPES`. + */ + failStageVariable(node) { + const name = field(node, 'name'); + const at = field(node, 'nameLoc') || node; + this.fail('stage-variable', `ステージの変数(${name})は日本語では書けません`, at, { name }); + } + /** * Note Ruby with no Japanese form that no other error tells (`case`, a * hash, a symbol, a modifier `unless`; Issue #1740): kept as it is @@ -336,6 +366,12 @@ class RubyReader { } case 'MultiWriteNode': return this.multiAssign(node); + case 'GlobalVariableWriteNode': + case 'GlobalVariableOperatorWriteNode': + case 'GlobalVariableOrWriteNode': + case 'GlobalVariableAndWriteNode': + this.failStageVariable(node); + return this.rawStatement(node); case 'InstanceVariableOperatorWriteNode': case 'LocalVariableOperatorWriteNode': case 'ConstantOperatorWriteNode': @@ -377,6 +413,11 @@ class RubyReader { append(node, call) { if (!call || (call.name !== 'push' && call.name !== '<<') || !call.receiver || call.block) return null; if (!call.args || call.args.length !== 1) return null; + // `$a.push(1)`: the list of the stage is told, not the call (Issue #1706). + if (STAGE_VARIABLE_TYPES.has(typeOf(call.receiver))) { + this.failStageVariable(call.receiver); + return this.rawStatement(node); + } const target = this.expression(call.receiver); if (target.type !== 'Name') return null; return this.at(node, { type: 'Append', target, value: this.expression(call.args[0]) }); @@ -432,6 +473,10 @@ class RubyReader { const targets = lefts.map((left) => { const type = typeOf(left); if (/^(?:InstanceVariable|LocalVariable|Constant)TargetNode$/.test(type)) return this.target(left); + if (STAGE_VARIABLE_TYPES.has(type)) { + this.failStageVariable(left); + return null; + } // `@a[0], @a[1] = @a[1], @a[0]`: an element of an array (Issue #2237). if (type === 'IndexTargetNode') { const args = field(left, 'arguments'); @@ -1020,6 +1065,9 @@ class RubyReader { } case 'LocalVariableReadNode': return { type: 'Name', name: field(node, 'name'), ...where }; + case 'GlobalVariableReadNode': + this.failStageVariable(node); + return this.raw(node); case 'ConstantReadNode': // With no table, a name in capitals is a constant (see `target`). return this.options.variable ? this.raw(node) : { type: 'Name', name: field(node, 'name'), ...where }; diff --git a/packages/ja-notation/test/data/ruby-to-ja.json b/packages/ja-notation/test/data/ruby-to-ja.json index 173d0ae301..93d40fd547 100644 --- a/packages/ja-notation/test/data/ruby-to-ja.json +++ b/packages/ja-notation/test/data/ruby-to-ja.json @@ -181,6 +181,102 @@ "ruby": "x = gets\nA[0] = gets.to_i", "ja": "x = 【外部からの入力】\nA[0] = 【整数を入力】", "errors": [] + }, + { + "title": "a variable of the stage ($) is told where it is, as the Japanese has no stage (Issue #1706)", + "table": "none", + "ruby": "$a = 1\nx = $a + 1", + "ja": "$a = 1\nx = $a + 1", + "errors": [ + { + "code": "stage-variable", + "message": "ステージの変数($a)は日本語では書けません", + "line": 1, + "column": 0, + "name": "$a" + }, + { + "code": "stage-variable", + "message": "ステージの変数($a)は日本語では書けません", + "line": 2, + "column": 4, + "name": "$a" + } + ] + }, + { + "title": "a list of the stage is told once, not as a command it calls (Issue #1706)", + "table": "none", + "ruby": "$a = []\n$a.push(1)", + "ja": "$a = []\n$a.push(1)", + "errors": [ + { + "code": "stage-variable", + "message": "ステージの変数($a)は日本語では書けません", + "line": 1, + "column": 0, + "name": "$a" + }, + { + "code": "stage-variable", + "message": "ステージの変数($a)は日本語では書けません", + "line": 2, + "column": 0, + "name": "$a" + } + ] + }, + { + "title": "a variable of the stage changed by an operator is told at its name (Issue #1706)", + "table": "none", + "ruby": "$a += 1", + "ja": "$a += 1", + "errors": [ + { + "code": "stage-variable", + "message": "ステージの変数($a)は日本語では書けません", + "line": 1, + "column": 0, + "name": "$a" + } + ] + }, + { + "title": "a variable of the stage among the targets of a multiple assignment is told (Issue #1706)", + "table": "none", + "ruby": "x, $b = 1, 2", + "ja": "x, $b = 1, 2", + "errors": [ + { + "code": "stage-variable", + "message": "ステージの変数($b)は日本語では書けません", + "line": 1, + "column": 3, + "name": "$b" + } + ] + }, + { + "title": "an element of a list of the stage is told at the list (Issue #1706)", + "table": "none", + "ruby": "$a[0] = 1\nx = $a[1]", + "ja": "$a[0] = 1\nx = $a[1]", + "errors": [ + { + "code": "stage-variable", + "message": "ステージの変数($a)は日本語では書けません", + "line": 1, + "column": 0, + "name": "$a" + }, + { + "code": "stage-variable", + "message": "ステージの変数($a)は日本語では書けません", + "line": 2, + "column": 4, + "name": "$a" + } + ] } ] } diff --git a/packages/scratch-gui/src/containers/ruby-tab.jsx b/packages/scratch-gui/src/containers/ruby-tab.jsx index 484ba6c015..7ff9339b1f 100644 --- a/packages/scratch-gui/src/containers/ruby-tab.jsx +++ b/packages/scratch-gui/src/containers/ruby-tab.jsx @@ -23,6 +23,7 @@ import { FORBIDDEN_PREFIX_ERROR_ID, isRubyCommandName, POST_TEST_LOOP_ERROR_ID, + STAGE_VARIABLE_ERROR_ID, UNSUPPORTED_COMMAND_ERROR_ID, UNSUPPORTED_NOTATION_ERROR_ID, UNSUPPORTED_NUMBER_ERROR_ID, @@ -812,6 +813,16 @@ const RubyTab = (props) => { { name: err.name }, ); } + if (err.id === STAGE_VARIABLE_ERROR_ID) { + return intl.formatMessage( + { + id: 'gui.rubyTab.dnclStageVariableError', + defaultMessage: + 'A variable of the stage ({name}) cannot be written in Japanese mode. You can write it in Ruby mode.', + }, + { name: err.name }, + ); + } if (err.id === UNSUPPORTED_NOTATION_ERROR_ID) { return intl.formatMessage( { diff --git a/packages/scratch-gui/src/lib/dncl/dncl-validator.js b/packages/scratch-gui/src/lib/dncl/dncl-validator.js index f1a03aa765..f6b60a99d6 100644 --- a/packages/scratch-gui/src/lib/dncl/dncl-validator.js +++ b/packages/scratch-gui/src/lib/dncl/dncl-validator.js @@ -172,6 +172,22 @@ const UNSUPPORTED_NOTATION_ERROR_ID = 'unsupportedNotation'; */ const unsupportedNotationMessage = (name) => `「${name}」は日本語モードでは書けません。Ruby モードでは書けます。`; +/** + * The id of the error for a variable or a list of the stage (`$a`) in the Ruby + * (issue #1706). The Japanese mode is written for a program that runs alone, + * as on a terminal, and has no stage: Ruby → Japanese does not write them and + * tells them where they are. The `name` is the variable (`$a`). + */ +const STAGE_VARIABLE_ERROR_ID = 'stageVariable'; + +/** + * The message of the stage variable error. + * @param {string} name - The variable (`$a`). + * @returns {string} The message. + */ +const stageVariableMessage = (name) => + `ステージの変数(${name})は日本語モードでは書けません。Ruby モードでは書けます。`; + /** * The command of a `do` block line: the name just before `do` and the * arguments of the command (`with_screen_refresh do` → `with_screen_refresh`, @@ -320,6 +336,8 @@ export { isRubyCommandName, POST_TEST_LOOP_ERROR_ID, POST_TEST_LOOP_MESSAGE, + STAGE_VARIABLE_ERROR_ID, + stageVariableMessage, UNSUPPORTED_COMMAND_ERROR_ID, unsupportedCommandMessage, UNSUPPORTED_NOTATION_ERROR_ID, diff --git a/packages/scratch-gui/src/lib/dncl/ja-notation-errors.js b/packages/scratch-gui/src/lib/dncl/ja-notation-errors.js index 82e8cf5c32..82d9ada28c 100644 --- a/packages/scratch-gui/src/lib/dncl/ja-notation-errors.js +++ b/packages/scratch-gui/src/lib/dncl/ja-notation-errors.js @@ -12,6 +12,8 @@ import { FORBIDDEN_PREFIX_ERROR_ID, POST_TEST_LOOP_ERROR_ID, POST_TEST_LOOP_MESSAGE, + STAGE_VARIABLE_ERROR_ID, + stageVariableMessage, UNSUPPORTED_NOTATION_ERROR_ID, UNSUPPORTED_NUMBER_ERROR_ID, UNSUPPORTED_COMMAND_ERROR_ID, @@ -65,7 +67,7 @@ const blockMessage = (error) => { * @param {object} error - An error of ja-notation. * @returns {?object} The error, or null when it is not one of the words of * the Japanese mode (a Ruby command, a number, Ruby with no Japanese form, - * `@`, the post-test loop). + * a variable of the stage, `@`, the post-test loop). */ const wordError = (error) => { const at = { line: error.line, column: error.column + 1 }; @@ -88,6 +90,13 @@ const wordError = (error) => { name: error.name, message: unsupportedNotationMessage(error.name), }; + case 'stage-variable': + return { + ...at, + id: STAGE_VARIABLE_ERROR_ID, + name: error.name, + message: stageVariableMessage(error.name), + }; case 'unknown-command': return { ...at, diff --git a/packages/scratch-gui/src/locales/en.js b/packages/scratch-gui/src/locales/en.js index 6ee6c625ca..4cc0b8c4b3 100644 --- a/packages/scratch-gui/src/locales/en.js +++ b/packages/scratch-gui/src/locales/en.js @@ -1570,6 +1570,8 @@ export default { 'gui.rubyTab.dnclForbiddenPrefixError': '"{name}" cannot be used in a variable in Japanese mode.', 'gui.rubyTab.dnclPostTestLoopError': 'A post-test loop (a loop that runs once before it checks the condition) cannot be written in Japanese. Write the first run before the loop, then make it a "〜の間繰り返す" loop. You can write it in Ruby mode.', + 'gui.rubyTab.dnclStageVariableError': + 'A variable of the stage ({name}) cannot be written in Japanese mode. You can write it in Ruby mode.', 'gui.rubyTab.dnclUndefinedFunctionError': '"{name}" is a function that is not defined. Define it with "関数 {name}(…):".', 'gui.rubyTab.dnclUnsupportedCommandError': diff --git a/packages/scratch-gui/src/locales/ja-Hira.js b/packages/scratch-gui/src/locales/ja-Hira.js index 31fe8a035f..1fce034b5d 100644 --- a/packages/scratch-gui/src/locales/ja-Hira.js +++ b/packages/scratch-gui/src/locales/ja-Hira.js @@ -1948,6 +1948,8 @@ export default { 'gui.rubyTab.dnclForbiddenPrefixError': 'にほんごモードでは、へんすうに「{name}」はつかえません', 'gui.rubyTab.dnclPostTestLoopError': 'あとではんていするくりかえし(さきに 1 かいうごかしてからじょうけんをたしかめるくりかえし)は、にほんごではかけません。さいしょの 1 かいをループのまえにかいてから、「〜のあいだくりかえす」にしてください。Ruby モードではかけます。', + 'gui.rubyTab.dnclStageVariableError': + 'ステージのへんすう({name})は、にほんごモードではかけません。Ruby モードではかけます。', 'gui.rubyTab.dnclUndefinedFunctionError': '「{name}」は、ていぎされていないかんすうです。「関数 {name}(…):」でていぎしてください。', 'gui.rubyTab.dnclUnsupportedCommandError': diff --git a/packages/scratch-gui/src/locales/ja.js b/packages/scratch-gui/src/locales/ja.js index f215ffacce..d4f59329f0 100644 --- a/packages/scratch-gui/src/locales/ja.js +++ b/packages/scratch-gui/src/locales/ja.js @@ -1907,6 +1907,7 @@ export default { 'gui.rubyTab.dnclForbiddenPrefixError': '日本語モードでは変数に「{name}」は使えません', 'gui.rubyTab.dnclPostTestLoopError': '後判定の繰り返し(先に 1 回動かしてから条件を確かめる繰り返し)は日本語では書けません。最初の 1 回をループの前に書いてから、「〜の間繰り返す」にしてください。Ruby モードでは書けます。', + 'gui.rubyTab.dnclStageVariableError': 'ステージの変数({name})は日本語モードでは書けません。Ruby モードでは書けます。', 'gui.rubyTab.dnclUndefinedFunctionError': '「{name}」は定義されていない関数です。「関数 {name}(…):」で定義してください。', 'gui.rubyTab.dnclUnsupportedCommandError': diff --git a/packages/scratch-gui/test/fixtures/ja-notation/golden/ruby.json b/packages/scratch-gui/test/fixtures/ja-notation/golden/ruby.json index dc1ae666fd..dd2ba056c5 100644 --- a/packages/scratch-gui/test/fixtures/ja-notation/golden/ruby.json +++ b/packages/scratch-gui/test/fixtures/ja-notation/golden/ruby.json @@ -171,9 +171,9 @@ { "line": 1, "column": 6, - "id": "unsupportedNotation", + "id": "stageVariable", "name": "$b", - "message": "「$b」は日本語モードでは書けません。Ruby モードでは書けます。" + "message": "ステージの変数($b)は日本語モードでは書けません。Ruby モードでは書けます。" }, { "line": 3, diff --git a/packages/scratch-gui/test/unit/lib/dncl/dncl-stage-variable.test.js b/packages/scratch-gui/test/unit/lib/dncl/dncl-stage-variable.test.js new file mode 100644 index 0000000000..8a298fc726 --- /dev/null +++ b/packages/scratch-gui/test/unit/lib/dncl/dncl-stage-variable.test.js @@ -0,0 +1,39 @@ +/** + * The Japanese mode has no stage (Issue #1706): it is written for a program + * that runs alone, as on a terminal. Ruby → Japanese does not write a variable + * or a list of the stage (`$a`) and tells it where it is, so the student is + * not given Japanese that cannot be turned back into Ruby. + */ +import { STAGE_VARIABLE_ERROR_ID } from '../../../../src/lib/dncl/dncl-validator'; +import { rubyToDncl } from '../../../../src/lib/dncl/ruby-to-dncl'; +import { loadPrism } from '../../../../src/lib/prism-parser'; + +beforeAll(() => loadPrism()); + +const lines = (...ls) => ls.join('\n'); + +const told = (line, column, name) => ({ + line, + column, + id: STAGE_VARIABLE_ERROR_ID, + name, + message: `ステージの変数(${name})は日本語モードでは書けません。Ruby モードでは書けます。`, +}); + +describe('Ruby → DNCL: the variables of the stage (issue #1706)', () => { + test('a variable of the stage is told where it is written and read', () => { + expect(rubyToDncl(lines('$a = 1', 'say($a)')).errors).toEqual([told(1, 1, '$a'), told(2, 5, '$a')]); + }); + + test('a list of the stage is told, not the command it calls', () => { + expect(rubyToDncl(lines('$a = []', '$a.push(1)')).errors).toEqual([told(1, 1, '$a'), told(2, 1, '$a')]); + }); + + test('a variable of the stage changed by an operator is told at its name', () => { + expect(rubyToDncl('$score += 1').errors).toEqual([told(1, 1, '$score')]); + }); + + test('a variable of the sprite is still written in the Japanese', () => { + expect(rubyToDncl(lines('@a = 1', 'say(@a)'))).toEqual({ dncl: lines('a = 1', '表示する(a)'), errors: [] }); + }); +}); From 0b655c92b506edb51858f4b440df3b4cdc23030e Mon Sep 17 00:00:00 2001 From: "smalruby3-editor-bot[bot]" <297607354+smalruby3-editor-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:00:12 +0000 Subject: [PATCH 2/5] fix(ja-notation): read full-width letters and digits as half-width ones MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Out of the strings and the comments, the lexer makes the full-width letters and digits half-width before it reads them (`x1` is `x1`, `and` is `and`), as the auto-correct of the Ruby mode does. A full-width letter is no longer a name of its own (the decision of #1714 is taken back). The strings and the comments keep what is written. Closes #2266 Co-Authored-By: Claude Opus 5.5 --- docs/dncl/README.md | 12 ++-- docs/dncl/policy.md | 2 +- docs/smalruby-dncl-spec.ja.md | 5 +- packages/ja-notation/src/lexer.js | 71 ++++++++++++++----- .../ja-notation/test/data/ja-to-ruby.json | 38 ++++++++-- .../test/fixtures/ja-notation/golden/ja.json | 8 +-- .../lib/dncl/dncl-number-notation.test.js | 9 ++- 7 files changed, 107 insertions(+), 38 deletions(-) diff --git a/docs/dncl/README.md b/docs/dncl/README.md index b793f43e0a..49a133ea51 100644 --- a/docs/dncl/README.md +++ b/docs/dncl/README.md @@ -150,18 +150,20 @@ DNCL 風の形の読み方(切りかえる前の変換に合わせたもの) | ファイル | 役割 | |---|---| | `packages/ja-notation/`(ワークスペースのパッケージ `@smalruby/ja-notation`。MIT。`LICENSE` あり) | ライブラリ。依存は無く、`src/` の外を import しない(`packages/ja-notation/test/boundary.test.js`)。使い方・JaAST の形・テストのデータは `packages/ja-notation/README.md`。下の `ja-notation/<ファイル>` は `packages/ja-notation/src/<ファイル>` | -| `ja-notation/lexer.js` | 1 行を字句に分ける。全角の演算子・`≦` など、数の全角数字(`12`)、コメントの `#` は半角のものとして読み、`“…”` は文字列として読む。名前の文字の判定(`isName` / `isNameHead` / `isNameChar`。下の「名前に使える文字」)もここにあり、エディタの判定(`paren-utils.js`)も同じものを使う | +| `ja-notation/lexer.js` | 1 行を字句に分ける。文字列とコメントの外の全角英字・全角数字(`x1` `12`)はまず半角にし(`halfWidthAlphanumerics`)、全角の演算子・`≦` など、コメントの `#` は半角のものとして読み、`“…”` は文字列として読む。名前の文字の判定(`isName` / `isNameHead` / `isNameChar`。下の「名前に使える文字」)もここにあり、エディタの判定(`paren-utils.js`)も同じものを使う | | `ja-notation/parse.js` | 日本語を読む。標準の形(行番号・`|` `⎿`・字下げ・`ならば:`・`and` / `or` / `not`)と DNCL 風の形(閉じる行・`←`・`かつ`・`でない`・「...」)。JaAST の形は `ja-notation/ja-ast.js` | | `ja-notation/build-ruby.js` | JaAST → Ruby の構文木(prism のノード名を使う小さな形)。変数の名前・関数・入力は外から受けとる表で決める | | `ja-notation/write-ruby.js` | Ruby のテキストと、Ruby の行ごとの日本語の行を書く | 名前に使える文字(`ja-notation/lexer.js` の `NAME_HEAD_RE` / `NAME_TAIL_RE`。Issue #1714): -- 1 文字目: 英字・`_`・どの文字体系の文字(Unicode の `\p{L}`。かな・漢字(CJK 拡張 A〜と BMP の外の `𠮷` も)・`々`・`〆`・`ヵ` `ヶ`・`ー`・全角英字・ギリシャ文字など)・ +- 1 文字目: 英字・`_`・どの文字体系の文字(Unicode の `\p{L}`。かな・漢字(CJK 拡張 A〜と BMP の外の `𠮷` も)・`々`・`〆`・`ヵ` `ヶ`・`ー`・ギリシャ文字など)・ 文字としての数字(`\p{Nl}`。`〇` `Ⅱ`)と、ひらがな・カタカナの区画の記号(`゛` `・` など。前から読めていたもの) -- 2 文字目から: 上に加えて、数字(`\p{Nd}`。全角の `1` も)と結合文字(`\p{M}`。`か` + `゙`) +- 2 文字目から: 上に加えて、数字(`\p{Nd}`)と結合文字(`\p{M}`。`か` + `゙`) - Ruby はこれらをどれも名前に使えて、Ruby → 日本語は名前をそのまま書く(`@佐々木` → `佐々木`)。日本語 → Ruby が同じ範囲を名前として読むので、書いた名前は読み戻せる。 -- 全角英字は全角のままの別の名前(`x` は `x` ではない)。Ruby でも別の変数なので、見た目の揺れとして 1 つにそろえない(`policy.md`)。 +- 全角英字・全角数字は、文字列(`"…"` `'…'` `「…」`)とコメントの外では、読む前にすべて半角にする(`x1` は `x1`、`and` は `and`)。見た目だけの揺れで(`policy.md`)、Ruby モードの自動置換も半角にするのと同じ考え。 + 文字列とコメントの中は書いたとおりに残す(`表示する("ABC")` は `"ABC"` のまま)。全角と半角は 1 字ずつ同じ長さなので、誤りの列は変わらない。 + Ruby → 日本語は Ruby の名前をそのまま書く(`@x` → `x`)ので、日本語から Ruby に戻すと `@x` になる。 - `☆` `①` `😀` のような記号は名前に使えず、「「☆」が読めません」の誤りになる(BMP の外の文字も 1 文字として示す)。 誤りは `{code, message, line, column}` に、日本語モードの文言を作るための `name`(字句)・`opener` / `direction` / `colon` / `word`(ブロック)・`block`(`stray-closer` / `closer-indent` / `stray-branch`)を添えて返す。 @@ -425,7 +427,7 @@ Smalruby は **共通テスト用プログラム表記の形のプログラム | 戻り値(標準の形) | `x * 2 を返す` | `return x * 2`(`返す x * 2` も読む) | | 要素の追加 | `Data に 3 を追加する` | `@_array_Data_.push(3)`(ブロックは「(3) を (Data) に追加する」。Ruby の `<<` も `を追加する` に戻す) | | 余り(全角) | `a % 3` | `a % 3` | -| 全角数字 | `a = 12` | `a = 12`(見た目だけの揺れとして半角で読む。名前の中の `x1` は名前のまま) | +| 全角英字・全角数字 | `a = 12` | `@a = 12`(見た目だけの揺れとして半角で読む。名前の中も `x1` → `x1`。文字列とコメントの中は変えない) | | インデントマーカー (`|`) | ` | a = 1` | ` a = 1`(2 スペース/marker)。`|` `│` も同じ | | 暗黙の `end` (`⎿`) | ` ⎿ a = 1` (1 marker) | ` a = 1` + 自動で `を実行する` 追加。`└` も同じ(英字の `L` は貼り付けで `⎿` に直す) | | 同一行複数 `⎿` | ` ⎿ ⎿ a = 1` | 2 個の `end` を一度に追加 | diff --git a/docs/dncl/policy.md b/docs/dncl/policy.md index ed471125d1..cd66bd625e 100644 --- a/docs/dncl/policy.md +++ b/docs/dncl/policy.md @@ -110,7 +110,7 @@ | 種類 | 扱い | 例 | |---|---|---| | **意味が変わるもの、または問題文で約束されるもの** | **設定にする**。選んだ設定はプログラムの冒頭に説明文として書く | 添字の始まり(0 から / 1 から)、コメントの記号(`#` か `//` か。`//` をコメントにしたときは、`//` を整数の割り算に使えない)、論理演算子の書き方 | -| **意味が変わらない、見た目だけの揺れ** | **設定にしない**。読むとき(貼り付けなど)はどの書き方も受け付ける。書くとき(ブロックや Ruby から日本語にするとき)は 1 つにそろえる | 行番号の形(`(01)` / `(1)`)、罫線の文字(`|` `⎿` / `|` `└`)、`:` と `:`、全角と半角の演算子(`+` `%` `<`)、引き算の記号(`-` / `−` / `–`)、`,` の後の空白 | +| **意味が変わらない、見た目だけの揺れ** | **設定にしない**。読むとき(貼り付けなど)はどの書き方も受け付ける。書くとき(ブロックや Ruby から日本語にするとき)は 1 つにそろえる | 行番号の形(`(01)` / `(1)`)、罫線の文字(`|` `⎿` / `|` `└`)、`:` と `:`、全角と半角の演算子(`+` `%` `<`)、文字列とコメントの外の全角英字・全角数字(`x1` `12`)、引き算の記号(`-` / `−` / `–`)、`,` の後の空白 | - 書くときにそろえる 1 つは、上の「文法の決め方」で決める(新しい年度の問題に合わせる)。 - 専門的でない受験者には細かい設定が難しいので、**よくある設定のパターンを用意**する。 diff --git a/docs/smalruby-dncl-spec.ja.md b/docs/smalruby-dncl-spec.ja.md index 4c746183cf..2ac128d547 100644 --- a/docs/smalruby-dncl-spec.ja.md +++ b/docs/smalruby-dncl-spec.ja.md @@ -151,8 +151,8 @@ c = "「く」がある" # → "「く」がある" のまま ### 識別子に使える文字 - ASCII 英字(`a-z`, `A-Z`)、アンダースコア(`_`)、2 文字目からは数字(`0-9`) -- ひらがな・カタカナ・漢字(CJK 拡張の漢字も)と、`々` `〆` `ヶ` `ー` など名前に使う文字。全角英字・ギリシャ文字など、ほかの文字体系の文字も使えます(`佐々木`、`α`) -- 全角英字は半角とは別の名前です(`x` と `x` は別の変数) +- ひらがな・カタカナ・漢字(CJK 拡張の漢字も)と、`々` `〆` `ヶ` `ー` など名前に使う文字。ギリシャ文字など、ほかの文字体系の文字も使えます(`佐々木`、`α`) +- 全角英字・全角数字は半角として読みます(`x1` は `x1` と同じ変数)。文字列とコメントの中は書いたとおりです - `☆` `①` のような記号は使えません 範囲の詳細は `docs/dncl/README.md` の「名前に使える文字」を参照してください。 @@ -652,6 +652,7 @@ Monaco エディタで以下の要素がハイライトされます: | 等価比較 | `==`(条件式の中の `=` も比較として読むが、`==` を推奨) | | 割り算 | `/`(小数になる割り算)、`÷`(商の整数値)。`//` も商の整数値として使える(コメントの記号を `//` にしたときを除く)。負の数の商は小さいほうへ丸める(`-7 ÷ 2` は `-4`) | | 全角の記号 | `%` `≦` `≧` `≠` `+` などの全角の演算子、`:` `,` も読む。書き出しは半角(余りだけ `%`) | +| 全角英字・全角数字 | 文字列とコメントの外では半角として読む(`x1` は `x1`、`12` は `12`) | | 入力 | `【外部からの入力】`(答えをそのまま使う)と `【整数を入力】`(整数にする) | | 要素の追加 | `A に 値 を追加する`(最後に足す。例題に無いので、方針の決め方の ⑤ で決めた) | | 戻り値 | `値 を返す`(例題に無いので、方針の決め方の ⑤ で決めた) | diff --git a/packages/ja-notation/src/lexer.js b/packages/ja-notation/src/lexer.js index 7693908de9..4967ac97fb 100644 --- a/packages/ja-notation/src/lexer.js +++ b/packages/ja-notation/src/lexer.js @@ -4,18 +4,19 @@ /** * The first character of a name: an ASCII letter, `_`, or a letter of any - * script (`\p{L}`: kana, kanji with the CJK extensions, `々`, `〆`, `ヶ`, full-width - * letters, Greek, ...), a letter number (`\p{Nl}`: `〇`, `Ⅱ`), and the marks of - * the kana blocks (`゛`, `・`). Ruby takes any of them in a name, and Ruby → + * script (`\p{L}`: kana, kanji with the CJK extensions, `々`, `〆`, `ヶ`, + * Greek, ...), a letter number (`\p{Nl}`: `〇`, `Ⅱ`), and the marks of the + * kana blocks (`゛`, `・`). Ruby takes any of them in a name, and Ruby → * Japanese writes the name as it is (`@佐々木` → `佐々木`), so the Japanese reads - * back every name it writes (Issue #1714). A full-width letter is a name of its - * own (`x` is not `x`): Ruby has them as two variables. + * back every name it writes (Issue #1714). A full-width letter or digit out of + * a string and a comment is read as the half-width one before (`x1` is + * `x1`; see `halfWidthAlphanumerics`), as the auto-correct of the Ruby mode does. */ const NAME_HEAD_RE = /[A-Za-z_\p{L}\p{Nl}\u3040-\u309F\u30A0-\u30FF]/u; /** - * A character after the first one of a name: the same, the digits (`\p{Nd}`, - * full-width ones too) and the combining marks (`\p{M}`: `か` and `゙`). + * A character after the first one of a name: the same, the digits (`\p{Nd}`) + * and the combining marks (`\p{M}`: `か` and `゙`). */ const NAME_TAIL_RE = /[A-Za-z0-9_\p{L}\p{Nl}\p{Nd}\p{M}\u3040-\u309F\u30A0-\u30FF]/u; @@ -129,20 +130,33 @@ const stringEnd = (text, start) => { return -1; }; +/** A digit (the full-width ones are made half-width before, see `halfWidthAlphanumerics`). */ +const DIGIT_RE = /[0-9]/; + +/** The full-width letters and digits (`A`–`Z`, `a`–`z`, `0`–`9`). */ +const FULL_WIDTH_ALPHANUMERIC_RE = /[A-Za-z0-9]/g; + /** - * A digit, half-width or full-width (`12` is `12`): only how it looks differs, so a number - * written with full-width digits is read as the number (docs/dncl/policy.md: 見た目だけの揺れ). - * In a name (`x1`) a full-width digit stays a part of the name, as Ruby has it. + * The text with its full-width letters and digits made half-width (`x1 = 12` → + * `x1 = 12`). Only how they look differs (docs/dncl/policy.md: 見た目だけの揺れ), and + * the Ruby mode makes them half-width too (its auto-correct), so the Japanese reads + * them as the half-width ones: `x` is the name `x`, `if` would be `if`. Each is one + * UTF-16 unit, as the half-width one, so the columns stay the same. + * @param {string} text - The code (no string and no comment in it). + * @returns {string} The text. */ -const DIGIT_RE = /[0-90-9]/; +const halfWidthAlphanumerics = (text) => + text.replace(FULL_WIDTH_ALPHANUMERIC_RE, (ch) => String.fromCharCode(ch.charCodeAt(0) - 0xfee0)); /** - * The number as the Ruby writes it: the full-width digits and `.` as half-width ones. - * @param {string} text - The number as written. + * The number as the Ruby writes it: `.` as `.`. + * @param {string} text - The number as written (its digits are half-width). * @returns {string} The number. */ -const halfWidthNumber = (text) => - text.replace(/[0-9.]/g, (ch) => (ch === '.' ? '.' : String.fromCharCode(ch.charCodeAt(0) - 0xfee0))); +const halfWidthNumber = (text) => text.replace(/./g, '.'); + +/** The characters that start a string or a comment, which are not made half-width. */ +const STRING_OR_COMMENT_RE = /["'「“##]|\/\//g; /** * The end of a number that starts at `text[start]`, and whether it is written @@ -185,7 +199,10 @@ const longOperatorAt = (text, i) => LONG_OPERATORS.find((op) => text.startsWith( /** * Read one line of code into tokens. A token is `{type, text, column}` and, - * for some types, `value`: + * for some types, `value`. The full-width letters and digits out of the strings + * and the comments are read as the half-width ones (`halfWidthAlphanumerics`): + * the `text` of a name or a number has the half-width ones. The strings and the + * comments are kept as they are written. * * - `number` (`value`: the number as written, with half-width digits), `badNumber`, `string` (`text` * is the literal with its quotes), `name`, `op` (`value`: the operator, a @@ -198,15 +215,27 @@ const longOperatorAt = (text, i) => LONG_OPERATORS.find((op) => text.startsWith( * - `forbidden`: `@` or `$`, which Japanese names do not have. * - `unknown`: any other character, and a string that is not closed. * - * `column` is the 0-based index in `text` plus `offset`. - * @param {string} text - The code of the line (without its line number and indent). + * `column` is the 0-based index in `source` plus `offset`. + * @param {string} source - The code of the line (without its line number and indent). * @param {number} [offset] - What to add to each column. * @param {string} [commentMarker] - The comment mark of the settings (`#` or * `//`). With `//`, `//` starts a comment (and `#` still does) instead of * being the integer quotient. * @returns {Array} The tokens. */ -const tokenize = (text, offset = 0, commentMarker = '#') => { +const tokenize = (source, offset = 0, commentMarker = '#') => { + let text = source; + // The code is made half-width up to the next string or comment, each time the reading gets there. + let halfWidthTo = 0; + const makeHalfWidthFrom = (start) => { + STRING_OR_COMMENT_RE.lastIndex = start + 1; + const next = STRING_OR_COMMENT_RE.exec(text); + halfWidthTo = next ? next.index : text.length; + text = + text.substring(0, start) + + halfWidthAlphanumerics(text.substring(start, halfWidthTo)) + + text.substring(halfWidthTo); + }; const tokens = []; const push = (type, start, end, extra = {}) => tokens.push({ type, text: text.substring(start, end), column: start + offset, ...extra }); @@ -217,6 +246,10 @@ const tokenize = (text, offset = 0, commentMarker = '#') => { i++; continue; } + if (i >= halfWidthTo && !/["'「“##]/.test(ch) && !text.startsWith('//', i)) { + makeHalfWidthFrom(i); + continue; + } if (ch === '#' || ch === '#') { // A full-width `#` is read as `#` (only how it looks differs). tokens.push({ type: 'comment', text: `#${text.substring(i + 1)}`, column: i + offset }); diff --git a/packages/ja-notation/test/data/ja-to-ruby.json b/packages/ja-notation/test/data/ja-to-ruby.json index 09645ecbea..f5cd4138b2 100644 --- a/packages/ja-notation/test/data/ja-to-ruby.json +++ b/packages/ja-notation/test/data/ja-to-ruby.json @@ -148,10 +148,10 @@ "jaLines": [1, 2, 3, 4, 5] }, { - "title": "a Greek or full-width letter is a name, of its own (x is not x), and full-width digits are in a name after its first character", + "title": "a Greek letter is a name, and a full-width letter or digit is read as the half-width one (x1 is x1, as the Ruby mode makes it)", "table": "none", "ja": "α = 1\nx1 = α ÷ 2\nx = x1", - "ruby": "α = 1\nx1 = (α / 2).to_i\nx = x1", + "ruby": "α = 1\nx1 = (α / 2).to_i\nx = x1", "jaLines": [1, 2, 3] }, { @@ -188,10 +188,38 @@ "jaLines": [1, 2, 3] }, { - "title": "full-width digits are read as the digits (only how they look differs), and the Ruby has the half-width ones", + "title": "full-width digits are read as the digits (only how they look differs), in a number and in a name, and the Ruby has the half-width ones", "table": "none", "ja": "x = 12\ny = 3.5 + x1", - "ruby": "x = 12\ny = 3.5 + x1", + "ruby": "x = 12\ny = 3.5 + x1", + "jaLines": [1, 2] + }, + { + "title": "the full-width letters and digits in a string are kept as they are written", + "table": "plain", + "ja": "表示する(\"ABC123\")\n表示する(「x=1」)\ns = 'a1'", + "ruby": "puts(\"ABC123\")\nputs(\"x=1\")\ns = 'a1'", + "jaLines": [1, 2, 3] + }, + { + "title": "the full-width letters and digits in a comment are kept as they are written, and the code before it is made half-width", + "table": "none", + "ja": "# x は 1 から\nx = 1 # x は 2 まで", + "ruby": "# x は 1 から\nx = 1 # x は 2 まで", + "jaLines": [1, 2] + }, + { + "title": "a keyword in full-width letters is the keyword (and is and)", + "table": "none", + "ja": "flag = x > 0 and not y", + "ruby": "flag = x > 0 && !y", + "jaLines": [1] + }, + { + "title": "with // as the comment mark, the full-width letters of the comment are kept", + "table": "none", + "ja": "// 「//」から行の終わりまでは,処理の対象とならない。\nx = 1 // x を 1 に", + "ruby": "# 「//」から行の終わりまでは,処理の対象とならない。\nx = 1 # x を 1 に", "jaLines": [1, 2] }, { @@ -214,7 +242,7 @@ "errors": [ { "code": "syntax", - "message": "「10回」は読めません。数と名前の間には、「10 * 回」のように演算子を書いてください", + "message": "「10回」は読めません。数と名前の間には、「10 * 回」のように演算子を書いてください", "line": 1, "column": 6 } diff --git a/packages/scratch-gui/test/fixtures/ja-notation/golden/ja.json b/packages/scratch-gui/test/fixtures/ja-notation/golden/ja.json index edb20b4f77..d23a017d24 100644 --- a/packages/scratch-gui/test/fixtures/ja-notation/golden/ja.json +++ b/packages/scratch-gui/test/fixtures/ja-notation/golden/ja.json @@ -332,7 +332,7 @@ } }, "ja-906fd1a488": { - "ruby": "@x〆 = 1\n@𠮷田 = @x〆 + 2\n@x1 = (@𠮷田 / 2).to_i\nconsole.puts(@x1)", + "ruby": "@x〆 = 1\n@𠮷田 = @x〆 + 2\n@x1 = (@𠮷田 / 2).to_i\nconsole.puts(@x1)", "errors": [], "rubyLines": [ 1, @@ -341,10 +341,10 @@ 4 ], "converterErrors": [], - "blocks": "data_setvariableto(VARIABLE = @x〆, VALUE: \"1\")\ndata_setvariableto(VARIABLE = @𠮷田, VALUE: operator_add(NUM1: @x〆, NUM2: 2))\ndata_setvariableto(VARIABLE = @x1, VALUE: operator_mathop(OPERATOR = \"floor\", NUM: operator_divide(NUM1: @𠮷田, NUM2: 2)) #\"@ruby:method:to_i\")\nsmalrubyConsole_print(TEXT: @x1)", + "blocks": "data_setvariableto(VARIABLE = @x〆, VALUE: \"1\")\ndata_setvariableto(VARIABLE = @𠮷田, VALUE: operator_add(NUM1: @x〆, NUM2: 2))\ndata_setvariableto(VARIABLE = @x1, VALUE: operator_mathop(OPERATOR = \"floor\", NUM: operator_divide(NUM1: @𠮷田, NUM2: 2)) #\"@ruby:method:to_i\")\nsmalrubyConsole_print(TEXT: @x1)", "shown": { - "ruby": "@x〆 = 1\n@𠮷田 = @x〆 + 2\n@x1 = (@𠮷田 / 2).to_i\nconsole.puts(@x1)", - "ja": "x〆 = 1\n𠮷田 = x〆 + 2\nx1 = 𠮷田 ÷ 2\n表示する(x1)", + "ruby": "@x〆 = 1\n@𠮷田 = @x〆 + 2\n@x1 = (@𠮷田 / 2).to_i\nconsole.puts(@x1)", + "ja": "x〆 = 1\n𠮷田 = x〆 + 2\nx1 = 𠮷田 ÷ 2\n表示する(x1)", "errors": [] } }, diff --git a/packages/scratch-gui/test/unit/lib/dncl/dncl-number-notation.test.js b/packages/scratch-gui/test/unit/lib/dncl/dncl-number-notation.test.js index b48ba62ed3..5d773e5b73 100644 --- a/packages/scratch-gui/test/unit/lib/dncl/dncl-number-notation.test.js +++ b/packages/scratch-gui/test/unit/lib/dncl/dncl-number-notation.test.js @@ -170,8 +170,13 @@ describe('DNCL → Ruby: full-width digits and a name right after a number (issu else expect(result.ruby).not.toMatch(/[0-9]/); }); - test('full-width digits in a name stay in the name', () => { - expect(dnclToRuby('x1 = 1').ruby).toBe('@x1 = 1'); + // The full-width letters and digits are made half-width, in a name too (W8 of the EPIC #1731). + test('full-width letters and digits in a name are read as the half-width ones', () => { + expect(dnclToRuby('x1 = 1\nx1 = x1 + 1').ruby).toBe('@x1 = 1\n@x1 = @x1 + 1'); + }); + + test('full-width letters and digits in a string and a comment are kept', () => { + expect(dnclToRuby('表示する("x1") # x1 を表示する').ruby).toBe('console.puts("x1") # x1 を表示する'); }); test.each([ From 7f0a57b1a8b971581d9f710e0a58daf4e768dc20 Mon Sep 17 00:00:00 2001 From: "smalruby3-editor-bot[bot]" <297607354+smalruby3-editor-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:03:53 +0000 Subject: [PATCH 3/5] fix(ja-notation): tell a closing word of another kind of block MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A block of the DNCL-like form closed by the closing word of another kind (a もし closed by を繰り返す, a counting loop by を実行する) is now an error (`closer-kind`) that says the word of the block, even when the Ruby could be made: the students are told as much as can be. A block forgotten inside the one the word closes is told as not closed. `end` still closes any. Closes #2268 Co-Authored-By: Claude Opus 5.5 --- docs/dncl/README.md | 14 ++- docs/smalruby-dncl-spec.ja.md | 2 + packages/ja-notation/src/parse.js | 76 +++++++++++-- .../ja-notation/test/data/ja-to-ruby.json | 18 ++- packages/ja-notation/test/data/parse.json | 106 ++++++++++++++++++ .../src/lib/dncl/ja-notation-errors.js | 13 ++- .../test/unit/lib/dncl/dncl-validator.test.js | 36 +++++- 7 files changed, 240 insertions(+), 25 deletions(-) diff --git a/docs/dncl/README.md b/docs/dncl/README.md index 49a133ea51..367b7e7a5d 100644 --- a/docs/dncl/README.md +++ b/docs/dncl/README.md @@ -139,8 +139,9 @@ JaAST では 1 つの形にする。エディタの日本語 → Ruby(`dnclToR DNCL 風の形の読み方(切りかえる前の変換に合わせたもの): - `:` の無い開く行(`もし … ならば`、`… の間`、`… ずつ増やしながら`、`関数 名前(引数)`、`名前(引数) を定義する`)のブロックは、閉じる行 - (`を実行する` / `を繰り返す` / `と定義する`。`end` も)か `⎿` で終わる。中の字下げは見ない。閉じる言葉とブロックの種類は照らし合わせない(前と同じ)。 - ただし数える繰り返しは、どの言葉で閉じても増分を足す(前は `を繰り返す` で閉じたときだけ足したので、`を実行する` で閉じると終わらなかった)。 + (`を実行する` / `を繰り返す` / `と定義する`。`end` も)か `⎿` で終わる。中の字下げは見ない。閉じる言葉はブロックの種類に合わせる(`もし` は `を実行する`、`〜の間` と数える繰り返しは `を繰り返す`、関数は `と定義する`)。 + 合わない言葉で閉じると、初心者に少しでも多く指摘するため誤りにする(下の「閉じ忘れのエラー」)。`end` は Ruby と同じく、どのブロックも閉じる。 + 標準の形(字下げ)では閉じる言葉を書かないので関係しない。 - `:` のある行のブロックは字下げで終わる。同じ字下げの閉じる行はそのブロックを閉じる。`:` があっても次の行が深くないときは、閉じる行で終わるブロックになる。2 つの形は混ぜてよい。 - `←` は `=`、`かつ` / `または` は `and` / `or`、後ろに付く `でない` は、前の `かつ` / `または`・`(`・`,`・`=` までをまとめて否定する(`a > 10 でない` は `not (a > 10)`)。 `でない` の後に演算子が続くときは、否定したものがその左側になる(`a でない == b` は Ruby の `!a == b`)。 @@ -166,7 +167,7 @@ DNCL 風の形の読み方(切りかえる前の変換に合わせたもの) Ruby → 日本語は Ruby の名前をそのまま書く(`@x` → `x`)ので、日本語から Ruby に戻すと `@x` になる。 - `☆` `①` `😀` のような記号は名前に使えず、「「☆」が読めません」の誤りになる(BMP の外の文字も 1 文字として示す)。 -誤りは `{code, message, line, column}` に、日本語モードの文言を作るための `name`(字句)・`opener` / `direction` / `colon` / `word`(ブロック)・`block`(`stray-closer` / `closer-indent` / `stray-branch`)を添えて返す。 +誤りは `{code, message, line, column}` に、日本語モードの文言を作るための `name`(字句)・`opener` / `direction` / `colon` / `word`(ブロック)・`block`(`stray-closer` / `closer-indent` / `closer-kind` / `stray-branch`)・`expected`(`closer-kind` のブロックの閉じのことば)を添えて返す。 テスト: ライブラリだけのもの(表なし・ほかの処理系の表)は `packages/ja-notation/test/`(データは `test/data/*.json`。`node --test`)。スモウルビーの表を通したものは scratch-gui の `test/unit/lib/ja-notation/corpus.test.js`(コーパスのゴールデンとの比較)と `build-and-write-ruby.test.js`。 @@ -256,11 +257,12 @@ DNCL モードでは、DNCL を Ruby に変換してからブロックに変換 | DNCL 風の形の `もし〜ならば` / `〜の間` / `〜ずつ増やしながら` / `〜ずつ減らしながら` / `関数` / `〜 do` を閉じていない | 開いた行に「「もし〜ならば」を「を実行する」で閉じてください」など | | 閉じるブロックが無いのに `を実行する` などがある | 「「を実行する」で閉じるものがありません」 | | `もし` の外の `そうでなければ` / `そうでなくもし` | 「「そうでなければ」の前に「もし〜ならば」がありません」。標準の形(行の終わりが `:`)では、`もし` より浅く字下げしたときにこうなるので「「そうでなければ:」は、「もし〜ならば:」と同じ字下げで書いてください」 | -| 種類の違う閉じのことば(ほかに合うブロックが無い) | 閉じのことばの行に「「もし〜ならば」は「を繰り返す」ではなく「を実行する」で閉じてください」 | +| 種類の違う閉じのことば(`もし … を繰り返す`・数える繰り返しを `を実行する` で閉じるなど) | 閉じのことばの行に「「もし〜ならば」は「を繰り返す」ではなく「を実行する」で閉じてください」。`:` で開いたブロックを同じ字下げの閉じの行で閉じたときは「「〜の間繰り返す:」は…」(ja-notation の `closer-kind`) | - 標準の形か DNCL 風の形かは、開いた行の終わりに `:` / `:` があるか(行末のコメントを除く)で決める(ja-notation の誤りの `colon`)。標準の形は字下げでブロックを示すので、閉じのことばを書くようには言わない。 -- ja-notation は閉じのことばの種類を見ずに、いちばん内側のブロックを閉じる(Ruby の `end` と同じ)。そのため、種類の違う閉じのことばでも数が合えばエラーにしない(`もし … を繰り返す` など)。 -- 数が合わずエラーになったときで、ブロックがすべて DNCL 風の形のときは、閉じのことばの種類を見て言う(`ja-notation-errors.js` の `closerFormBlockErrors`)。内側のブロックを閉じ忘れて外側の閉じのことばが来たとき(`〜の間` の中の `もし` を閉じ忘れて `を繰り返す`)は、外側ではなく**閉じ忘れた内側**の行に付ける。 +- ja-notation は閉じのことばとブロックの種類を照らし合わせ、合わなければ誤りにする(`closer-kind`。数が合っていて Ruby が作れるときも)。`end` はどのブロックも閉じる(Ruby と同じ)。 +- 内側のブロックを閉じ忘れて外側の閉じのことばが来たとき(`〜の間` の中の `もし` を閉じ忘れて `を繰り返す`)は、外側ではなく**閉じ忘れた内側**の行に付ける(ja-notation の `unclosed`。間のブロックがすべて DNCL 風の形のとき)。 + ブロックがすべて DNCL 風の形のときは、エディタも閉じのことばの種類を見て同じことを言う(`ja-notation-errors.js` の `closerFormBlockErrors`)。 - `with_screen_refresh do` / `loop do` / `when_flag_clicked do` / `list.each do |x|` など、日本語に書きかえるものが無い `xxx do`(`|x|` 付きも)は Ruby → 日本語で書いてあるとおりの Ruby のまま(`end` も)残す(`N.times do` と `(a..b).step(s) do |i|` は `〜ずつ増やしながら` に、`while x do` / `until x do` は `〜の間` になる)。構文木で読むので、外側のブロックの閉じ方は変わらない。日本語の中にそうした行があるときの判定は `dncl-validator.js` の `isDoBlockLine`(行末のコメントを除いてから行末の `do` だけを見るので、文字列やコメントの中の `do` は数えない)。日本語モードにはこうした命令が無いので、ほかの対応していない命令と同じくその行に「「with_screen_refresh」は日本語モードでは書けない命令です。…」を出し、Ruby には変換しない(下の「日本語モードに無い命令」)。 - `dnclToRuby` はこのエラーを `errors`(日本語の行)として返し、Ruby は作らない。エディタは Ruby を送らず、エラーの印(`ruby-tab.jsx` の日本語の誤りのマーカー。owner は `DNCL_UNSUPPORTED_OWNER`)をその行に出し、前の変換の印(`smalruby`)は消す。生成AI に相談の確かめ(`genai-dncl-answer.js`)も、この誤りを問題として返す。 diff --git a/docs/smalruby-dncl-spec.ja.md b/docs/smalruby-dncl-spec.ja.md index 2ac128d547..91b323968b 100644 --- a/docs/smalruby-dncl-spec.ja.md +++ b/docs/smalruby-dncl-spec.ja.md @@ -382,6 +382,8 @@ DNCL 風の形の終端キーワードも読みます(読み込みだけ)。 | `を繰り返す` | `の間`(while ループ)、`ずつ増やしながら/減らしながら`(for ループ) | | `と定義する` | `関数〜`(関数定義) | +ブロックの種類に合わない終端キーワードで閉じると誤りです(`もし〜ならば` を `を繰り返す` で閉じるなど。「「もし〜ならば」は「を繰り返す」ではなく「を実行する」で閉じてください」)。`end` はどのブロックも閉じます。 + ## 7. 関数 ### 関数定義 diff --git a/packages/ja-notation/src/parse.js b/packages/ja-notation/src/parse.js index 5c80d80fc2..bcdafda193 100644 --- a/packages/ja-notation/src/parse.js +++ b/packages/ja-notation/src/parse.js @@ -97,7 +97,8 @@ const STOP_NAMES = new Set([ * @param {object} [detail] - What a caller may need to say the error in its own * words: `name` (the token), `opener` / `direction` / `colon` / `word` (the * block of a block error), `block` (`stray-closer`, `closer-indent`, - * `stray-branch`) and `branch`. + * `closer-kind`, `stray-branch`), `expected` (the closing word of the block + * of a `closer-kind`) and `branch`. * @returns {object} The error. */ const makeError = (code, message, line, column = 0, detail = {}) => ({ code, message, line, column, ...detail }); @@ -914,6 +915,33 @@ const tokenError = (tokens) => { return null; }; +/** + * The closing word of a block in the DNCL-like form. + * @param {object} node - The block (`If`, `While`, `For`, `FunctionDef`). + * @returns {string} `を実行する`, `を繰り返す` or `と定義する`. + */ +const closerOf = (node) => { + if (node.type === 'If') return 'を実行する'; + if (node.type === 'FunctionDef') return 'と定義する'; + return 'を繰り返す'; +}; + +/** + * Where in the open blocks is the nearest one a closing word closes, when only + * blocks closed by a line of their own are inside it (so the word closes it and + * the blocks inside it were forgotten), or -1. + * @param {Array} stack - The open blocks (the innermost last). + * @param {string} word - The closing word. + * @returns {number} The index in the stack, or -1. + */ +const matchingCloser = (stack, word) => { + for (let i = stack.length - 1; i >= 0; i--) { + if (stack[i].mode !== 'closer') return -1; + if (closerOf(stack[i].node) === word) return i; + } + return -1; +}; + /** * Read the Japanese (the standard form, the DNCL-like form or both mixed) * into a JaAST. @@ -947,6 +975,16 @@ const parse = (source) => { ...(entry.node.type === 'For' ? { direction: entry.node.direction } : {}), colon: entry.colon, }); + // A block closed by a line of its own that was not closed. + const unclosed = (entry) => { + const word = closerOf(entry.node); + errors.push( + makeError('unclosed', `「${word}」で閉じていません`, entry.node.line, entry.node.column, { + ...openerOf(entry), + word, + }), + ); + }; const emptyBlock = (entry) => errors.push( makeError( @@ -1021,6 +1059,33 @@ const parse = (source) => { ); return; } + // The closing word must be the one of the block (Issue #1731, W3): a + // `もし` closed by `を繰り返す` is told. `end` closes any block, as in Ruby. + if (block.word !== END_WORD && block.word !== closerOf(top.node)) { + // A block forgotten to be closed inside the one the word closes (a + // `もし` in a loop closed by `を繰り返す`) is told as not closed. + const index = matchingCloser(stack, block.word); + if (index < 0) { + stack.pop(); + const expected = closerOf(top.node); + errors.push( + makeError( + 'syntax', + `「${block.word}」ではなく「${expected}」で閉じてください`, + entry.line, + column, + { ...openerOf(top), block: 'closer-kind', word: block.word, expected }, + ), + ); + return; + } + while (stack.length > index + 1) unclosed(stack.pop()); + const found = stack.pop(); + close(found, entry.line, entry.line); + found.node.closeOwnLine = true; + lastCodeLine = entry.line; + return; + } stack.pop(); close(top, entry.line, entry.line); top.node.closeOwnLine = true; @@ -1081,14 +1146,7 @@ const parse = (source) => { } else if (top.mode === 'indent') { emptyBlock(top); } else { - const word = - top.node.type === 'If' ? 'を実行する' : top.node.type === 'FunctionDef' ? 'と定義する' : 'を繰り返す'; - errors.push( - makeError('unclosed', `「${word}」で閉じていません`, top.node.line, top.node.column, { - ...openerOf(top), - word, - }), - ); + unclosed(top); } } return errors.length > 0 ? { program: null, errors } : { program, errors }; diff --git a/packages/ja-notation/test/data/ja-to-ruby.json b/packages/ja-notation/test/data/ja-to-ruby.json index f5cd4138b2..55e2b71a85 100644 --- a/packages/ja-notation/test/data/ja-to-ruby.json +++ b/packages/ja-notation/test/data/ja-to-ruby.json @@ -79,11 +79,23 @@ "jaLines": [1, 1, 2, 3, 3] }, { - "title": "a counting loop closed by another closing word adds the step too", + "title": "a counting loop closed by another closing word is an error that says its closing word (W3 of Issue #1731)", "table": "plain", "ja": "i を 1 から 3 まで 1 ずつ増やしながら\n 表示する(i)\nを実行する", - "ruby": "i = 1\nwhile i <= 3\n puts(i)\n i += 1\nend", - "jaLines": [1, 1, 2, 3, 3] + "errors": [ + { + "code": "syntax", + "message": "「を実行する」ではなく「を繰り返す」で閉じてください", + "line": 3, + "column": 0, + "opener": "For", + "direction": "up", + "colon": false, + "block": "closer-kind", + "word": "を実行する", + "expected": "を繰り返す" + } + ] }, { "title": "the names and functions are what the table says", diff --git a/packages/ja-notation/test/data/parse.json b/packages/ja-notation/test/data/parse.json index 7b7d595a4e..1f0f17ae56 100644 --- a/packages/ja-notation/test/data/parse.json +++ b/packages/ja-notation/test/data/parse.json @@ -1292,6 +1292,11 @@ "ja": "もし a > 0 ならば\n b = 1\nend", "as": "もし a > 0 ならば:\n b = 1" }, + { + "title": "`end` closes any kind of block opened without `:` (as in Ruby; the closing words must be of their block)", + "ja": "x > 0 の間\n x = x - 1\nend", + "as": "x > 0 の間繰り返す:\n x = x - 1" + }, { "title": "`を追加する` with no spaces around the value in brackets", "ja": "A に (3) を追加する", @@ -1341,6 +1346,107 @@ } ] }, + { + "title": "a closing word of another kind of block is an error on the closing line (W3 of Issue #1731)", + "ja": "もし a > 0 ならば\n b = 1\nを繰り返す", + "errors": [ + { + "code": "syntax", + "message": "「を繰り返す」ではなく「を実行する」で閉じてください", + "line": 3, + "column": 0, + "opener": "If", + "colon": false, + "block": "closer-kind", + "word": "を繰り返す", + "expected": "を実行する" + } + ] + }, + { + "title": "a loop closed by を実行する is an error", + "ja": "a > 0 の間\n a = a - 1\nを実行する", + "errors": [ + { + "code": "syntax", + "message": "「を実行する」ではなく「を繰り返す」で閉じてください", + "line": 3, + "column": 0, + "opener": "While", + "colon": false, + "block": "closer-kind", + "word": "を実行する", + "expected": "を繰り返す" + } + ] + }, + { + "title": "a counting loop down closed by と定義する is an error", + "ja": "i を 3 から 1 まで 1 ずつ減らしながら\n b = i\nと定義する", + "errors": [ + { + "code": "syntax", + "message": "「と定義する」ではなく「を繰り返す」で閉じてください", + "line": 3, + "column": 0, + "opener": "For", + "direction": "down", + "colon": false, + "block": "closer-kind", + "word": "と定義する", + "expected": "を繰り返す" + } + ] + }, + { + "title": "a function closed by を繰り返す is an error", + "ja": "関数 f(a)\n 返す a\nを繰り返す", + "errors": [ + { + "code": "syntax", + "message": "「を繰り返す」ではなく「と定義する」で閉じてください", + "line": 3, + "column": 0, + "opener": "FunctionDef", + "colon": false, + "block": "closer-kind", + "word": "を繰り返す", + "expected": "と定義する" + } + ] + }, + { + "title": "a block opened with : closed by a line of another kind at its indent is an error", + "ja": "もし a > 0 ならば:\n b = 1\nを繰り返す", + "errors": [ + { + "code": "syntax", + "message": "「を繰り返す」ではなく「を実行する」で閉じてください", + "line": 3, + "column": 0, + "opener": "If", + "colon": true, + "block": "closer-kind", + "word": "を繰り返す", + "expected": "を実行する" + } + ] + }, + { + "title": "a block forgotten to be closed inside the one the closing word closes is told as not closed", + "ja": "i を 1 から 3 まで 1 ずつ増やしながら\n もし i > 1 ならば\n x = 1\nを繰り返す", + "errors": [ + { + "code": "unclosed", + "message": "「を実行する」で閉じていません", + "line": 2, + "column": 2, + "opener": "If", + "colon": false, + "word": "を実行する" + } + ] + }, { "title": "もし not closed", "ja": "もし a > 0 ならば\n b = 1", diff --git a/packages/scratch-gui/src/lib/dncl/ja-notation-errors.js b/packages/scratch-gui/src/lib/dncl/ja-notation-errors.js index 82d9ada28c..847c229b5e 100644 --- a/packages/scratch-gui/src/lib/dncl/ja-notation-errors.js +++ b/packages/scratch-gui/src/lib/dncl/ja-notation-errors.js @@ -51,6 +51,12 @@ const blockMessage = (error) => { ? `${names.standard}の中の行を字下げしてください` : `${names.name}を「${names.closer}」で閉じてください`; } + if (error.block === 'closer-kind') { + // A closer of another kind of block (W3 of #1731). + const names = BLOCK_NAMES[error.opener === 'For' ? error.direction : error.opener]; + if (!names) return null; + return `${error.colon ? names.standard : names.name}は「${error.word}」ではなく「${names.closer}」で閉じてください`; + } if (error.block === 'stray-closer') return `「${error.word}」で閉じるものがありません`; if (error.block === 'stray-branch') { const name = BRANCH_NAMES[error.branch]; @@ -167,10 +173,9 @@ const openerOf = (code) => { * block closed by a line of its own), found by the kind of each closing line * (Issue #1419): a closing line closes the nearest open block it is the * closer of, and the blocks left open inside it are told, so a student who - * forgot one `を実行する` is told about that `もし`. ja-notation closes the - * innermost block with any closing line, as Ruby closes it with any `end`, - * so a program that reads that way has no error, and this is used only to - * say the errors of one that does not. + * forgot one `を実行する` is told about that `もし`. ja-notation tells the same + * (a closing line of another kind of block, W3 of #1731), and this is used + * only to say the errors of a program it tells, in the words of the blocks. * @param {Array} lines - The lines (line numbers and marks blanked out). * @returns {?Array} The errors, or null when a block of the program * is opened with `:` (the standard form, whose errors ja-notation says). diff --git a/packages/scratch-gui/test/unit/lib/dncl/dncl-validator.test.js b/packages/scratch-gui/test/unit/lib/dncl/dncl-validator.test.js index e389552386..3acc371b6f 100644 --- a/packages/scratch-gui/test/unit/lib/dncl/dncl-validator.test.js +++ b/packages/scratch-gui/test/unit/lib/dncl/dncl-validator.test.js @@ -79,9 +79,39 @@ describe('block errors of the DNCL-like form', () => { ]); }); - test('a wrong closer that still makes good Ruby is not an error', () => { - // The editor takes it (every closer becomes `end`), so it is left alone. - expect(errorsOf(['もし x > 0 ならば', ' 表示する(x)', 'を繰り返す'])).toEqual([]); + // A closer of another kind of block is an error even when the Ruby would be good (W3 of #1731). + test('a wrong closer is reported with the closer of the block', () => { + expect(errorsOf(['もし x > 0 ならば', ' 表示する(x)', 'を繰り返す'])).toEqual([ + { + line: 3, + column: 1, + message: '「もし〜ならば」は「を繰り返す」ではなく「を実行する」で閉じてください', + }, + ]); + }); + + test('a counting loop closed with another closer is reported', () => { + expect(errorsOf(['i を 1 から 3 まで 1 ずつ増やしながら', ' 表示する(i)', 'を実行する'])).toEqual([ + { + line: 3, + column: 1, + message: '「〜ずつ増やしながら」は「を実行する」ではなく「を繰り返す」で閉じてください', + }, + ]); + }); + + test('a block opened with : closed by a line of another kind names the standard form', () => { + expect(errorsOf(['x < 3 の間繰り返す:', ' x = x + 1', 'と定義する'])).toEqual([ + { + line: 3, + column: 1, + message: '「〜の間繰り返す:」は「と定義する」ではなく「を繰り返す」で閉じてください', + }, + ]); + }); + + test('end still closes any kind of block', () => { + expect(errorsOf(['x < 3 の間', ' x ← x + 1', 'end'])).toEqual([]); }); test('そうでなければ inside a loop of an if left open names the if', () => { From d3f2acf019cbed6eb97b3f6e15de029ab741c029 Mon Sep 17 00:00:00 2001 From: "smalruby3-editor-bot[bot]" <297607354+smalruby3-editor-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:14:59 +0000 Subject: [PATCH 4/5] test(ja-notation): a counting loop closed by another closing word is an error Co-Authored-By: Claude Opus 5.5 --- .../unit/lib/ja-notation/build-and-write-ruby.test.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/scratch-gui/test/unit/lib/ja-notation/build-and-write-ruby.test.js b/packages/scratch-gui/test/unit/lib/ja-notation/build-and-write-ruby.test.js index ffb6ff1d4d..2b9fff3b1a 100644 --- a/packages/scratch-gui/test/unit/lib/ja-notation/build-and-write-ruby.test.js +++ b/packages/scratch-gui/test/unit/lib/ja-notation/build-and-write-ruby.test.js @@ -63,10 +63,11 @@ describe('jaToRuby with the table of Smalruby', () => { // The current conversion adds the step only at `を繰り返す`, so a counting // loop closed by `を実行する` never ends there; here every closing line adds it. - test('a counting loop closed by another closing word adds the step too', () => { - expect(smalruby('i を 1 から 3 まで 1 ずつ増やしながら\n 表示する(i)\nを実行する').ruby).toBe( - '@i = 1\nwhile @i <= 3\n console.puts(@i)\n @i += 1\nend', - ); + // The closing word must be the one of the block (W3 of the EPIC #1731). + test('a counting loop closed by another closing word is an error', () => { + const result = smalruby('i を 1 から 3 まで 1 ずつ増やしながら\n 表示する(i)\nを実行する'); + expect(result.ruby).toBeNull(); + expect(result.errors).toMatchObject([{ block: 'closer-kind', line: 3, expected: 'を繰り返す' }]); }); test.each([ From 5d4cf3e65fa5b81a947229a09c3d4dd4a422c204 Mon Sep 17 00:00:00 2001 From: "smalruby3-editor-bot[bot]" <297607354+smalruby3-editor-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:16:00 +0000 Subject: [PATCH 5/5] style(locales): format the message of the stage variables Co-Authored-By: Claude Opus 5.5 --- packages/scratch-gui/src/locales/ja.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/scratch-gui/src/locales/ja.js b/packages/scratch-gui/src/locales/ja.js index d4f59329f0..66a1c0bd88 100644 --- a/packages/scratch-gui/src/locales/ja.js +++ b/packages/scratch-gui/src/locales/ja.js @@ -1907,7 +1907,8 @@ export default { 'gui.rubyTab.dnclForbiddenPrefixError': '日本語モードでは変数に「{name}」は使えません', 'gui.rubyTab.dnclPostTestLoopError': '後判定の繰り返し(先に 1 回動かしてから条件を確かめる繰り返し)は日本語では書けません。最初の 1 回をループの前に書いてから、「〜の間繰り返す」にしてください。Ruby モードでは書けます。', - 'gui.rubyTab.dnclStageVariableError': 'ステージの変数({name})は日本語モードでは書けません。Ruby モードでは書けます。', + 'gui.rubyTab.dnclStageVariableError': + 'ステージの変数({name})は日本語モードでは書けません。Ruby モードでは書けます。', 'gui.rubyTab.dnclUndefinedFunctionError': '「{name}」は定義されていない関数です。「関数 {name}(…):」で定義してください。', 'gui.rubyTab.dnclUnsupportedCommandError':