How to tell if Matlab code is syntactically valid?

matlab, parsing

Solution

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/')

Problem

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.

Original source

Related problems