How to check that a method always returns a value

和自甴很熟 提交于 2019-12-07 10:13:02

问题


I wrote a compiler which is already working decently. It checks that all non-void methods do have at least one return statement, but it does not check whether all code paths within a non-void method return a value. So, for example, if I have the following code:

int function(bool a) 
{
     if(a){
         return 5;
     }
}

It will compile "fine" and if a is false, control will drop off the function and keep executing whatever is defined under the function.

Is there some algorithm I can use to perform this check so that I always know if a method is always returning a value? Or will I need to reinvent the wheel?


回答1:


Functions cannot "fall off the end" and start executing code outside of their scope, regardless of whether they return a value or not. It's common to allow the final return statement to be omitted for functions which do not return a result (or in some undisciplined languages even for functions which do return a result), but the function needs to return in all cases.

Given that, the simplest way to produce error messages for non-void functions which fall of the end is:

  • The parser inserts a return statement at the end of the function body.

  • Dead code elimination is used to remove the inserted return statement in case it is unnecessary.

  • Typechecking is used to verify that all return statements, included the inserted one if it hasn't been deleted, are consistent with the return type of the function. (That is, since the generated return statement has no value, it can only be consistent with a void function.)

In this scenario, you need to delete unnecessary return statements before typechecking, or you'll end up with a lot of incorrect error messages. That requires some control flow analysis.

If that's too much work, you can issue the error message at run-time by compiling the no-value return statement as an error operation in the case that the function returns a value.



来源:https://stackoverflow.com/questions/26761063/how-to-check-that-a-method-always-returns-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!