006 Web Assembly之调试方法

JavaScript/前端
507
0
0
2022-06-12
标签   WebAssembly

0 介绍

视频地址:www.bilibili.com/video/BV1eg411g7c...

相关源码:github.com/anonymousGiga/Rust-and-...

上一节我们对之前写的代码进行了测试,这一节我们来介绍调试方法。

在我们写更多的代码之前,我们希望有一些调试工具来让我们调试代码中的bug。具体的一些工具我们后续介绍。下面我们主要介绍三种调试方法。

1 打开panic 日志

我们的wasm-pack-template附带了一个可选的,默认情况下启用的依赖,该依赖属于console_error_panic_hook包,在wasm-game-of-life/src/utils中配置。我们需要做的就是在初始化函数或者公共代码路径中安装钩子。我们可以在Universe::new构造器中调用,如下:

pub fn new() -> Universe {
utils::set_panic_hook();
// ...
}

2 添加log到我们的游戏中

在Cargo.toml中添加如下代码:

[dependencies.web-sys]
version = "0.3"
features = [
"console",
]

在src/lib.rs中添加:

extern crate web_sys;
// A macro to provide `println!(..)`-style syntax for `console.log` logging.
macro_rules! log {
( $( $t:tt )* ) => {
web_sys::console::log_1(&format!( $( $t )* ).into());
}
}

修改src/lib.rs中的tick函数如下:

//计算下一个滴答的状态
pub fn tick(&mut self) {
let mut next = self.cells.clone();
for row in 0..self.height {
for col in 0..self.width {
let idx = self.get_index(row, col);
let cell = self.cells[idx];
let live_neighbors = self.live_neighbor_count(row, col);
//以下为添加的内容
log!(
"cell[{}, {}] is initially {:?} and has {} live neighbors",
row,
col,
cell,
live_neighbors
);
let next_cell = match(cell, live_neighbors) {
(Cell::Alive, x) if x < 2 => Cell::Dead,
(Cell::Alive, 2) | (Cell::Alive, 3) => Cell::Alive,
(Cell::Alive, x) if x > 3 => Cell::Dead,
(Cell::Dead, 3) => Cell::Alive,
(otherwise, _) => otherwise,
};
//以下为添加的内容
log!(" it becomes {:?}", next_cell);
next[idx] = next_cell;
}
}
self.cells = next;
}

3 使用debugger暂停每个tick

我们在js代码中添加一个js的debugger,如下:

//www/index.js中
function renderLoop() {
debugger;
...
}

3.1 编译

在wasm-game-of-life目录下运行:

wasm-pack build

在www目录下运行:

npm run start

按F12打开网页调试工具,可以进行调试。