changeset 97:59a94f3ad56f

Added short-circuit && and || operators
author Mike Pavone <pavone@retrodev.com>
date Thu, 26 Jul 2012 23:40:56 -0700
parents 84b65ee8b78b
children 094227f2f64e
files cbackend.js compiler.js modules/false.tp modules/true.tp samples/logical.tp
diffstat 5 files changed, 41 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/cbackend.js	Thu Jul 26 18:54:42 2012 -0700
+++ b/cbackend.js	Thu Jul 26 23:40:56 2012 -0700
@@ -13,7 +13,7 @@
 }
 
 op.prototype.toC = function(isReceiver) {
-	var optoMeth = {'+': 'ADD_', '-': 'SUB_', '*': 'MUL_', '/': 'DIV_', '%': 'MOD_', '=': 'EQ_', '!=': 'NEQ_', '<': 'LT_', '>': 'GT_', '>=': 'GEQ_', '<=': 'LEQ_', '.': 'CAT_'};
+	var optoMeth = {'+': 'ADD_', '-': 'SUB_', '*': 'MUL_', '/': 'DIV_', '%': 'MOD_', '=': 'EQ_', '!=': 'NEQ_', '<': 'LT_', '>': 'GT_', '>=': 'GEQ_', '<=': 'LEQ_', '.': 'CAT_', '&&':'if', '||':'ifnot'};
 	var method = optoMeth[this.op];
 	return 'mcall(' + getMethodId(method) + '/* ' + method + ' */, 2, (object *)' + this.left.toC() + ', ' + this.right.toC() + ')\n';
 };
--- a/compiler.js	Thu Jul 26 18:54:42 2012 -0700
+++ b/compiler.js	Thu Jul 26 23:40:56 2012 -0700
@@ -296,6 +296,12 @@
 
 op.prototype.populateSymbols = function(symbols, isReceiver) {
 	this.left.populateSymbols(symbols);
+	if (this.op == '&&' || this.op == '||') {
+		//&& and || are syntactic sugar for if and ifnot with
+		//the second argument transformed into a lambda to
+		//achieve short-circuit evalutation
+		this.right = new lambda([], [this.right]);
+	}
 	this.right.populateSymbols(symbols);
 };
 
--- a/modules/false.tp	Thu Jul 26 18:54:42 2012 -0700
+++ b/modules/false.tp	Thu Jul 26 23:40:56 2012 -0700
@@ -2,6 +2,9 @@
 	if <- :self trueblock {
 		self
 	}
+	ifnot <- :self falseblock {
+		falseblock:
+	}
 	if:else <- :self trueblock :elseblock {
 		elseblock:
 	}
--- a/modules/true.tp	Thu Jul 26 18:54:42 2012 -0700
+++ b/modules/true.tp	Thu Jul 26 23:40:56 2012 -0700
@@ -2,6 +2,9 @@
 	if <- :self trueblock {
 		trueblock:
 	}
+	ifnot <- :self falseblock {
+		self
+	}
 	if:else <- :self trueblock :elseblock {
 		trueblock:
 	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/samples/logical.tp	Thu Jul 26 23:40:56 2012 -0700
@@ -0,0 +1,28 @@
+#{
+
+	foo <- {
+		print: "foo\n"
+		true
+	}
+	
+	bar <- {
+		print: "bar\n"
+		false
+	}
+	
+	baz <- {
+		print: "baz\n"
+		true
+	}
+	
+	qux <- {
+		print: "shouldn't be printed\n"
+		true
+	}
+	
+	
+	main <- {
+		foo && bar || (baz || qux)
+	}
+
+}