Merge pull request #92 from ashleygwilliams/node-modules

feat(node): support node enums
This commit is contained in:
Alex Crichton 2018-03-29 17:27:21 +02:00 committed by GitHub
commit 31107db86d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 3 deletions

View File

@ -1565,9 +1565,21 @@ impl<'a, 'b> SubContext<'a, 'b> {
for variant in enum_.variants.iter() {
variants.push_str(&format!("{}:{},", variant.name, variant.value));
}
self.cx.globals.push_str(&format!("export const {} = {{", enum_.name));
self.cx.globals.push_str(&variants);
self.cx.globals.push_str("}\n");
let global_export = if self.cx.config.nodejs {
let mut enum_string = format!("const {} = Object.freeze({{", enum_.name);
enum_string.push_str(&variants);
enum_string.push_str("})\n");
let export = format!("module.exports.{} = {};\n", enum_.name, enum_.name);
enum_string.push_str(&export);
enum_string
} else {
let mut enum_string = format!("export const {} = {{", enum_.name);
enum_string.push_str(&variants);
enum_string.push_str("}\n");
enum_string
};
self.cx.globals.push_str(&global_export);
self.cx.typescript.push_str(&format!("export enum {} {{", enum_.name));
variants.clear();

View File

@ -39,6 +39,21 @@ fn works() {
self.contents
}
}
#[wasm_bindgen]
pub enum Color {
Green,
Yellow,
Red,
}
#[wasm_bindgen]
pub fn cycle(color: Color) -> Color {
match color {
Color::Green => Color::Yellow,
Color::Yellow => Color::Red,
Color::Red => Color::Green,
}
}
"#)
.file("test.js", r#"
const assert = require('assert');
@ -68,6 +83,14 @@ fn works() {
assert.strictEqual(r2.add(1), 1);
assert.strictEqual(r2.add(2), 2);
r2.free();
var Color = run.Color;
assert.strictEqual(Color.Green, 0);
assert.strictEqual(Color.Yellow, 1);
assert.strictEqual(Color.Red, 2);
assert.strictEqual(Object.keys(Color).length, 3);
assert.strictEqual(Color.cycle(Color.Green), Color.Yellow);
};
"#)