From de29a13d625ba134a8240e1613757438a25b0d36 Mon Sep 17 00:00:00 2001 From: "smalruby3-editor-bot[bot]" <297607354+smalruby3-editor-bot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:26:26 +0000 Subject: [PATCH] fix(ruby): keep warp and digit-leading names of custom blocks in ruby MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "Run without screen refresh" of a custom block is written `without_screen_refresh def foo ... end`. The parse stage unwraps the call to the def and remembers it, so my-blocks.js sets warp "true"; before, Ruby dropped it and converting back turned it off. A custom block name that starts with a digit or is a reserved word gets `_` in front (`1 文字えらぶ` -> `def _1_文字えらぶ`; one digit gets `__`, as `_1`..`_9` are numbered parameters), and the converter takes it off again (ruby-method-name.js). The @ruby:return markers are read with [^:,\s]+ instead of \w+, which missed Japanese method names. The smalruby3 gem gets a no-op `without_screen_refresh` class method. Closes #2114 Closes #2116 Co-Authored-By: Claude Opus 5.5 --- docs/ruby-editor/bridging-patterns.md | 27 ++ docs/smalruby-language-spec.ja.md | 12 + docs/smalruby-language-spec.md | 12 + packages/scratch-gui/.prettierignore | 1 + .../src/lib/ruby-generator/class-wrapper.js | 2 +- .../src/lib/ruby-generator/control.js | 2 +- .../src/lib/ruby-generator/data.js | 4 +- .../src/lib/ruby-generator/procedure.js | 27 +- .../scratch-gui/src/lib/ruby-method-name.js | 118 +++++++ .../ruby-to-blocks-converter/context-utils.js | 2 + .../module-visitor.js | 2 + .../lib/ruby-to-blocks-converter/my-blocks.js | 12 +- .../ruby-to-blocks-converter/parse-stage.js | 3 + .../return-value-temps.js | 3 +- .../screen-refresh-defs.js | 52 +++ .../variable-utils.js | 9 +- .../my-block-warp-and-name.test.js | 318 ++++++++++++++++++ ruby/smalruby3/lib/smalruby3/dsl.rb | 14 + ruby/smalruby3/test/dsl_test.rb | 15 + 19 files changed, 613 insertions(+), 22 deletions(-) create mode 100644 packages/scratch-gui/src/lib/ruby-method-name.js create mode 100644 packages/scratch-gui/src/lib/ruby-to-blocks-converter/screen-refresh-defs.js create mode 100644 packages/scratch-gui/test/unit/lib/ruby-roundtrip/my-block-warp-and-name.test.js diff --git a/docs/ruby-editor/bridging-patterns.md b/docs/ruby-editor/bridging-patterns.md index 597bd410374..866e7eb2290 100644 --- a/docs/ruby-editor/bridging-patterns.md +++ b/docs/ruby-editor/bridging-patterns.md @@ -96,6 +96,7 @@ Scratch の変数・リストの名前で、Ruby の情報を持たせている | `_symbols_`(ステージ) | 使われたシンボル | ステージのリスト | `variable-utils.js` の `_symbolToBlock` | | `__lit_<番号>__1_` | 何もしないリテラルだけの行(`"Jimmy"`) | スプライトの変数・リスト | `finish.js` の `_convertBareLiteralToAssignment` | | `_super_<メソッド>_<番号>_` | `super` で呼ばれる、module 側の同じ名前のメソッド | 定義ブロック(手続き名) | `class-visitor.js` | +| `_<名前>`(`_1_文字えらぶ`・`_end`。1 けたの数字は `__1`) | 数字で始まる名前・予約語の名前の定義ブロック(「1 文字えらぶ」「end」) | 定義ブロック(Ruby のメソッド名だけ。ブロックの名前には `_` を付けない) | `src/lib/ruby-method-name.js`(P20) | 生成器だけが使う、出力の途中の目印もある(Ruby には残らない)。 @@ -739,6 +740,32 @@ say(mesh.message_value) **テスト**: `ruby-to-blocks-converter/mesh_v2.test.js`、`ruby-roundtrip/extension_mesh.test.js`、`furigana-annotator.test.js`。 +### P20. 定義ブロックの名前と「画面を再描画せずに実行する」 + +**Ruby で書きたいこと**: 定義ブロック(ブロックを作る)の名前と設定を、Ruby の `def` で書く。名前が数字で始まる・予約語のものもある。 + +**Scratch での表し方**: 定義ブロック(`procedures_definition` と `procedures_prototype`)。名前は `proccode` の言葉、「画面を再描画せずに実行する」は `procedures_prototype` の `mutation.warp`(`"true"` / `"false"`。読みこんだ作品では真偽値のこともある)。 + +- **名前**: 生成器は `proccode` の言葉(`%s` / `%b` を除く)を `_` でつないでメソッド名にする(`'1 文字えらぶ %s'` → `1_文字えらぶ`)。名前が数字で始まるか予約語のときは前に `_` を付け、1 けたの数字(`_1`〜`_9` は番号指定パラメータ)には `__` を付ける。もとから `_` で始まる同じ形の名前には、もう 1 つ付ける(`_1x` → `__1x`)。変換器は逆に付けた分を取る。この対応は `src/lib/ruby-method-name.js` の 1 か所(`rubyMethodNameOfProccode` / `blockNameOfRubyMethodName`)にあり、生成器 `procedure.js` と、変換器が `proccode` からメソッド名を求める所(`variable-utils.js` の `_isProcedureCallWithReturnValue`・`my-blocks.js`・`return-value-temps.js` の `_procedureNameOfCall`)が使う。変換器の手続きの表(`_context.procedures`)と `_return_<メソッド>_`・`@ruby:return:<メソッド>` は Ruby のメソッド名(`_1_文字えらぶ`)のまま。 +- **注釈の名前**: `@ruby:return:<メソッド>` のメソッド名は日本語のこともあるので、生成器は `\w+` ではなく `[^:,\s]+` で読む(`\w` は日本語に当たらず、`return` のある日本語の名前のメソッドで、初期化と控えのブロックが Ruby に出ていた)。 +- **画面を再描画せずに実行する**: 生成器は `without_screen_refresh def foo ... end` と書く(Ruby の `private def foo` と同じ形。`def` はメソッド名のシンボルを返すので、Ruby として正しい)。変換器は解析の段(`parse-stage.js`)で、この呼び出しを中の `def` に置きかえ(`screen-refresh-defs.js` の `unwrapWithoutScreenRefreshDefs`)、`def` を `_context.warpDefNodes` に覚える。分析・class / module・コメント・ブロックの中の `def` の検査は、ふつうの `def` として見る。`my-blocks.js` が `warp` を `"true"` にする(呼び出しのブロックの `mutation.warp` も同じにする)。module のメソッド(ほかのスプライトの module を読むときも)も同じ。注釈は使わない(Ruby だけで書く人も書けるように、Ruby の形で表す)。smalruby3 gem では `without_screen_refresh` は名前を返すだけのクラスメソッドで、メソッドはふつうに動く。 + +**往復の例**: + +```ruby +without_screen_refresh def _1_文字えらぶ(n) + say(n) +end + +_1_文字えらぶ(1) +``` + +- 定義ブロック「1_文字えらぶ (n)」(画面を再描画せずに実行する)と、その呼び出しになり、同じコードに戻る。 + +**できないこと**: 名前の中の空白は `_` になり、ブロックに戻しても `_` のまま(「1 文字えらぶ」は「1_文字えらぶ」になる)。`-` などメソッド名に使えない記号の入った名前は、そのまま書くので Ruby の文法エラーになる。自分で `def without_screen_refresh` を定義したコードでは、`without_screen_refresh def foo` をその呼び出しとして読む(置きかえない)。日本語モードは `without_screen_refresh def` を読めない。 + +**テスト**: `ruby-roundtrip/my-block-warp-and-name.test.js`、`ruby-roundtrip/my_blocks.test.js`。 + ## 注釈 `@ruby:*` の一覧(仕様) 「書く」はその注釈を作るところ、「読む」は使うところ。変換器・生成器は `packages/scratch-gui/src/lib/` の `ruby-to-blocks-converter/` と `ruby-generator/` のこと。 diff --git a/docs/smalruby-language-spec.ja.md b/docs/smalruby-language-spec.ja.md index ef7e528ab61..df4ecf71b47 100644 --- a/docs/smalruby-language-spec.ja.md +++ b/docs/smalruby-language-spec.ja.md @@ -435,6 +435,18 @@ greet("こんにちは") - メソッドのオーバーロードはできません - 再帰呼び出しはできません +**画面を再描画せずに実行する**: 定義ブロックの「画面を再描画せずに実行する」は、`def` の前に `without_screen_refresh` を書きます(`private def foo` と同じ形)。`def` の前に書かなければ、ふつうの定義ブロック(画面を再描画する)になります。 + +```ruby +without_screen_refresh def 学習する(n) + n.times do + @見る長さ += 1 + end +end +``` + +**メソッドにできない名前の定義ブロック**: 数字で始まる名前(「1 文字えらぶ」)や Ruby の予約語(`end`・`if` など)の名前は、Ruby では前に `_` を付けて書きます(`def _1_文字えらぶ` / 呼び出しも `_1_文字えらぶ`)。ブロックに戻すと `_` は取れます(「1_文字えらぶ」)。`_1` から `_9` は Ruby のブロックの番号指定パラメータで名前にできないので、1 けたの数字だけの名前は `__` を付けます(「1」は `__1`)。もとから `_` で始まる同じ形の名前(「_1x」「_end」)は、もう 1 つ `_` を付けます(`__1x`・`__end`)。名前の中の空白は `_` になります(ブロックに戻しても `_` のまま)。 + ### 戻り値 ```ruby diff --git a/docs/smalruby-language-spec.md b/docs/smalruby-language-spec.md index d3b84d64e5c..6e5634a4328 100644 --- a/docs/smalruby-language-spec.md +++ b/docs/smalruby-language-spec.md @@ -406,6 +406,18 @@ greet("hello") - Method overloading is not supported - Recursion is not supported +**Run without screen refresh**: "Run without screen refresh" of a custom block is written `without_screen_refresh` before `def` (the same form as `private def foo`). Without it, the custom block refreshes the screen as usual. + +```ruby +without_screen_refresh def learn(n) + n.times do + @length += 1 + end +end +``` + +**Custom block names that cannot be method names**: a name that starts with a digit ("1 pick letter") or is a reserved word of Ruby (`end`, `if`, ...) gets `_` in front in Ruby (`def _1_pick_letter`, called as `_1_pick_letter`). Back in the blocks the `_` is taken off ("1_pick_letter"). `_1` to `_9` are the numbered parameters of Ruby blocks, so a name that is one digit gets `__` ("1" is `__1`). A name of the same form that already starts with `_` ("_1x", "_end") gets one more `_` (`__1x`, `__end`). A space in a name becomes `_` (it stays `_` in the blocks). + ### Return Values ```ruby diff --git a/packages/scratch-gui/.prettierignore b/packages/scratch-gui/.prettierignore index cb0430d2824..35b6b27aca0 100644 --- a/packages/scratch-gui/.prettierignore +++ b/packages/scratch-gui/.prettierignore @@ -246,6 +246,7 @@ src/lib/* !src/lib/lessons/** !src/lib/lesson-dynamic-categories.js !src/lib/ruby-markers.js +!src/lib/ruby-method-name.js !src/lib/dncl/** !src/lib/ruby-to-blocks-converter/ !src/lib/ruby-to-blocks-converter/** diff --git a/packages/scratch-gui/src/lib/ruby-generator/class-wrapper.js b/packages/scratch-gui/src/lib/ruby-generator/class-wrapper.js index 4f0e9d84f62..3b09e3fabcf 100644 --- a/packages/scratch-gui/src/lib/ruby-generator/class-wrapper.js +++ b/packages/scratch-gui/src/lib/ruby-generator/class-wrapper.js @@ -217,7 +217,7 @@ export default function (Generator) { /^self\.when\(/.test(trimmed) || /^when_/.test(trimmed) || /^\w+\.when[\s_(]/.test(trimmed) || - /^def /.test(trimmed) + /^(?:without_screen_refresh )?def /.test(trimmed) ) { insideSections.push(section); } else { diff --git a/packages/scratch-gui/src/lib/ruby-generator/control.js b/packages/scratch-gui/src/lib/ruby-generator/control.js index aa294b7b264..778e3265723 100644 --- a/packages/scratch-gui/src/lib/ruby-generator/control.js +++ b/packages/scratch-gui/src/lib/ruby-generator/control.js @@ -174,7 +174,7 @@ export default function (Generator) { if (block.opcode === 'procedures_call') { return /^(?:@ruby:super(?::forwarding)?,)?@ruby:return:\S+$/.test(comment); } - if (block.opcode === 'data_setvariableto') return /^@ruby:return:\w+:\d+$/.test(comment); + if (block.opcode === 'data_setvariableto') return /^@ruby:return:[^:,\s]+:\d+$/.test(comment); return false; }; diff --git a/packages/scratch-gui/src/lib/ruby-generator/data.js b/packages/scratch-gui/src/lib/ruby-generator/data.js index 8b7dfd4d753..d9ccc0b652c 100644 --- a/packages/scratch-gui/src/lib/ruby-generator/data.js +++ b/packages/scratch-gui/src/lib/ruby-generator/data.js @@ -92,7 +92,7 @@ export default function (Generator) { // Check if this is a return value assignment if (comment && comment.includes('@ruby:return:')) { // Check if it is an evacuation block (has a number at the end) or initialize block - if (/@ruby:return:\w+:\d+/.test(comment) || /@ruby:return:\w+:initialize/.test(comment)) { + if (/@ruby:return:[^:,\s]+:\d+/.test(comment) || /@ruby:return:[^:,\s]+:initialize/.test(comment)) { return ''; } @@ -132,7 +132,7 @@ export default function (Generator) { // Check if this is the last block in procedure definition if (block._isLastReturnInProcedure) { // Check if there's a cached super call for this method - const returnMethodMatch = comment.match(/@ruby:return:(\w+)/); + const returnMethodMatch = comment.match(/@ruby:return:([^:,\s]+)/); if ( returnMethodMatch && Generator.returnCallCache_ && diff --git a/packages/scratch-gui/src/lib/ruby-generator/procedure.js b/packages/scratch-gui/src/lib/ruby-generator/procedure.js index fbfe98997f9..306c377f855 100644 --- a/packages/scratch-gui/src/lib/ruby-generator/procedure.js +++ b/packages/scratch-gui/src/lib/ruby-generator/procedure.js @@ -1,3 +1,16 @@ +import { rubyMethodNameOfProccode } from '../ruby-method-name'; + +/** + * Whether a custom block runs without screen refresh. A project made in the block editor keeps + * the `warp` of the prototype as a string (`"true"`); a loaded project may keep a boolean. + * @param {object} customBlock - The procedures_prototype block. + * @returns {boolean} true when it runs without screen refresh. + */ +const isWarp = (customBlock) => { + const warp = customBlock && customBlock.mutation && customBlock.mutation.warp; + return warp === true || warp === 'true'; +}; + /** * Define Ruby code generator for Procedures Blocks * @param {RubyGenerator} Generator The RubyGenerator @@ -102,6 +115,10 @@ export default function (Generator) { } else { code = Generator.blockToCode(customBlock); } + // "Run without screen refresh" (issue #2114): `without_screen_refresh def foo`, as `private def foo`. + if (isWarp(customBlock)) { + code = `without_screen_refresh ${code}`; + } // Generate method body from the saved next block const bodyBlock = Generator.getBlock(savedNext); @@ -133,7 +150,7 @@ export default function (Generator) { // The return comment contains the method name const returnComment = Generator.getRubyMarkerText(lastBlock); if (returnComment) { - const returnMatch = returnComment.match(/@ruby:return:(\w+)/); + const returnMatch = returnComment.match(/@ruby:return:([^:,\s]+)/); if (returnMatch) { if (!Generator.returnCallCache_) { Generator.returnCallCache_ = {}; @@ -204,10 +221,8 @@ export default function (Generator) { }; const blockToMethod = function (block, isCall) { - let methodName = block.mutation.proccode - .split(' ') - .filter((i) => !/^%[sb]$/.test(i)) - .join('_'); + // A name that starts with a digit or is a reserved word gets `_` in front (issue #2116). + let methodName = rubyMethodNameOfProccode(block.mutation.proccode); if (methodName.length === 0) { methodName = 'procedure'; } @@ -273,7 +288,7 @@ export default function (Generator) { // Extract method name from the return assignment comment const nextComment = Generator.getRubyMarkerText(nextBlock); if (nextComment) { - const match = nextComment.match(/@ruby:return:(\w+)/); + const match = nextComment.match(/@ruby:return:([^:,\s]+)/); if (match) { Generator.returnCallCache_[match[1]] = superCode; } diff --git a/packages/scratch-gui/src/lib/ruby-method-name.js b/packages/scratch-gui/src/lib/ruby-method-name.js new file mode 100644 index 00000000000..013a1662b70 --- /dev/null +++ b/packages/scratch-gui/src/lib/ruby-method-name.js @@ -0,0 +1,118 @@ +/** + * The name of a custom block (My Block) and its Ruby method name (issue #2116). + * + * The generator joins the words of the block name with `_` (`'1 文字えらぶ %s'` → `1_文字えらぶ`). + * A name that starts with a digit (`1_文字えらぶ`) or is a reserved word (`end`, `if`) is not a + * method name that can be called in Ruby, so the generator puts a `_` in front (`_1_文字えらぶ`) and + * the converter takes it off again. The names that only differ by the `_` in front are handled the + * same way (`_end` is written `__end`), so every block name comes back as it was. + * `_1` to `_9` are the numbered parameters of a block in Ruby and cannot be method names, so a + * name that is one digit from 1 to 9 gets `__` (`1` is written `__1`, `_1` is `___1`). + */ + +/** + * The reserved words of Ruby. A method may be defined with these names, but calling it without + * a receiver (`end`, `if(1)`) is a syntax error. + */ +const RESERVED_WORDS = new Set([ + '__ENCODING__', + '__LINE__', + '__FILE__', + 'BEGIN', + 'END', + 'alias', + 'and', + 'begin', + 'break', + 'case', + 'class', + 'def', + 'defined?', + 'do', + 'else', + 'elsif', + 'end', + 'ensure', + 'false', + 'for', + 'if', + 'in', + 'module', + 'next', + 'nil', + 'not', + 'or', + 'redo', + 'rescue', + 'retry', + 'return', + 'self', + 'super', + 'then', + 'true', + 'undef', + 'unless', + 'until', + 'when', + 'while', + 'yield', +]); + +/** + * Whether a name, without the `_`s in front, cannot be a Ruby method name to call. + * @param {string} name - The name. + * @returns {boolean} true when it starts with a digit or is a reserved word. + */ +const needsPrefix = (name) => { + const base = name.replace(/^_+/, ''); + return /^\d/.test(base) || RESERVED_WORDS.has(base); +}; + +/** + * Whether a name, without the `_`s in front, is one digit from 1 to 9 (`_1` is a numbered parameter). + * @param {string} name - The name. + * @returns {boolean} true for `1`, `_1`, `__9`, ... + */ +const isOneDigit = (name) => /^_*[1-9]$/.test(name); + +/** + * The prefix that makes a block name a Ruby method name. + * @param {string} name - The name of the block. + * @returns {string} `''`, `'_'` or `'__'`. + */ +const prefixOf = (name) => { + if (isOneDigit(name)) return '__'; + return needsPrefix(name) ? '_' : ''; +}; + +/** + * The Ruby method name of a custom block name (the words of the proccode joined with `_`). + * @param {string} blockName - The name of the block, e.g. `1_文字えらぶ`. + * @returns {string} The method name, e.g. `_1_文字えらぶ`. + */ +const rubyMethodNameOfBlockName = (blockName) => `${prefixOf(blockName)}${blockName}`; + +/** + * The name of the custom block of a Ruby method name (the reverse of `rubyMethodNameOfBlockName`). + * @param {string} methodName - The method name, e.g. `_1_文字えらぶ`. + * @returns {string} The name of the block, e.g. `1_文字えらぶ`. + */ +const blockNameOfRubyMethodName = (methodName) => { + if (isOneDigit(methodName)) return methodName.startsWith('__') ? methodName.slice(2) : methodName; + return methodName.startsWith('_') && needsPrefix(methodName) ? methodName.slice(1) : methodName; +}; + +/** + * The Ruby method name of a proccode (`'1 文字えらぶ %s'` → `_1_文字えらぶ`). + * @param {string} proccode - The proccode of a procedures_prototype / procedures_call block. + * @returns {string} The method name (an empty string for an empty proccode). + */ +const rubyMethodNameOfProccode = (proccode) => + rubyMethodNameOfBlockName( + (proccode || '') + .split(' ') + .filter((i) => !/^%[sb]$/.test(i)) + .join('_'), + ); + +export { blockNameOfRubyMethodName, rubyMethodNameOfBlockName, rubyMethodNameOfProccode }; diff --git a/packages/scratch-gui/src/lib/ruby-to-blocks-converter/context-utils.js b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/context-utils.js index 73a3bc992a0..5d50caae0fd 100644 --- a/packages/scratch-gui/src/lib/ruby-to-blocks-converter/context-utils.js +++ b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/context-utils.js @@ -54,6 +54,8 @@ const ContextUtils = { containerNodeRanges: [], // Store {startLine, endLine} for container nodes (block, begin, kwbegin) processDepth: 0, rootNode: null, + // The DefNodes of `without_screen_refresh def` (screen-refresh-defs.js) + warpDefNodes: new Set(), modules: Object.create(null), currentModuleName: null, superMethodMap: Object.create(null), diff --git a/packages/scratch-gui/src/lib/ruby-to-blocks-converter/module-visitor.js b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/module-visitor.js index 71a287d28dd..c571e88ebfd 100644 --- a/packages/scratch-gui/src/lib/ruby-to-blocks-converter/module-visitor.js +++ b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/module-visitor.js @@ -4,6 +4,7 @@ import RubyParser from '../ruby-parser'; import { messages } from './converter-errors'; import { RubyToBlocksConverterError } from './errors'; import { nodeTypeName } from './node-walk'; +import { unwrapWithoutScreenRefreshDefs } from './screen-refresh-defs'; /** * Mixin methods for visiting module nodes in the Ruby-to-blocks converter. @@ -81,6 +82,7 @@ const ModuleVisitor = { // The parsed result should be: ProgramNode > StatementsNode > [ModuleNode] const root = parseResult.value; + unwrapWithoutScreenRefreshDefs(root).forEach((def) => this._context.warpDefNodes.add(def)); let moduleNode = null; if (root.statements && root.statements.body) { for (const stmt of root.statements.body) { diff --git a/packages/scratch-gui/src/lib/ruby-to-blocks-converter/my-blocks.js b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/my-blocks.js index 96e9900699e..25b09f62c73 100644 --- a/packages/scratch-gui/src/lib/ruby-to-blocks-converter/my-blocks.js +++ b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/my-blocks.js @@ -1,6 +1,7 @@ import _ from 'lodash'; import { defineMessages } from 'react-intl'; import * as Blockly from 'scratch-blocks'; +import { rubyMethodNameOfProccode } from '../ruby-method-name'; import { RubyToBlocksConverterError } from './errors'; import Primitive from './primitive'; @@ -42,7 +43,7 @@ const MyBlocksConverter = { children: [], proccode: procedure.procCode.join(' '), tagName: 'mutation', - warp: 'false', + warp: procedure.warp ? 'true' : 'false', }, }); @@ -218,6 +219,8 @@ const MyBlocksConverter = { topLevel: true, }); const procedure = converter._createProcedure(procedureName); + // `without_screen_refresh def` (issue #2114, unwrapped by the parse stage) + procedure.warp = converter._context.warpDefNodes.has(node); const customBlock = converter._createBlock('procedures_prototype', 'statement', { shadow: true, @@ -332,10 +335,7 @@ const MyBlocksConverter = { !lastCommentText.includes('@ruby:syntax:return') ) { const calledProccode = last.mutation.proccode; - const calledProcName = calledProccode - .split(' ') - .filter((i) => !/^%[sb]$/.test(i)) - .join('_'); + const calledProcName = rubyMethodNameOfProccode(calledProccode); const sourceVariable = converter._lookupOrCreateVariable(`@_return_${calledProcName}_`); const targetVariable = converter._lookupOrCreateVariable(`@_return_${procedureName}_`); @@ -526,7 +526,7 @@ const MyBlocksConverter = { children: [], proccode: procedure.procCode.join(' '), tagName: 'mutation', - warp: 'false', + warp: procedure.warp ? 'true' : 'false', }; return block; diff --git a/packages/scratch-gui/src/lib/ruby-to-blocks-converter/parse-stage.js b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/parse-stage.js index 0f4fca12380..e5a1f322a91 100644 --- a/packages/scratch-gui/src/lib/ruby-to-blocks-converter/parse-stage.js +++ b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/parse-stage.js @@ -1,4 +1,5 @@ // === Smalruby: This file is Smalruby-specific (the parse stage, docs/ruby-editor/converter-stages.md) === +import { unwrapWithoutScreenRefreshDefs } from './screen-refresh-defs'; /** * The parse stage: the index of the source and the tree of prism. Mixed into @@ -35,6 +36,8 @@ const ParseStage = { return null; } this._context.rootNode = parseResult.value; // Save root node for line mapping + // `without_screen_refresh def foo` becomes the `def`; the `def`s are kept (issue #2114). + this._context.warpDefNodes = unwrapWithoutScreenRefreshDefs(parseResult.value); return parseResult; }, }; diff --git a/packages/scratch-gui/src/lib/ruby-to-blocks-converter/return-value-temps.js b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/return-value-temps.js index 5c3cf01af68..33eed3054b5 100644 --- a/packages/scratch-gui/src/lib/ruby-to-blocks-converter/return-value-temps.js +++ b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/return-value-temps.js @@ -1,5 +1,6 @@ // === Smalruby: This file is Smalruby-specific (return values saved in instance variables, issue #1725) === import _ from 'lodash'; +import { rubyMethodNameOfProccode } from '../ruby-method-name'; import { RubyToBlocksConverterError } from './errors'; import { myBlocksMessages } from './my-blocks'; @@ -200,7 +201,7 @@ const ReturnValueTemps = { */ _procedureNameOfCall(block) { const proccode = (block.mutation && block.mutation.proccode) || ''; - return proccode.split(' ')[0]; + return rubyMethodNameOfProccode(proccode); }, /** diff --git a/packages/scratch-gui/src/lib/ruby-to-blocks-converter/screen-refresh-defs.js b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/screen-refresh-defs.js new file mode 100644 index 00000000000..b28224a5dc2 --- /dev/null +++ b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/screen-refresh-defs.js @@ -0,0 +1,52 @@ +// === Smalruby: This file is Smalruby-specific (`without_screen_refresh def`, issue #2114) === +import { forEachNode, nodeTypeName } from './node-walk'; + +const WITHOUT_SCREEN_REFRESH = 'without_screen_refresh'; + +/** + * The `def` of `without_screen_refresh def foo ... end`, or null for any other node. + * @param {object} node - A statement. + * @returns {?object} The DefNode. + */ +const wrappedDefOf = (node) => { + if (nodeTypeName(node) !== 'CallNode' || node.name !== WITHOUT_SCREEN_REFRESH) return null; + if (node.receiver || node.block) return null; + const args = node.arguments_ ? node.arguments_.arguments_ : []; + if (args.length !== 1 || nodeTypeName(args[0]) !== 'DefNode') return null; + return args[0]; +}; + +/** + * "Run without screen refresh" of a custom block is written `without_screen_refresh def foo ... end` + * (as `private def foo`). The parse stage puts the `def` in the place of the call, so the rest of + * the converter (the analysis, class / module, comments, the check of `def` in a block body) sees + * an ordinary `def`, and returns the `def`s that were wrapped. The tree is changed in place. + * A program that defines its own `without_screen_refresh` method keeps the calls as they are. + * @param {object} root - The root of the prism tree. + * @returns {Set} The DefNodes that run without screen refresh. + */ +const unwrapWithoutScreenRefreshDefs = (root) => { + const defs = new Set(); + let definesOwn = false; + forEachNode(root, { + enter(node, type) { + if (type === 'DefNode' && node.name === WITHOUT_SCREEN_REFRESH) definesOwn = true; + }, + }); + if (definesOwn) return defs; + forEachNode(root, { + enter(node, type) { + if (type !== 'StatementsNode' || !Array.isArray(node.body)) return; + node.body.forEach((statement, i) => { + const def = wrappedDefOf(statement); + if (def) { + node.body[i] = def; + defs.add(def); + } + }); + }, + }); + return defs; +}; + +export { unwrapWithoutScreenRefreshDefs }; diff --git a/packages/scratch-gui/src/lib/ruby-to-blocks-converter/variable-utils.js b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/variable-utils.js index 3130cd11beb..fa11363beb5 100644 --- a/packages/scratch-gui/src/lib/ruby-to-blocks-converter/variable-utils.js +++ b/packages/scratch-gui/src/lib/ruby-to-blocks-converter/variable-utils.js @@ -1,5 +1,6 @@ import { defineMessages } from 'react-intl'; import * as Blockly from 'scratch-blocks'; +import { blockNameOfRubyMethodName, rubyMethodNameOfProccode } from '../ruby-method-name'; import { Variable } from './constants'; import { RubyToBlocksConverterError } from './errors'; @@ -238,10 +239,7 @@ const VariableUtils = { const proccode = block.mutation.proccode; if (!proccode) return false; // Extract procedure name from proccode (name is the first part before any %s/%b) - const procName = proccode - .split(' ') - .filter((i) => !/^%[sb]$/.test(i)) - .join('_'); + const procName = rubyMethodNameOfProccode(proccode); const procedure = this._lookupProcedure(procName); return procedure && procedure.hasReturnValue; }, @@ -258,7 +256,8 @@ const VariableUtils = { procedure = { id: Blockly.utils.idGenerator.genUid(), name: name, - procCode: [name], + // The block name of a method name such as `_1_文字えらぶ` is `1_文字えらぶ` (issue #2116). + procCode: [blockNameOfRubyMethodName(name)], argumentNames: [], argumentDefaults: [], argumentIds: [], diff --git a/packages/scratch-gui/test/unit/lib/ruby-roundtrip/my-block-warp-and-name.test.js b/packages/scratch-gui/test/unit/lib/ruby-roundtrip/my-block-warp-and-name.test.js new file mode 100644 index 00000000000..b1e1430e6ee --- /dev/null +++ b/packages/scratch-gui/test/unit/lib/ruby-roundtrip/my-block-warp-and-name.test.js @@ -0,0 +1,318 @@ +/** + * The definition of a custom block (My Block) in Ruby: + * - "run without screen refresh" (the `warp` of the prototype) is `without_screen_refresh def ...` + * (issue #2114). + * - a name that cannot be a Ruby method name (it starts with a digit, or is a reserved word) gets + * a `_` in front, and the `_` is taken off again on the way back (issue #2116). + */ +import dedent from 'dedent'; +import RubyGenerator from '../../../../src/lib/ruby-generator'; +import { + expectRoundTrip, + makeConverter, + makeSpriteTarget, + rubyToBlocksToRuby, + setupRubyGenerator, +} from '../../helpers/ruby-roundtrip-helper'; + +const blocksOf = (target, opcode) => Object.values(target.blocks._blocks).filter((b) => b.opcode === opcode); + +const generate = (target, version) => { + RubyGenerator.currentTarget = target; + return RubyGenerator.targetToCode(target, { version }).trim(); +}; + +describe('Ruby Roundtrip: run without screen refresh (issue #2114)', () => { + let target, runtime, converter; + + const convert = async (code, version = '2') => { + ({ target, runtime } = makeSpriteTarget()); + setupRubyGenerator(); + converter = makeConverter(target, runtime, { version }); + const ok = await converter.targetCodeToBlocks(target, code); + if (!ok) throw new Error(JSON.stringify(converter.errors)); + await converter.applyTargetBlocks(target); + }; + + beforeEach(() => { + ({ target, runtime } = makeSpriteTarget()); + setupRubyGenerator(); + converter = makeConverter(target, runtime, { version: '2' }); + }); + + test('without_screen_refresh def makes a definition that runs without screen refresh', async () => { + await convert(dedent` + without_screen_refresh def 学習する + @見る長さ = 1 + end + `); + const [prototype] = blocksOf(target, 'procedures_prototype'); + expect(prototype.mutation.warp).toBe('true'); + }); + + test('a plain def runs with screen refresh', async () => { + await convert(dedent` + def 学習する + @見る長さ = 1 + end + `); + const [prototype] = blocksOf(target, 'procedures_prototype'); + expect(prototype.mutation.warp).toBe('false'); + }); + + test('a definition that runs without screen refresh is written with without_screen_refresh', async () => { + await convert(dedent` + def 学習する(n) + @見る長さ = n + end + + 学習する(2) + `); + blocksOf(target, 'procedures_prototype')[0].mutation.warp = 'true'; + expect(generate(target, '2')).toEqual(dedent` + without_screen_refresh def 学習する(n) + @見る長さ = n + end + + 学習する(2) + `); + }); + + test('warp as a boolean (a loaded project) is written too', async () => { + await convert('def foo\n move(10)\nend'); + blocksOf(target, 'procedures_prototype')[0].mutation.warp = true; + expect(generate(target, '2')).toEqual('without_screen_refresh def foo\n move(10)\nend'); + }); + + test.each([ + [ + 'arguments and a return value', + dedent` + without_screen_refresh def add(a, b) + a + b + end + + when_flag_clicked do + say(add(1, 2)) + end + `, + ], + [ + 'a call of a method in the body', + dedent` + def foo(n) + n * 2 + end + + without_screen_refresh def bar(n) + say(foo(1) + n) + end + + bar(3) + `, + ], + [ + 'two definitions, one of them without screen refresh', + dedent` + def foo + move(10) + end + + without_screen_refresh def bar + 10.times do + move(1) + end + end + `, + ], + ])('round trip: %s', async (_name, code) => { + expect(await rubyToBlocksToRuby(converter, target, code)).toEqual(code); + }); + + test('round trip at Ruby v1 (def self.)', async () => { + ({ target, runtime } = makeSpriteTarget()); + converter = makeConverter(target, runtime, { version: '1' }); + const code = dedent` + without_screen_refresh def self.foo + move(10) + end + `; + expect(await rubyToBlocksToRuby(converter, target, code)).toEqual(code); + }); + + test('round trip in a class', async () => { + const inClass = async (code) => { + ({ target, runtime } = makeSpriteTarget()); + target.sprite = { name: 'Sprite1', costumes: [], sounds: [] }; + target.runtime.targets = [target]; + converter = makeConverter(target, runtime, { version: '2' }); + return rubyToBlocksToRuby(converter, target, code); + }; + const plain = await inClass('class Sprite1\n def foo\n move(10)\n end\nend'); + const warp = await inClass('class Sprite1\n without_screen_refresh def foo\n move(10)\n end\nend'); + expect(warp).toEqual(plain.replace('def foo', 'without_screen_refresh def foo')); + expect(warp).toContain(' without_screen_refresh def foo\n'); + }); + + test('round trip in a module', async () => { + ({ target, runtime } = makeSpriteTarget()); + target.sprite = { name: 'Sprite1', costumes: [], sounds: [] }; + runtime.targets = [runtime.getTargetForStage(), target]; + converter = makeConverter(target, runtime, { version: '2' }); + const code = dedent` + module Walk + without_screen_refresh def walk + move(10) + end + end + + class Sprite1 + include Walk + + when_flag_clicked do + walk + end + end + `; + expect(await rubyToBlocksToRuby(converter, target, code)).toEqual(code); + expect(blocksOf(target, 'procedures_prototype')[0].mutation.warp).toBe('true'); + }); + + test('a method of the user named without_screen_refresh is called as it is', async () => { + await expectRoundTrip( + converter, + target, + dedent` + def without_screen_refresh(n) + move(n) + end + + without_screen_refresh(10) + `, + ); + }); +}); + +describe('Ruby Roundtrip: a name of a custom block that cannot be a Ruby method name (issue #2116)', () => { + let target, runtime, converter; + + beforeEach(() => { + ({ target, runtime } = makeSpriteTarget()); + setupRubyGenerator(); + converter = makeConverter(target, runtime, { version: '2' }); + }); + + const convert = async (code) => { + const ok = await converter.targetCodeToBlocks(target, code); + if (!ok) throw new Error(JSON.stringify(converter.errors)); + await converter.applyTargetBlocks(target); + }; + + const renameProcedure = (from, to) => { + [...blocksOf(target, 'procedures_prototype'), ...blocksOf(target, 'procedures_call')].forEach((b) => { + b.mutation.proccode = b.mutation.proccode.replace(from, to); + }); + }; + + test('a name that starts with a digit gets `_` in Ruby', async () => { + await convert(dedent` + def foo(n) + say(n) + end + + foo(1) + `); + renameProcedure('foo', '1 文字えらぶ'); + expect(generate(target, '2')).toEqual(dedent` + def _1_文字えらぶ(n) + say(n) + end + + _1_文字えらぶ(1) + `); + }); + + test('the `_` is taken off on the way back', async () => { + await convert(dedent` + def _1_文字えらぶ(n) + say(n) + end + + _1_文字えらぶ(1) + `); + const [prototype] = blocksOf(target, 'procedures_prototype'); + expect(prototype.mutation.proccode).toBe('1_文字えらぶ %s'); + const [call] = blocksOf(target, 'procedures_call'); + expect(call.mutation.proccode).toBe('1_文字えらぶ %s'); + }); + + test.each([ + ['end', '_end'], + ['if', '_if'], + ['_1 x', '__1_x'], + ['_end', '__end'], + ['1', '__1'], + ['_1', '___1'], + ['10', '_10'], + ])('the block name %s is written %s and comes back', async (blockName, rubyName) => { + await convert('def foo\n move(10)\nend\n\nfoo'); + renameProcedure(/^foo/, blockName); + const ruby = generate(target, '2'); + expect(ruby).toEqual(`def ${rubyName}\n move(10)\nend\n\n${rubyName}`); + + ({ target, runtime } = makeSpriteTarget()); + converter = makeConverter(target, runtime, { version: '2' }); + await convert(ruby); + expect(blocksOf(target, 'procedures_prototype')[0].mutation.proccode).toBe(blockName.replace(' ', '_')); + expect(generate(target, '2')).toEqual(ruby); + }); + + test.each([ + [ + 'a call whose value is used', + dedent` + def _1_文字えらぶ(n) + n + 1 + end + + when_flag_clicked do + say(_1_文字えらぶ(3)) + end + `, + ], + [ + 'an explicit return', + dedent` + def _1_文字えらぶ(n) + return n + 1 + end + + when_flag_clicked do + say(_1_文字えらぶ(3) + _1_文字えらぶ(4)) + end + `, + ], + [ + 'without screen refresh', + dedent` + without_screen_refresh def _2_回(n) + move(n) + end + + _2_回(1) + `, + ], + [ + 'an ordinary name with an underscore in front', + dedent` + def _foo + move(10) + end + + _foo + `, + ], + ])('round trip: %s', async (_name, code) => { + expect(await rubyToBlocksToRuby(converter, target, code)).toEqual(code); + }); +}); diff --git a/ruby/smalruby3/lib/smalruby3/dsl.rb b/ruby/smalruby3/lib/smalruby3/dsl.rb index c6f1f0218c6..bcc3575dccd 100644 --- a/ruby/smalruby3/lib/smalruby3/dsl.rb +++ b/ruby/smalruby3/lib/smalruby3/dsl.rb @@ -56,6 +56,13 @@ def set_name(name) @_name = name end + # `without_screen_refresh def foo ... end` marks a custom block "run without screen + # refresh" in Smalruby's Ruby. The runtime runs the method as it is (a loop in it still + # refreshes the screen with `with_screen_refresh`); the mark is kept for the editor. + def without_screen_refresh(name) + name + end + def set_sprite(name) @_sprite_name = name end @@ -155,6 +162,13 @@ def set_name(name) @_name = name end + # `without_screen_refresh def foo ... end` marks a custom block "run without screen + # refresh" in Smalruby's Ruby. The runtime runs the method as it is (a loop in it still + # refreshes the screen with `with_screen_refresh`); the mark is kept for the editor. + def without_screen_refresh(name) + name + end + def set_backdrops(list) @_backdrop_names = list end diff --git a/ruby/smalruby3/test/dsl_test.rb b/ruby/smalruby3/test/dsl_test.rb index 14f6025ab06..93581c4040e 100644 --- a/ruby/smalruby3/test/dsl_test.rb +++ b/ruby/smalruby3/test/dsl_test.rb @@ -29,6 +29,21 @@ def test_sprite_defaults assert_equal "all around", klass._initial_rotation_style end + def test_without_screen_refresh_def_defines_the_method + sprite_class = Class.new(Smalruby3::Sprite) do + without_screen_refresh def foo(n) + n * 2 + end + end + stage_class = Class.new(Smalruby3::Stage) do + without_screen_refresh def bar + 3 + end + end + assert sprite_class.method_defined?(:foo) + assert stage_class.method_defined?(:bar) + end + def test_sprite_set_sprite klass = Class.new(Smalruby3::Sprite) do set_sprite "Shimaraby"