Add a utility for generating Rust 'match' expressions.

This makes it a little simpler to generate 'match' statements, and
it performs deduplication of identical arms. And it means I don't
have to think about as many strings like '{} {{ {}.. }} => {}'
when I'm trying to think about how instructions work :-).
This commit is contained in:
Dan Gohman
2018-03-14 10:40:47 -07:00
parent d9712f5d7d
commit 272d03d8fc
3 changed files with 157 additions and 82 deletions

View File

@@ -57,12 +57,11 @@ def gen_getter(setting, sgrp, fmt):
ty = camel_case(setting.name)
proto = 'pub fn {}(&self) -> {}'.format(setting.name, ty)
with fmt.indented(proto + ' {', '}'):
with fmt.indented(
'match self.bytes[{}] {{'
.format(setting.byte_offset), '}'):
for i, v in enumerate(setting.values):
fmt.line('{} => {}::{},'.format(i, ty, camel_case(v)))
fmt.line('_ => panic!("Invalid enum value"),')
m = srcgen.Match('self.bytes[{}]'.format(setting.byte_offset))
for i, v in enumerate(setting.values):
m.arm(str(i), [], '{}::{}'.format(ty, camel_case(v)))
m.arm('_', [], 'panic!("Invalid enum value")')
fmt.match(m)
else:
raise AssertionError("Unknown setting kind")