# 修正済みのバグ

このページ: https://emojicode-ide.com/docs/about/patched/

Emojicode の公式コンパイラ（[`master`](https://github.com/emojicode/emojicode/tree/master)、コミット [`4dec45b`](https://github.com/emojicode/emojicode/commit/4dec45b497e4f4dce7f5f5ae11a00d8e8e9af67c)）にあるバグのうち、この IDE では修正パッチが当たっていて、正しく動くものです。公式コンパイラで同じコードを動かすと、結果が違うことがあります。

修正されていないバグは [Emojicode言語のバグ](https://emojicode-ide.com/docs/about/known-issues.md) にあります。修正パッチの全体は [emojicode-wasm32.patch](/docs/patches/emojicode-wasm32.patch.txt) で見られます。

## `🔧` で、文字列の最後の日本語や絵文字が壊れる

公式コンパイラでは、`🔧`（前後の空白を取り除く）で、文字列の最後の文字が日本語や絵文字だと、その文字が壊れます。どの環境でも起きます。

```emojicode
🏁 🍇
  😀 🔧 🔤  まわりの空白  🔤❗️❗️
🍉
```

この IDE の実行結果:

```text
まわりの空白
```

公式コンパイラの実行結果:

```text
まわりの空�
```

公式コンパイラでは、最後の文字が壊れて `まわりの空�` になります。最後の文字の位置を「その文字の先頭のバイト」として数えているので、2 バイト目より後ろが切り捨てられるためです。修正パッチでは、最後の文字の終わりまでを残します。

修正パッチ：s/String.cpp:

```diff
@@ -140,32 +147,41 @@ extern "C" s::String* sStringTrim(String *string) {
     for (; begin < string->count;) {
         utf8proc_int32_t codepoint;
         auto state = utf8proc_iterate(reinterpret_cast<utf8proc_uint8_t *>(string->characters.get()) + begin,
-                                      string->count, &codepoint);
+                                      string->count - begin, &codepoint);
         if (state < 0) break;
         if (utf8proc_get_property(codepoint)->bidi_class != UTF8PROC_BIDI_CLASS_WS) break;
         begin += state;
     }
 
-    size_t end = begin - 1;
+    // end is exclusive: the byte after the last non-whitespace code point. Using the start of that code point
+    // (as before) cut multi-byte characters at the end of the string down to their first byte.
+    size_t end = begin;
     for (size_t i = begin; i < string->count;) {
         utf8proc_int32_t codepoint;
         auto state = utf8proc_iterate(reinterpret_cast<utf8proc_uint8_t *>(string->characters.get()) + i,
-                                      string->count, &codepoint);
+                                      string->count - i, &codepoint);
         if (state < 0) break;
         if (utf8proc_get_property(codepoint)->bidi_class != UTF8PROC_BIDI_CLASS_WS) {
-            end = i;
+            end = i + state;
         }
         i += state;
     }
 
     auto newString = String::init();
-    newString->count = end - begin + 1;
+    newString->count = end - begin;
     newString->characters = runtime::allocate<char>(string->count);
     std::memcpy(newString->characters.get(), string->characters.get() + begin, newString->count);
     return newString;
 }
 
+#ifdef __wasi__
+extern "C" void sStringGraphemes(String *string, void *cbFn, void *cbCapture) {
+    runtime::Callable<void, s::String*> cb;
+    void *parts[2] = {cbFn, cbCapture};
+    std::memcpy(&cb, parts, sizeof(parts));
+#else
 extern "C" void sStringGraphemes(String *string, runtime::Callable<void, s::String*> cb) {
+#endif
     auto bytes = reinterpret_cast<utf8proc_uint8_t *>(string->characters.get());
     utf8proc_int32_t state = 0;
     utf8proc_int32_t prev;
```

## `🤷‍♀️` と比べる式で、コンパイラが落ちることがある

公式コンパイラでは、`値 🙌 🤷‍♀️`（値なしとの比較）を含む式をコンパイルするとき、コンパイラの中で、使わない値を作ろうとして未定義動作が起きます。普通のパソコン（x86-64）ではたまたま問題が出ませんが、WebAssembly ではコンパイラが落ちます。

```emojicode
🏁 🍇
  🖍🆕 thing ⚪️
  🔤abc🔤 ➡️ 🖍thing
  ↪️ 🔲 thing 🔢 🙌 🤷‍♀️ 🍇
    😀 🔤数ではない🔤❗️
  🍉
🍉
```

この IDE の実行結果:

```text
数ではない
```

公式コンパイラの実行結果:

```text
（コンパイルが終わらない）
```

`🔲 thing 🔢`（`⚪️` を `🔢` にキャストした結果。キャストできなければ値なし）を `🤷‍♀️` と比べています。公式コンパイラをパッチなしで WebAssembly にすると、この例のコンパイルが終わらなくなります（普通のパソコンで動く公式コンパイラでは、たまたま問題が出ないことがあります）。

修正パッチでは、`🤷‍♀️` の側の値を作りません（そもそも必要ないため）。

修正パッチ：Compiler/AST/ASTBinaryOperator_CG.cpp:

```diff
@@ -17,6 +17,21 @@ Value* ASTBinaryOperator::generate(FunctionCodeGenerator *fg) const {
         return generateLogical(fg);
     }
 
+    // The 🤷‍♀️ operand is never complied (its type stays noReturn), so it must not be generated:
+    // building an optional of void is undefined behaviour inside LLVM and crashes on wasm32.
+    if (builtIn_ == BuiltInType::IsNoValueLeft) {
+        auto left = left_->generate(fg);
+        return left_->expressionType().storageType() == StorageType::Box
+                ? fg->buildHasNoValueBox(left)
+                : fg->buildOptionalHasNoValue(left, left_->expressionType());
+    }
+    if (builtIn_ == BuiltInType::IsNoValueRight) {
+        auto right = right_->generate(fg);
+        return right_->expressionType().storageType() == StorageType::Box
+                ? fg->buildHasNoValueBox(right)
+                : fg->buildOptionalHasNoValue(right, right_->expressionType());
+    }
+
     if (builtIn_ != BuiltInType::None) {
         auto left = left_->generate(fg);
         auto right = right_->generate(fg);
@@ -71,14 +86,6 @@ Value* ASTBinaryOperator::generate(FunctionCodeGenerator *fg) const {
                 return fg->builder().CreateAnd(left, right);
             case BuiltInType::Equal:
                 return fg->builder().CreateICmpEQ(left, right);
-            case BuiltInType::IsNoValueLeft:
-                return left_->expressionType().storageType() == StorageType::Box
-                        ? fg->buildHasNoValueBox(left)
-                        : fg->buildOptionalHasNoValue(left, left_->expressionType());
-            case BuiltInType::IsNoValueRight:
-                return right_->expressionType().storageType() == StorageType::Box
-                        ? fg->buildHasNoValueBox(right)
-                        : fg->buildOptionalHasNoValue(right, right_->expressionType());
             default:
                 break;
         }
```

## `📦 files` で、ファイルへの書き込みに失敗してもエラーにならない

公式コンパイラでは、`files` パッケージの `✏️`（ファイルに書き込む）は、エラーを投げることがあるメソッドとして宣言されていますが、中身（C++）がエラーを受け取る引数を持っていません。そのため、書き込みに失敗してもエラーになりません。WebAssembly では、引数の数が合わないとその場で止まるので、書き込み自体ができません。修正パッチでは、引数を足して、書き込みに失敗したらエラーを投げます。

修正パッチ：files/File.cpp:

```diff
@@ -37,8 +37,10 @@ extern "C" File* filesFileNewReading(String *path, runtime::Raiser *raiser) {
     return file;
 }
 
-extern "C" void filesFileWrite(File *file, Data *data) {
+// files.🍇 declares ✏️ as raising, so the compiler passes a Raiser (a missing parameter is a signature mismatch on wasm).
+extern "C" void filesFileWrite(File *file, Data *data, runtime::Raiser *raiser) {
     file->file_.write(reinterpret_cast<char *>(data->data.get()), data->count);
+    EJC_COND_RAISE_IO_VOID(!file->file_.fail(), raiser);
 }
 
 extern "C" void filesFileClose(File *file) {
```

## クラスの情報の並び方が、コンパイラとランタイムで違う

公式コンパイラでは、クラスのインスタンスが持っている「クラスの情報」の先頭の部分の並び方が、コンパイラ（それを作る側）とランタイム（それを読む側）で食い違っています。64 ビットの環境ではたまたま大きさが同じなので問題になりませんが、32 ビットの WebAssembly ではずれてしまい、インスタンスを片付けるときに落ちます。修正パッチでは、ランタイム側の並び方をコンパイラに合わせます。

修正パッチ：runtime/Runtime.h:

```diff
@@ -48,8 +48,16 @@ using is_complete = decltype(is_complete_impl(std::declval<T*>()));
 
 }  // namespace util
 
+/// Mirrors the compiler's %runTimeTypeInfo = { i16, i16, i8 } so that the layout
+/// matches on every target (a plain pointer only happened to match on 64-bit).
+struct ClassRunTimeTypeInfo {
+    uint16_t genericParameterCount;
+    uint16_t genericParameterOffset;
+    uint8_t flags;
+};
+
 struct ClassInfo {
-    void *rtti;
+    ClassRunTimeTypeInfo rtti;
     void **dispatchTable;
     void *protocolTable;
     ClassInfo *superclass;
```

## `🍱` 型の変数を片付けるときに止まる

公式コンパイラでは、複数のプロトコルをまとめた型（`🍱プロトコル プロトコル🍱`、[型の値とキャスト](https://emojicode-ide.com/docs/types/casting.md)）の **変数** にクラスのインスタンスを入れると、その変数を片付けるところで、関係のない場所を関数として呼んでしまいます。

```emojicode
🐊 🔊 🍇
  ❗️ 🗣 ➡️ 🔡
🍉

🐊 🏃 🍇
  ❗️ 🦵 ➡️ 🔡
🍉

🐇 🐕 🍇
  🐊 🔊
  🐊 🏃
  🆕 🍇🍉
  ❗️ 🗣 ➡️ 🔡 🍇
    ↩️ 🔤ワン🔤
  🍉
  ❗️ 🦵 ➡️ 🔡 🍇
    ↩️ 🔤タタタ🔤
  🍉
🍉

🏁 🍇
  🖍🆕 pet 🍱🔊🏃🍱
  🆕🐕❗️ ➡️ 🖍pet
  😀 🗣 pet❗️❗️
  😀 🦵 pet❗️❗️
🍉
```

この IDE の実行結果:

```text
ワン
タタタ
```

公式コンパイラの実行結果:

```text
ワン
タタタ
（最後に null function or function signature mismatch で止まる）
```

`🍱` の値を入れた箱の先頭には、「箱の情報」ではなく「プロトコルごとの対応表の一覧」が入っています。公式コンパイラは、片付けるときだけそれを「箱の情報」として読むので、一覧の外を読んで、そこにある値を関数として呼んでしまいます（上の結果は、パッチなしで WebAssembly にした場合です）。修正パッチでは、一覧の最初の対応表から、片付ける関数を取り出します。

修正パッチ：Compiler/Generation/FunctionCodeGenerator.cpp:

```diff
@@ -469,6 +469,15 @@ void FunctionCodeGenerator::manageBox(bool retain, llvm::Value *boxInfo, llvm::V
         auto conf = builder().CreateBitCast(boxInfo, typeHelper().protocolConformance()->getPointerTo());
         fnPtr = builder().CreateConstInBoundsGEP2_32(typeHelper().protocolConformance(), conf, 0, retain ? 3 : 4);
     }
+    else if (type.boxedFor().type() == TypeType::MultiProtocol) {
+        // A multiprotocol box does not store a box info but a pointer to an array of protocol conformances (one per
+        // protocol). They all belong to the boxed value's type, so the first one provides the right retain/release.
+        // Treating the array as a box info read past its end and called an arbitrary pointer.
+        auto confPtrType = typeHelper().protocolConformance()->getPointerTo();
+        auto array = builder().CreateBitCast(boxInfo, confPtrType->getPointerTo());
+        auto conf = builder().CreateLoad(confPtrType, array);
+        fnPtr = builder().CreateConstInBoundsGEP2_32(typeHelper().protocolConformance(), conf, 0, retain ? 3 : 4);
+    }
     else {
         fnPtr = builder().CreateConstInBoundsGEP2_32(typeHelper().boxInfo(), boxInfo, 0, retain ? 1 : 2);
     }
```

## WebAssembly で動かすための変更

バグではありませんが、ブラウザの中で動かすために、公式コンパイラから変えているところです。

### 32 ビットの環境に合わせる

公式コンパイラは、メモリを確保する `malloc` に 64 ビットの大きさを渡します。32 ビットの WebAssembly では型が合わないので、間に 1 つ関数をはさんでいます。

修正パッチ：Compiler/Generation/RunTimeHelper.cpp:

```diff
@@ -111,7 +111,7 @@ void RunTimeHelper::declareRunTime() {
     buildRetainRelease(Type(Type::noReturn(), {}, Type::noReturn()), "callable.boxRetain", "callable.boxRelease",
                        boxInfoCallables_);
 
-    malloc_ = declareRunTimeFunction("malloc", llvm::Type::getInt8PtrTy(generator_->context()),
+    malloc_ = declareRunTimeFunction("ejcMalloc", llvm::Type::getInt8PtrTy(generator_->context()),
                                     llvm::Type::getInt64Ty(generator_->context()));
     malloc_->removeFnAttr(llvm::Attribute::NoRecurse);
     malloc_->addAttribute(llvm::AttributeList::ReturnIndex, llvm::Attribute::NonNull);
```

修正パッチ：runtime/main.cpp:

```diff
@@ -26,6 +26,10 @@ runtime::internal::ControlBlock* runtime::internal::newControlBlock() {
 
 extern "C" runtime::Integer fn_1f3c1();
 
+extern "C" int8_t* ejcMalloc(runtime::Integer size) {
+    return static_cast<int8_t*>(malloc(static_cast<size_t>(size)));
+}
+
 extern "C" int8_t* ejcAlloc(runtime::Integer size) {
     auto ptr = malloc(size);
     *static_cast<runtime::internal::ControlBlock**>(ptr) = new runtime::internal::ControlBlock;
```

クロージャを C++ に渡すときの形も、公式コンパイラは x86-64 の決まりに頼っています。WebAssembly のときだけ、受け取り方を変えています。

修正パッチ：s/String.cpp:

```diff
@@ -123,7 +123,14 @@ extern "C" runtime::SimpleOptional<runtime::Integer> sStringFindFromIndex(String
     return runtime::NoValue;
 }
 
+#ifdef __wasi__
+extern "C" void sStringCodepoints(String *string, void *cbFn, void *cbCapture) {
+    runtime::Callable<void, runtime::Integer, runtime::Integer> cb;
+    void *parts[2] = {cbFn, cbCapture};
+    std::memcpy(&cb, parts, sizeof(parts));
+#else
 extern "C" void sStringCodepoints(String *string, runtime::Callable<void, runtime::Integer, runtime::Integer> cb) {
+#endif
     for (size_t off = 0; off < string->count;) {
         utf8proc_int32_t codepoint;
         auto state = utf8proc_iterate(reinterpret_cast<utf8proc_uint8_t *>(string->characters.get()) + off,
```

### プロセスを起動しない

コンパイラはリンクのために外部のコマンドを起動しますが、ブラウザの中ではできません。リンクは別に用意した WebAssembly のリンカーで行い、`💻`（コマンドの実行）も何もしないようにしています。

修正パッチ：Compiler/Compiler.cpp:

```diff
@@ -93,7 +93,9 @@ void Compiler::LinkPhase::perform(Compiler *compiler) {
     auto runtimeLib = compiler->findBinaryPathPackage(compiler->searchPackage("runtime", SourcePosition()), "runtime");
     cmd << " " << runtimeLib << " -o " << outPath_;
 
+#ifndef __wasi__
     system(cmd.str().c_str());
+#endif
 }
 
 void Compiler::ArchivePhase::perform(Compiler *compiler) {
@@ -102,7 +104,9 @@ void Compiler::ArchivePhase::perform(Compiler *compiler) {
     cmd.append(outPath_);
     cmd.append(" ");
     cmd.append(objectFilePath_);
+#ifndef __wasi__
     system(cmd.c_str());
+#endif
 }
 
 std::string Compiler::searchPackage(const std::string &name, const SourcePosition &p) {
```

修正パッチ：s/System.cpp:

```diff
@@ -36,5 +36,7 @@ extern "C" runtime::SimpleOptional<s::String*> sSystemArg(runtime::ClassInfo*, r
 }
 
 extern "C" void sSystemSystem(runtime::ClassInfo*, s::String *string) {
+#ifndef __wasi__
     std::system(string->stdString().c_str());
+#endif
 }
```

### スレッドなし

ブラウザの中ではスレッドを使わないので、`🧵` は渡したクロージャをその場で実行するだけにしています（[Thread_wasi.cpp](/docs/patches/Thread_wasi.cpp.txt)）。

### コンパイラそのものを WebAssembly にする

Emojicode のコンパイラは LLVM 8 を使っています。LLVM 8 を WebAssembly 向けにビルドするための変更は [llvm-8.0.1-wasi.patch](/docs/patches/llvm-8.0.1-wasi.patch.txt) にあります。
