我不相信有一種方法可以爲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.
注意一條消息被列在第一,第四和第六測試匹配您的錯誤代碼(兩次第六測試用例的情況下,由於是這條線上的兩個錯誤)。
這會適用於所有可能的情況嗎?我會假設沒有。您可能不得不增加正則表達式模式的複雜性來處理其他情況。但至少這可能是解析代碼時必須考慮的事情的一個例子。
你應該看看這篇文章(http://undocumentedmatlab.com/blog/parsing-mlint-code-analyzer-output) – obchardon