2016-12-20 64 views
6

對於如何糾正錯誤和低效率,matlab代碼分析器有很多不錯的建議,但我有時會遇到我希望被分析器捕獲的情況。特別是我想到的是類似於下面的代碼:我可以自定義matlab代碼分析器警告嗎?

if numel(list > x) 
    ... 
end 

我不能把我的頭頂部想到這裏我需要使用上面的代碼的任何情況,而下面的代碼:

if numel(list) > x 
    ... 
end 

經常使用。

我查看了代碼分析器可能警告我的可能事情列表,但我沒有發現這種可能性。

所以我的問題是:是否有可能將我自己的警告添加到代碼分析器,如果是這樣,如何?

我意識到,如果有可能這可能是一項艱鉅的任務,所以對於具體問題的任何替代方案或解決方法建議也將不勝感激!

+0

你應該看看這篇文章(http://undocumentedmatlab.com/blog/parsing-mlint-code-analyzer-output) – obchardon

回答

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. 

注意一條消息被列在第一,第四和第六測試匹配您的錯誤代碼(兩次第六測試用例的情況下,由於是這條線上的兩個錯誤)。

這會適用於所有可能的情況嗎?我會假設沒有。您可能不得不增加正則表達式模式的複雜性來處理其他情況。但至少這可能是解析代碼時必須考慮的事情的一個例子。

相關問題