I'm working on a parser for Matlab, using a whole bunch of code from the Matlab Central File Exchange as test data. While sifting through some of it, I found that some of the code I downloaded legitimately shouldn't parse (i.e. Matlab itself won't accept it).
Is there an easy way to check if an m-file (either function or script) contains syntax errors -- perhaps some library function? I'm not looking to run the code, just see if it should parse.
If you are willing to use undocumented functions, consider the following:
function isValid = checkValidMFile(file_name)
% make sure file can be found
fname = which(file_name);
assert(~isempty(fname) && exist(fname,'file')~=0, 'file not found');
% parse M-file and validate
t = mtree(fname, '-file');
if count(t) == 0 || (count(t)==1 && iskind(t,'ERR'))
isValid = false;
else
isValid = true;
end
end
(You could also pass it a string of MATLAB language code instead of a saved file name).
Of course mtree
will give a lot more information, it can actually return the parse tree, as well as any warnings or errors. I have previously used it to differentiate between scripts vs. functions, and to strip all comments from an M-file.
It is unfortunately not officially supported, so you will have to browse its source code to figure out what everything means (thankfully it is well commented). The function uses the internal mtreemex
MEX-function.
Additional (undocumented) ways:
builtin('_mcheck', 'some_file.m')
and
checkSyntacticWarnings('./path/to/folder/')
Since 2011b the way to parse Matlab code is via checkcode
. In older versions of Matlab you can use mlint
(in R2013a+, and maybe earlier, this command just calls checkcode
). Both of these rely on a private undocumented function called mlintmex
. You can learn a bit more about this function and related topics on the Undocumented Matlab website.
Another potentially-related project is Linguist, which is used by GitHub and others to classify languages and uses pygments.rb to highlight code. It supports Matlab. A while back the Matlab support used to be hit-or-miss, but I think that it has improved. These won't validate code, but they may be useful for what you're doing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With