拿到錘子的我想在微控制器上面執行 Ruby - 邱政憲

歡迎來到 MOPCON 2020 共筆

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

共筆入口:https://hackmd.io/@mopcon/2020
手機版請點選上方 按鈕展開議程列表。

鐵人賽文章

背景起源

Python 程式遊戲設計

Virtual Machine

語言的虛擬機 = 讓語言在不用平台上執行,不受平台影響

一般語言:Source code => Compiler => Executable
有虛擬機的語言(Ruby):Source code => Compiler => Ruby VM

Compiler

Getting Started

​​​​1 brew install rbenv
​​​​2 rbenv install mruby-2.1.2

先寫點扣:

# app.rb puts "Hello World"
mrbc app.rb
mruby -b app.mrb

mrbc -v app.rb
dump 機器碼(machine code)

IREP

intermediate representation (中間碼)
IR: A語言轉換為B語言
mruby 轉出來的的就是 IR

app.mrb:
RITE Header + IREP + Debug Section
-D: Debug

IREP: ISEQ + Pools + Symbols + IREP
ISEQ: 暫存器的分配
Pools: 字串存放的地方
Symbols: 不能修改的字串,轉成 ID
IREP: block, method 子程式自己的程式、環境

mrb_exec L1VM

約一千行的 ruby VM,複雜度 cruby > mruby > mrb_exec
Stack based VM 比較容易實現

Load Variable (載入變數)

讀取 IREP 時,轉換成 ruby 的變數,mruby 的執行時間複雜度為 O(1)

一般 ruby VM 編譯完的 binary 執行檔為 50 MB
mruby 是 500-600 K
L1VM 是 幾 K

Behind VM

function call

function argument 從 ruby 變數複製出 argv
但 argv 內為一個 pointer 指向實際變數位址

VM 的 pass by value/pass by reference 依 VM 實作而定

Block

Ruby 的 block 是一種參數,可以存取外層變數,並能像遞迴一樣呼叫

linter

linter 會依照 VM 實作,限制某些語言的寫法(ex. block 行數)

Hardware

根據微控制器所提供的 SDK,開發更加便利
在沒有 hardware knowledge 寫 hardware 的驅動程式是最困難的

HAL: 支援在不同硬體上執行

Conclusion

在有限的執行資源上(微控制器),實作應用是件有趣的事

瞭解語言底層的相關設計

tags: MOPCON 2020
Select a repo