如何检查方法是否始终返回值 [英] How to check that a method always returns a value

查看:70
本文介绍了如何检查方法是否始终返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个已经可以正常工作的编译器。它检查所有非void方法是否至少具有一个return语句,但不检查非void方法内的所有代码路径是否返回值。因此,例如,如果我有以下代码:

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;
     }
}

它将编译为 fine,如果a为假,控件将放弃该功能,并继续执行该功能下定义的内容。

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?

推荐答案

函数不能落空并开始在其范围之外执行代码,无论它们是否返回值或返回值。不。对于不返回结果的函数(或者对于某些返回结果的函数,也可以使用一些不成规则的语言),通常会省略最后的 return 语句,但是

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:


  • 解析器在函数主体的末尾插入 return 语句。

消除死代码用于删除插入的 return 语句,以防不必要。

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

类型检查用于验证所有 return 语句(包括未删除的插入语句)是否一致函数的返回类型。 (也就是说,由于生成的 return 语句没有任何值,因此只能与 void 函数保持一致。)

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.

这篇关于如何检查方法是否始终返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆