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

Can I make custom matlab code-analyser warnings?

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.

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

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