switch 语句设计

在程序设计语言中,switch 是一种常见的分支结构。但是有些脚本语言不支持,比如说lua和neko,现在我程序翻译的阶段分支结构只剩下这个switch 未处理了 , 如果处理他需要考虑的是 SwitchStatement , Case Statement 和 BreakStatement。 有点复杂了。

首先不考虑输入的情况 , 我们写段伪代码模拟一下。

标签A:
条件不满足  && $goto(B);
A代码段
$goto(END);
标签B:
条件不满足  && $goto(C);
B代码段
$goto(END);
标签C:
条件不满足  && $goto(END);
C代码段
条件END:
空代码

思路有了就好办了。

输入:



var isLeapYear = function (y) {
	return (y%4==0&&y%100!=0||y%400==0);
}


var getMonthDay = function (y , m) {
	var d = 30;
	switch (m) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
		d = 31;
		break;
		case 4:
		case 6:
		case 9:
		case 11:
		d = 30;
		break;
		default:
		d = isLeapYear(y)? 29 : 28;
		break;
	}
	return d;
}

console.log(getMonthDay(2000, 2));

经过我们的翻译器优化后:

__exports_defines__symblos__ = $new(null)
var isLeapYear = function (y) { 
return $istrue($istrue(y%4==0)&&$istrue(y%100!=0))||$istrue(y%400==0);
}
var getMonthDay = function (y,m) { 
var d = 30;
m604949256604109342:
$istrue(m!=1)&&$istrue(m!=3)&&$istrue(m!=5)&&$istrue(m!=7)&&$istrue(m!=8)&&$istrue(m!=10)&& $istrue(m!=12) && $goto(m604949553320853319);
 d=31
$goto(m604949230881628819);
m604949553320853319:
$istrue(m!=4)&&$istrue(m!=6)&&$istrue(m!=9)&& $istrue(m!=11) && $goto(m60494984164847712);
 d=30
$goto(m604949230881628819);

m60494984164847712:
d=(if($istrue(isLeapYear (y))) {29} else {28})
$goto(m604949230881628819);

m604949230881628819:
{}
return d;
}
$print (getMonthDay (2000,2))

输出结果:

$ neko example/test.n
29
 

猜你喜欢

转载自my.oschina.net/littlemonkeyc/blog/1794626