Matlab代码分析器对如何纠正错误和效率低下有很多不错的建议,但是有时我会遇到一些我想被分析仪发现的情况。具体来说,我正在考虑如下代码:
if numel(list > x)
...
end
我无法想到需要使用上述代码而使用以下代码的任何情况:
if numel(list) > x
...
end
是经常使用的。
我浏览了代码分析器可能警告我的所有可能事项,但我没有发现这种可能性。
所以我的问题是:是否可以在代码分析器中添加我自己的警告?
我意识到,如果可能的话,这可能是一项艰巨的任务,那么对于特定问题的任何替代方案或解决方法建议也将不胜感激!
最佳答案
我不相信有一种方法可以为MATLAB Code Analyzer添加新的代码模式。您所能做的就是设置显示或隐藏现有警告。
我不确定代码分析可能使用哪种第三方工具,而自己创建通用分析器将是相当艰巨的。但是,如果要尝试在代码中突出显示一些非常具体,定义明确的模式,则可以尝试使用regular expressions(提示恐怖的音乐和尖叫声)来解析它。
这通常很困难,但可行。作为示例,我编写了这段代码来查找您上面提到的模式。进行此类操作时经常需要管理的一件事是考虑一组封闭的括号,我首先通过删除不感兴趣的括号对及其内容来处理这些括号:
function check_code(filePath)
% Read lines from the file:
fid = fopen(filePath, 'r');
codeLines = textscan(fid, '%s', 'Delimiter', '\n');
fclose(fid);
codeLines = codeLines{1};
% Remove sets of parentheses that do not encapsulate a logical statement:
tempCode = codeLines;
modCode = regexprep(tempCode, '\([^\(\)<>=~\|\&]*\)', '');
while ~isequal(modCode, tempCode)
tempCode = modCode;
modCode = regexprep(tempCode, '\([^\(\)<>=~\|\&]*\)', '');
end
% Match patterns using regexp:
matchIndex = regexp(modCode, 'numel\([^\(\)]+[<>=~\|\&]+[^\(\)]+\)');
% Format return information:
nMatches = cellfun(@numel, matchIndex);
index = find(nMatches);
lineNumbers = repelem(index, nMatches(index));
fprintf('Line %d: Potential incorrect use of NUMEL in logical statement.\n', ...
lineNumbers);
end
% Test cases:
% if numel(list < x)
% if numel(list) < x
% if numel(list(:,1)) < x
% if numel(list(:,1) < x)
% if (numel(list(:,1)) < x)
% if numel(list < x) & numel(list < y)
% if (numel(list) < x) & (numel(list) < y)
注意,我在文件底部的注释中添加了一些测试用例。当我自己运行此代码时,我得到了:
>> check_code('check_code.m')
Line 28: Potential incorrect use of NUMEL in logical statement.
Line 31: Potential incorrect use of NUMEL in logical statement.
Line 33: Potential incorrect use of NUMEL in logical statement.
Line 33: Potential incorrect use of NUMEL in logical statement.
请注意,列出了与错误代码匹配的第一个,第四个和第六个测试用例的消息(第六个测试用例的两倍,因为该行有两个错误)。
这会在所有可能的情况下起作用吗?我会假设不是。您可能必须增加正则表达式模式的复杂性才能处理其他情况。但这至少可以作为您解析代码时必须考虑的事情的一个示例。
关于matlab - 我可以制作自定义的matlab代码分析警告吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41242635/