diff --git a/docs/dncl/README.md b/docs/dncl/README.md index c4ea4c64d3..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`)を添えて返す。 @@ -178,18 +180,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 +219,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 の文のまま(「「//」が読めません」など) | @@ -421,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` を一度に追加 | @@ -549,6 +555,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/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/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/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/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..66a1c0bd88 100644 --- a/packages/scratch-gui/src/locales/ja.js +++ b/packages/scratch-gui/src/locales/ja.js @@ -1907,6 +1907,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/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/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-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([ 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: [] }); + }); +});