我可以制作自定义的matlab代码分析器警告吗?

时间:2016-12-20 12:42:04

标签: matlab code-analysis

matlab代码分析器有很多关于如何纠正错误和低效率的好建议,但我有时会遇到我希望被分析器捕获的情况。具体来说,我正在考虑如下代码:

if numel(list > x)
  ...
end

我无法想到我需要使用上述代码的任何情况,而以下代码:

if numel(list) > x
  ...
end
经常使用

我查看了代码分析器可以警告我的可能事项列表,但我没有发现这种可能性。

所以我的问题是:是否有可能将自己的警告添加到代码分析器中,如果是,如何添加?

我意识到如果可能这可能是一项艰巨的任务,那么对于特定问题的任何替代方案或解决方案建议也将受到赞赏!

1 个答案:

答案 0 :(得分:2)

我不相信有一种方法可以为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.

请注意,列出了与您的错误代码匹配的第一,第四和第六个测试用例的消息(第六个测试用例的两次,因为该行有两个错误)。

这适用于所有可能的情况吗?我不会假设。您可能必须增加正则表达式模式的复杂性以处理其他情况。但至少这可以作为解析代码时必须考虑的事情的一个例子。

相关问题