如何判断Matlab代码在语法上是否有效? [英] How to tell if Matlab code is syntactically valid?

查看:202
本文介绍了如何判断Matlab代码在语法上是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Matlab解析器,使用Matlab中央文件交换中的一堆代码作为测试数据.在筛选其中的一些内容时,我发现我合法下载的某些代码不应该解析(即Matlab本身不接受).

I'm working on a parser for Matlab, using a whole bunch of code from the Matlab Central File Exchange as test data. While sifting through some of it, I found that some of the code I downloaded legitimately shouldn't parse (i.e. Matlab itself won't accept it).

是否有一种简单的方法来检查m文件(函数或脚本)是否包含语法错误-也许是某些库函数?我不想运行代码,只是看看它是否应该解析.

Is there an easy way to check if an m-file (either function or script) contains syntax errors -- perhaps some library function? I'm not looking to run the code, just see if it should parse.

推荐答案

如果您愿意使用未记录的功能,请考虑以下事项:

If you are willing to use undocumented functions, consider the following:

function isValid = checkValidMFile(file_name)
    % make sure file can be found
    fname = which(file_name);
    assert(~isempty(fname) && exist(fname,'file')~=0, 'file not found');

    % parse M-file and validate
    t = mtree(fname, '-file');
    if count(t) == 0 || (count(t)==1 && iskind(t,'ERR'))
        isValid = false;
    else
        isValid = true;
    end
end

(您还可以向其传递一个MATLAB语言代码字符串,而不是保存的文件名).

(You could also pass it a string of MATLAB language code instead of a saved file name).

当然mtree将提供很多信息,它实际上可以返回解析树,以及任何警告或错误.我以前曾用它来区别脚本与函数,以及

Of course mtree will give a lot more information, it can actually return the parse tree, as well as any warnings or errors. I have previously used it to differentiate between scripts vs. functions, and to strip all comments from an M-file.

很遗憾,它没有得到官方的支持,因此您必须浏览其源代码以了解一切的含义(很遗憾,它得到了很好的注释).该功能使用内部的mtreemex MEX功能.

It is unfortunately not officially supported, so you will have to browse its source code to figure out what everything means (thankfully it is well commented). The function uses the internal mtreemex MEX-function.

其他(未记录)方式:

builtin('_mcheck', 'some_file.m')

checkSyntacticWarnings('./path/to/folder/')

这篇关于如何判断Matlab代码在语法上是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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