mita icon indicating copy to clipboard operation
mita copied to clipboard

Short-circuit function returns

Open wegendt-bosch opened this issue 6 years ago • 0 comments

Say a function returns just another function:

fn foo() {
    return bar();
}
fn bar() {
    return 4;
}

Currently this translates to the very verbose C code:

Retcode_T foo(int32_t* _result)
{

	Retcode_T exception = NO_EXCEPTION;
	
	
	int32_t result147049396;
	exception = bar(&result147049396);
	if(exception != NO_EXCEPTION) return exception;
	
	*_result = result147049396;
	return exception;

	return exception;
}

Retcode_T bar(int32_t* _result)
{

	Retcode_T exception = NO_EXCEPTION;
	
	
	*_result = 4;
	return exception;

	return exception;
}

Ignoring the duplicate return exception there is an obvious improvement here: since we directly return a function result, we can ignore all that exception stuff (unless we are in try-catch) and don't need to copy the result, cleaning up generated code:

Retcode_T foo(int32_t* _result)
{

	Retcode_T exception = NO_EXCEPTION;
	
	return bar(result);

	return exception;
}

In try-catch it's a bit more complicated, but we don't need to copy the result, we can directly pass in the result variable:

Retcode_T foo(int32_t* _result)
{

	Retcode_T exception = NO_EXCEPTION;
	bool returnFromWithinTryCatch = false;
	
	
	// TRY
	returnFromWithinTryCatch = false;
	for(bool _runOnce212050329 = true; _runOnce212050329; _runOnce212050329 = false)
	{
		exception = bar(result);
		if(exception != NO_EXCEPTION) break;
		
		returnFromWithinTryCatch = true;
		break;
	}
	// CATCH Exception
	if(exception != NO_EXCEPTION)
	{
		exception = NO_EXCEPTION;
		for(bool _runOnce212050329 = true; _runOnce212050329; _runOnce212050329 = false)
		{
		}
	}
	if(returnFromWithinTryCatch || exception != NO_EXCEPTION) {
	return exception;
	}

	return exception;
}

wegendt-bosch avatar May 25 '18 12:05 wegendt-bosch