Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions docs/ruby-editor/bridging-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 には残らない)。

Expand Down Expand Up @@ -740,6 +741,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/` のこと。
Expand Down
12 changes: 12 additions & 0 deletions docs/smalruby-language-spec.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions docs/smalruby-language-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions packages/scratch-gui/.prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,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/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion packages/scratch-gui/src/lib/ruby-generator/control.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};

Expand Down
4 changes: 2 additions & 2 deletions packages/scratch-gui/src/lib/ruby-generator/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 '';
}

Expand Down Expand Up @@ -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_ &&
Expand Down
27 changes: 21 additions & 6 deletions packages/scratch-gui/src/lib/ruby-generator/procedure.js
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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_ = {};
Expand Down Expand Up @@ -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';
}
Expand Down Expand Up @@ -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;
}
Expand Down
118 changes: 118 additions & 0 deletions packages/scratch-gui/src/lib/ruby-method-name.js
Original file line number Diff line number Diff line change
@@ -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 };
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -42,7 +43,7 @@ const MyBlocksConverter = {
children: [],
proccode: procedure.procCode.join(' '),
tagName: 'mutation',
warp: 'false',
warp: procedure.warp ? 'true' : 'false',
},
});

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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}_`);

Expand Down Expand Up @@ -526,7 +526,7 @@ const MyBlocksConverter = {
children: [],
proccode: procedure.procCode.join(' '),
tagName: 'mutation',
warp: 'false',
warp: procedure.warp ? 'true' : 'false',
};

return block;
Expand Down
Loading
Loading