Table of Contents

Code Checker for MATLAB

Table of Contents


Troubleshooting

Datatype Detection

Introduction

What is CC4M?

CC4M is a tool to easily check your MATLAB Code, Simulink Models, and Stateflow Charts against your company's or your team's coding standard. CC4M includes a convenient approach to easily configure and run checks. Furthermore, CC4M provides an M-Code analyzer to enable running checks on variables and functions as easy as checks on Simulink and Stateflow properties.

Concept

CC4M includes an M-code analyzer that is separated from the configurable checks infrastructure in such a way that the checks can reuse the results of the M-code analyzer.

Along with six reports (defined variables, defined functions, a dependency report, a list of all required mex-files, a report on cyclomatic complexity, and a report of == and ~= comparisons) a set of configurable checks is provided. The configuration of these checks is performed via a configuration file that can be edited interactively. On the roadmap even support for custom, user-defined checks is mentioned. If you are interested in having your own checks, please contact us at info@monkeyproofsolutions.nl.

The combination of the configuration file, the collection of checks and the M-code analyzer output together are the input for the checker (see figure Architecture of CC4M). The checker generates the report containing the results of all checks as configured via the configuration file and applied to the analyzed code. The interactive report contains links to the rule violations in your code, to the configuration file representing your MATLAB coding rules, and to the coding standards whose standards and rules are reflected by the configuration file.

CC4M can be used with a standard license and a Pro license. The Pro license features are about the MATLAB command window interface, for more information about these features see section Pro features.

Architecture of CC4M. Note that “Custom checks” are only available via services.

Getting Started

Installation

CC4M is provided as a MATLAB Toolbox CodeCheckerForMATLAB_vxxx.mltbx. To install the toolbox, double click the add-on installation file in the MATLAB Current Folder browser. Alternatively, install CC4M from the command window using   matlab.addons.toolbox.installToolbox. The add-on installation procedure gives no hint on whether the installation is successful, but you can continue directly after installing CC4M. The files are installed in the Add-Ons folder that is configured in the Preferences on the MATLAB > Add-Ons tab.

Once CC4M is installed as an add-on in one MATLAB version, it is available in every MATLAB installation on your system that is configured to have add-ons in the selected installation folder.

Complete and verify installation: check M-code

To verify that the installation is successful, run monkeyproof.cc4m.start. The following application should appear after you have activated your license:

image

Now you can specify what to check and start the run. The different options are discussed in further detail in section The CC4M user interface.

During the first call, the installation procedure is completed. This includes creating a default configuration - having all checks enabled with default parameter values, priority and severity level. After installation the predefined configuration MonkeyProof MATLAB Coding Standard++ becomes active. For more information on check configurations, see Configuration.

Shortcut for the MATLAB Editor

Calling monkeyproof.cc4m.start for the first time creates a shortcut in the MATLAB Shortcuts Toolstrip. The shortcut opens the CC4M user interface. It will show up in the top-right corner of MATLAB: image

For MATLAB releases prior to R2018a, the shortcut is not automatically available on the quick access toolbar. To add the shortcut to the quick access toolbar, edit the shortcut and select the "Add to quick access toolbar" option. To add a label to the shortcut, select the "Show label on quick access toolbar" option. For more information see MATLAB documentation.

Getting help and reporting feedback

For questions, feedback or issues, please refer to the Code Checker for MATLAB forum. Please add the summary of your question or issue in the post's subject, and put a detailed description, if applicable the steps to reproduce, additional information (at least the CC4M and MATLAB version) and the priority you have with the question/issue in the contents of the post.

In case of errors, please include the full error message and -if possible- also include the file or model that triggers the error when analyzed or checked so that the problem can be reproduced (and fixed).

License Dialog

image

License Information

  • License ID The license ID is a unique reference to the license, created when the license was purchased.
  • Activation ID The activation is a unique reference to an activation, created when the license was activated.
  • License status Shows the current status of the license (validity and activation). If the text in this field is red, either action is required or an error occurred.
    • No license The license file has not been found: use the "Change product key" and specify the requested details.
    • Validation: LICENSE_VALID  Activation: ACTIVATION_REQUIRED The license needs to be activated: use the "Activate" button.
    • Other Go to the support forum for assistance.
  • Expiration date This is the expiration date of the license. Maintenance can be purchased in the webshop.

User Information

  • Name Name of the user to which the product is licensed.
  • Email Email address used to purchase the license.
  • Company Company of the licensee.

Change Product Key

Specify the product key sent to you by email and the user's name and company as were specified during purchase.

image

Activate

When the Activate button is clicked, the Activation Dialog appears. It shows the end user license agreement, which needs to be accepted to activate the license.

Deactivate

Deactivates the license to make it available for activation on another machine. The number of allowed deactivations is limited.

Show Hardware IDs

The Hardware IDs dialogs shows the IDs of a number of properties that can be used for offline activation. The right-click menu offers the option to copy all IDs to the clipboard.

image

Enter Modification Key

If you receive a license modification key, you can enter it here.

image

Show EULA

Shows the end user license agreement.

User Guide

Using CC4M from MATLAB

For a quick introduction on how to check your code using CC4M, see this video. The tool runs by clicking the shortcut (see section Shortcut for the MATLAB Editor) or is started from the command-line calling monkeyproof.cc4m.start. More information on the user interface is given in section The CC4M user interface. The checker allows for checking one or more selected files, files in a folder (and its sub-folders) or a MATLAB Project. A choice can be made between checking all files or only those with local changes with respect to a SubVersion or GIT repository.

Supported file types are:

  • MATLAB code (.m)
  • Live Editor files (.mlx)
  • App Designer apps (.mlapp)
  • Simulink models (.slx, .mdl)
    • MATLAB Function blocks
    • MATLAB Functions in Stateflow Charts

For all file types except .m limitations apply as described in section Live Editor files, App Designer files and Simulink models. For obvious reasons, p-code files (obfuscated versions of m-code files) cannot be analyzed by CC4M.

Results from the metrics and all checks are shown in one result report. This result report contains the following sections:

  • Meta data
  • Summary
  • Results
  • Additional information
    • List of checks and parameters with missing/duplicate configurations.
    • List of disabled checks.
    • List of toolboxes installed.

The content of most of these sections is described in section Metrics. Upon running CC4M, the report is saved as a webpage (.html) in the reports folder automatically for future reference. The report will be given a unique name based on a timestamp.

When running CC4M for the first time (see section Complete and verify installation), the reports folder is created at a default location. For Windows this is:

%APPDATA%\Roaming\cc4m\cc4m_reports

For Mac this is:

~/Library/Application Support/cc4m/cc4m_reports

For Linux this is:

~/.matlab/cc4m/cc4m_reports

The reports folder can be changed or requested from the command line or the GUI. See Function Reference for an overview of the options.

The checks are directly accessible from the Model Advisor. There are two ways to use the checks within the Model Advisor; either configure the checks within the Model Advisor, or select a configuration from the GUI. To configure and run the checks from the Model Advisor, use the CC4M node in the "By Product" section of the tree (see figures Options to use-(a) and Example to configure). Furthermore, the predefined configurations shipped CC4M and your own configurations are available from the "CC4M Tasks" section, see figure Options to use-(b) .

(a)

(a)

(b)

(b)

Options to use the Model Advisor: (a) - configure from the Model Advisor or (b) - run the configurations from the GUI.

Example to configure and run a check from the “By Product” node. The report shown is generated from the sldemo_radar_eml example model. This model includes MATLAB Function blocks and is shipped as a demo with Simulink.

The CC4M user interface

The graphical user interface of CC4M on startup is shown in the figure below. It can be opened by entering monkeyproof.cc4m.start() in your command window or using the shortcut. The GUI consists of a number of tabs, each with multiple controls. This section describes all of them.

General tab of the CC4M GUI on startup

General

The General tab lets you select what files to check. The first step is to select whether you would like to check a file, folder, or MATLAB project. After making a selection, the relevant controls are shown. The controls for each of the options are shown in the figure below.

General tab of the GUI after choosing to check a file, folder or MATLAB project

File

After clicking File, several controls are shown.

  • By selecting Active in editor on the top switch, CC4M automatically selects the currently active file in the MATLAB editor. When the switch is set to Browse, the selected file(s) shown in the text field will be checked by CC4M.

  • The image button is used to browse for the file(s) to run CC4M on. You can browse for any file with extension .m, .mlx, .mlapp, .slx or .mdl. It is allowed to select multiple files. The results of all checked files are placed in one report. The files can also be selected by entering them in the text field. Multiple files can be selected this way by separating them with semicolons. Non-existing files will result in a warning and the image button will be disabled until the selection is valid.

  • The switch labeled Changed files only (when enabled: image) allows you to narrow the selection of files by only running CC4M on the selected files that have changed locally with respect to your Git or SVN repository. For this option, all selected files must be within the same repository. When disabled (image), selected files are checked regardless of their status with respect to the repository.

  • The bottom switch, Ignore exemptions allows you to switch off all exemptions to coding standards in your code for the duration of the run. For more information on exemptions, see section Exemptions. The behaviour of this switch is equal for all three options (File, Folder, Project).

Folder

If you would like to check the code of files in a folder, select the Folder at the top.

  • By selecting Current directory on the top switch, CC4M automatically selects the current directory for checking. When the switch is set to Browse, the selected folder shown in the text field will be checked by CC4M.

  • The image button can be used to browse for the folder to run CC4M on. Similar to the File option described above, the folder can also be selected by entering it in the text field.

  • Include subfolders, when turned on, selects the m-files in the selected folder and in all subfolders. This option can be very useful for checking an entire codebase, or a section thereof.

  • Narrow the selection of files to check by enabling the Changed files only switch if desired. The selected folder must be (in) a repository for this to work. If the folder contains the repository in a subdirectory, no changed files are found.

Project

MATLAB projects provide a convenient way to set the bounds of your code and to define startup and shutdown tasks (among others). By selecting the Project option in CC4M, you can easily check the files of a project.

  • Select Current project to have CC4M check the project that is currently open (if any). If there is no project open, the run cannot be started. This is also shown in the figure. By selecting Browse, the project file shown in the textfield will be checked.

  • Use the image button to browse for a project to check (.prj file). Alternatively, enter the absolute path of the project file in the textfield.

  • Project files to be checked can be filtered by enabling the Skip files labeled 'Test' option. This removes all files labeled Test from the list of files that will be checked. Test files do not always have to meet (the same) coding standards as other files do. Applying the label to your test files is also useful for easily generating a testsuite for the project.

  • The files to check can be further filtered by enabling Changed files only. This supports filtering files in the project based on their Git or SVN status. The selection includes files added to the project that have not yet been committed. In the case of a Git repository, uncommitted changes and staged changes are considered 'changes'. Newly added files need to be staged to be considered as 'changes'. If your changes have been committed locally, they will not be checked by CC4M if the Changed files only option is enabled.

After choosing the right options and starting the run, the selected project will be loaded if it is not loaded yet. You will be prompted to agree to this. Please note that because only one MATLAB project can be open at a time, loading a project closes any other open project.

MATLAB projects were introduced in MATLAB R2019a. If you are using a release older than that, the Project option will be disabled.

Starting the run

Once all settings are valid, the image button will be enabled. This button is available on every tab in the GUI. After clicking it, the settings are applied and CC4M will run the checks on the files you selected using the rule configurations file of your choice. This action hides the GUI. Before running the checks on the files or folders you have selected, the code to check will be temporarily added to the MATLAB path so that the relevant information for properly performing the code analyses is available. During the analysis, property values may be initialized when gathering class information, if the checked code has class definitions among them. This may cause unexpected behaviour if the calculation of the initial values of properties deals with peripherals such as printing to the command window or reading from or writing to files. Potential errors during the initialization of properties are caught and will not interfere with the code analysis.

After analyzing the report and applying changes accordingly, you might want to run CC4M again to make sure the code satisfies the coding standards. Opening the GUI again using the shortcut or monkeyproof.cc4m.start()within the same MATLAB session restores the selected GUI settings so that the same file(s) can easily be checked again. Alternatively, use the rerun all button in the report that was generated as described in section Rerun functionality.

Configuration

The Configuration tab shown in figure Configuration tab of the CC4M GUI is used to select the rule configuration file that is used for checking your code. A rules configuration file is an xml file that can be used to map your own MATLAB coding standard onto the checks and reports of CC4M. When running CC4M for the first time after installation (see section Complete and verify installation), the default configuration is created in the default folder that contains the configurations. For Windows this is:

    %APPDATA%\Roaming\cc4m\cc4m_configurations

For Mac:

    ~/Library/Application Support/cc4m/cc4m_configurations

for Linux:

    ~/.matlab/cc4m/cc4m_configurations

After installing the CodeChecker, the predefined configuration MonkeyProof MATLAB Coding Standard++ becomes active. For more information on configuring checks, see section Configuring checks.

Configuration tab of the CC4M GUI

When the top switch is set to Custom, it means that a custom configuration file is selected for use during the checks. When the switch is set to Predefined, a configuration shipped with CC4M will be used to run the checks. Choosing this option hides the configurations folder selection and Import rules configuration file(s) controls as they are irrelevant for predefined configurations. The window you see will look like the one shown in the figure below. For more information on predefined configurations, see section Predefined Configurations.

  • The image button is used to select a folder in which your rules configuration files are stored locally. The folder can also be selected by typing it in the text field. Typing a non-existent folder will result in a warning and the image button will be disabled until the selection is valid. If the selected folder exists, but contains no xml files, a warning and an additional button 'Place default configuration in selected folder' will be shown. Upon clicking this button, a configuration file with default settings will be placed in the selected configuration folder. Selecting a configuration folder is unavailable as long as the switch at the top of the tab is set to Predefined.

  • The Import rules configuration file(s) option can be used to import one or multiple configuration files from for example a network drive to the configurations folder you selected above. Clicking this button will open a dialog that lets you choose any number of xml files. Upon clicking Open, the selected files are copied to the rules configurations folder you selected. If any of the configuration files to import already exists in the destination folder, you will be asked whether or not to overwrite them. By importing a rules configurations file instead of directly linking to it, you still have access to it, even if there is no internet connection or if it changes. This button is unavailable as long as the switch at the top of the tab is set to Predefined.

  • The dropdown box under Rule configurations file lets you select a configuration file that is in the selected configurations folder. If the switch at the top of the tab The contents of this file are used to apply your coding rules to CC4M. Click the Open button next to the dropdown box to open the selected configurations file in the Configuration Editor. This lets you interactively edit the configuration file as described in section Configuration Editor. Click the New button next to the Open button to create a new configuration file. For MATLAB R2020b and newer, the description of the configuration set/file is shown below the dropdown box.

  • Under Run checks by priority, you can filter the checks you wish to run by the priority you appointed to each of them. At least one of the boxes must be checked. Information on this selection is also shown in the meta data of the report.

Configuration tab of the CC4M GUI after switching to a predefined configuration

Report

The Report tab, as shown in the figure below lets you change the folder in which the HTML reports generated by CC4M will be stored. If the entered folder does not exist, the folder and at most one parent will be created for you. In addition, there are some options that let you choose what to show in the report that is generated after the run:

  • By default, only check results show up in the HTML report. By enabling Include metrics, you can have CC4M include useful information such as a list of functions, a list of variables and a list of complexity values per function in the HTML report.

  • Use the Include passed checks option to have CC4M include entries for all checks in the HTML report, regardless of whether any violations were reported for them.

  • Use the dropdown menu to select the number of entries to show in the check result table.

Report tab of the CC4M GUI

Preferences

On the Preferences tab, you can turn certain options on or off. The preferences available are listed below. These preferences can also be obtained and changed via the command line interface.

  • Switch on Hide the user interface when starting a run to have the CC4M user interface hide itself when the Run button is clicked. The user interface can be shown again using the shortcut (see section Shortcut for the MATLAB Editor) or the monkeyproof.cc4m.start command. Set the preference via the command line :

    monkeyproof.cc4m.setPreference('HideGuiOnRun', true);
    
  • Switch the Run unconfigured checks to the right to have CC4M run checks that are not in the selected configuration file. Default values are used for those checks. You can add unconfigured checks to your configuration file as described in section Update the configuration file. Set the preference via the command line :

    monkeyproof.cc4m.setPreference('EnableUnconfiguredChecks', true);
    
  • Use the Open reports in a new tab preference to have CC4M open its reports in a new tab instead of in the currently active tab of the MATLAB web browser (if any). This allows you to compare the results of multiple reports. It must be noted that auto-fixes and the rerun functionality will only work for the most recently generated report. Set the preference via the command line :

    monkeyproof.cc4m.setPreference('OpenReportInNewTab', true);
    
  • With the Report violations when not entirely sure preference, you can choose whether you want CC4M to report violations when not completely sure about them. To illustrate this, consider the following example:

    var = myUnknownFcn();
    var.My_Field = true;
    

    In this case, CC4M is unable to detect whether var is a struct or an object. If it is a struct, it violates checkStructFieldCasing. Only when this preference is switched on will this situation be reported as a violation. By keeping this preference switched off, you can reduce the number of reported violations that are not actually violations of your coding standards. Set the preference via the command line :

    monkeyproof.cc4m.setPreference('ReportViolationsWhenUnsure', true);
    
  • Switch the Smart indent files before checking to the right to have CC4M smart indent the selected files before checking them, or use the command line interface, see below. This feature for convenience purposes automatically modifies your code - it is your responsibility to make sure your code is (functionally) correct after these modifications.

    monkeyproof.cc4m.setPreference('SmartIndent', true);
    
  • Switch the Exclude Live Editor files and App Designer files to the right to exclude the files in Open XML format from being checked.

    monkeyproof.cc4m.setPreference('ExcludeOxml', true);
    
  • Switch the Exclude Simulink files to the right to exclude Simulink models from being checked.

    monkeyproof.cc4m.setPreference('ExcludeSimulink', true);
    
  • With the Skip or check large files preference, you can choose what needs to be done with large files. Large file will take relatively long to process and may pollute the results report. Additionally, large files may be generated and not require checking at all. The preference has three options :

    • Ask every time: When one or more large files are selected for checking, you will be asked every run whether you would like to check or skip the large files.

    • Skip: Always skip large files if they are selected. Do not check them.

    • Check: Always check large files if they are selected.

    Set the preference via the command line :

    monkeyproof.cc4m.setPreference('SkipOrCheckLargeFiles', 'Skip');
    
  • The File size threshold [kB] preference lets you specify the threshold in kilobytes above which selected files are considered 'large'. The value can be between 50 and 1000 kB. As a rule of thumb, you can assume that a thousand lines of code constitute about 50 kB. Set the preference via the command line :

    monkeyproof.cc4m.setPreference('FileSizeThresholdKb', sizeInKb);
    

The current value of a preference can be obtained , for example, by the command below where defaultValue is returned if the preference has not been set yet.

monkeyproof.cc4m.getPreference('FileSizeThresholdKb', defaultValue);

Limitation

  • Smart indenting is always disabled for files in the MATLAB root since you are not allowed to change these.

Preferences tab of the CC4M GUI

About

The About tab as shown in the figure(#fig:AboutTab) below contains information about CC4M:

  • The installed version of the CC4M.

  • A button for opening the HTML documentation of CC4M.

  • A button for accessing the CC4M support forum.

  • A button for opening a license information dialog. From this dialog, you can extend or upgrade your CC4M license. This dialog is described in section License dialog.

  • Access the proxy settings by clicking Proxy settings.

About tab of the CC4M GUI

Configuring checks

CC4M has metrics and checks that are configurable. This way, the code checker can be adapted to fit the company's or the team's coding standards. A configuration file allows to define:

  • Description of the check.
  • Category of the check.
  • Rule identifier the check is related to.
  • Hyperlink to content of the rules.
  • If the check is used (enabled) or not.
  • Priority of the check.
  • Severity level of the check.
  • Parameter values: further customization.

The reports contain the configurations defined for the check and link it to an internal rules, see the figure below. It also includes a link to directly open the configuration of a specific check in the Configuration Editor. If you have specified a rules link, this will be accessible by clicking the rules ID in the report. If the link refers to a webpage, the rules link must start with https:// or http://. If your rules link contains a local drive address (i.e. C:\), links to specific pages in a PDF will simply open the file to the first page.

In order to provide insight in the settings of a check, information on its parameters is given in the report generated by CC4M. For every check that is enabled and has at least one parameter, the name, description, type, value and allowed values are shown. This information is obtained from the active configuration file. A link is also included that can be used to open the Configuration Editor to a specific parameter. An example of the information on a parameter for the check on variable casing as given in the report is shown in the figure below.

Information about the AllowNumbers parameter of checkVariableCasing.

Edit the configuration files

Section Configuration Editor describes the Configuration Editor for CC4M. It is used to open the configuration file of your choice interactively. The Configuration Editor can be opened by using the Open button on the Configuration tab in the CC4M GUI. The selected configuration file will be activated and opened. The Configuration Editor can also be opened from the Meta data section in a CC4M report using the Open button next to the configuration file path. To start editing the configuration of a specific check or parameter, use the links in the check result tables of a CC4M report. You will not be able to save any configuration files in the folder for predefined configurations shipped with CC4M (see section Predefined Configurations).

You could also edit the XML file directly in the text editor of your choice. However, this is not recommended because it is unintuitive and error-prone. The Configuration Editor makes sure that the edits you make and save, make the configuration file pass validation.

Update the configuration file

If a new version of CC4M is released, new checks and check parameters may be added. Your existing configuration file can be updated so that it will include these missing parts with default values. After updating, the newly added check configurations can be edited so that they apply the settings reflecting your coding standards and rules. Configuration files can be updated using one of two syntaxes:

monkeyproof.cc4m.updateConfigurationFile();

% Update the specified configuration file.
monkeyproof.cc4m.updateConfigurationFile('<myFolder>\<configName>.xml');

As described in section Configuration Editor, this option is also available in the Configuration Editor by clicking Add missing elements. If you have run CC4M and a report was generated, it will include a section on missing check or parameter configuration. It also includes a link to directly update the configuration file. After using any of these last two options, a dialog is shown that tells you what checks and parameters were added. If you call monkeyproof.cc4m.updateConfigurationFile from the MATLAB command window, the list of added checks and parameters is given as an output to the function call.

Considerations

Comments in the configuration file get lost during this process. It is therefore advisable to -if applicable- adjust the description of a check or parameter instead of placing the additional information in comments the xml file.

Empty lines in the xml file are also lost during this process.

Remark

It is not allowed to update a predefined configuration.

Multiple configurations per check

To allow for a better mapping of your coding standards onto your CC4M configurations file, one check can be configured multiple times. The Code Checker distinguishes between different configurations based on the rule identifier. This is useful for example when there are multiple guidelines on what MATLAB-installed functions to avoid using, each with their own rationale, ID and list of function names. The Configuration Editor fully supports multiple configurations per check, see section Clone and remove check configurations. Results for a check that is configured more than once do have an individual checks result table in the report. Based on the rules identifier you can distinguish between the different results.

If the same check is configured multiple times, the additional configurations of the check are ignored when checking your code if one of the following is true:

  • Not all rules IDs of the check configurations are unique.

  • The check has no configurable parameters (the results would be the same for every configuration of the check).

You can exempt specific configurations of a check or all configurations of the same check. This is described in section Exemptions.

Referencing configurations

There's the option to include other configuration files from within the active configuration file. This option allows one to stack rules that are split over several configuration files, for example a configuration file related to naming conventions, another configuration file related to layout and another configuration file related to code generation. More information about referencing configurations can be found in section Reference configurations.

Missing checks

If the checks available within CC4M do not cover something you want to have checked, please contact us at info@monkeyproofsolutions.nl.

Disabled checks and reports

A check or report can be disabled using your configuration. If a check/report is disabled, it will not be performed and you will therefore not see any results for it in the final report. However, a table listing all disabled checks and reports can be found at the bottom of the report. It also includes a link to the configuration of the check/report so that you can easily enable the check and change its configurations. For quick access to this table, a link to it is included in the metadata at the top of the report as described in section Meta data and summary, which also shows the number of disabled checks and reports.

Exemptions

You might want to exempt certain parts of your code from specific checks. By doing this, results for those checks on those parts of the code will not be contained in the report shown after CC4M is finished checking your files. Code can be made exempt from checks in a way that is similar to MATLAB's mlint that lets you disable warnings in the editor by using syntax like %#ok<NASGU>. Every check has its own unique five-letter exemption tag, except for the checks that you are not allowed to add exemptions for:

These tags can be used to exempt a line of code from a check by placing %@ok<MYTAG> behind it (where MYTAG is the tag of a check) somewhere in a comment on the line of code. By adding a '*' before the tag (so %@ok<``*``MYTAG>), you can exempt the entire file from a check. An example is shown below:

x = rand();
if x > 0.99 %@ok<IFELS> This is my explanation on why I don't want an 'else' here.
    disp('Hurray!')
    return
end %@ok<*AVFUN>

Normally (if the check is enabled), we would see this part of the code show up in the report because the if does not have an else section. However, by using the exemption tag for checkIfElse, it will not show up in the report. On the last line, we can see a file-wide exemption for checkAvoidFunctions. Doing this will make sure that return (or any function whose use you configure as discouraged) is not reported as a function to avoid for this file. The placement of this file-wide exemption within the file is irrelevant, as long as it is a comment.

As described in section Multiple configurations per check, a check can be configured more than once. In order to exempt your code of a specific configuration of a check (related to a specific rule) append the exemption tag with a dash followed by the rule ID. For example, to exempt your code of a configuration of checkAvoidFunctions with rule ID A1_0, add the exemption %@ok<AVFUN-A1_0>.

The exemptions can be ignored by switching on Ignore exemptions in the GUI.

Multiple exemptions can be defined on a single line like so:

y = x>0.99 %@ok<IFELS, *AVFUN, SURSP-MYID> My explanation.

Add exemptions automatically

In order to easily add exemptions to your code, you can use the Add exemptions column in reports generated by CC4M. This is shown in figure Add exemptions where the button in the third row has been clicked. Upon clicking the Add exemption button, an exemption tag is added to the file in which the violation was found and the file is opened at the place where you can add a comment on why the code is exempt from the check. The exemption tag will include the ruleID (if any) so that the automatically added exemption only exempts your code for one of configurations of a check. This is shown at the bottom of the figure. By clicking the Add file-wide exemption button, you can add a file-wide exemption (with *-notation) as described above. This feature takes pre-existing comments and exemptions into account when inserting the new exemptions.

For the automatic exemptions to work, the lines and line numbers at which to add the exemptions should not have been edited between running the check and clicking the Add exemption button. Doing so might result in a warning. After a button has been clicked and an exemption was added, the button will be disabled. This feature helps to keep track of the exemption buttons that have been clicked previously, but they do not reflect the most up-to-date state of the code. This feature for convenience purposes automatically modifies your code - it is your responsibility to make sure your code is (functionally) correct after these modifications.

Example of the Add exemptions column in a CC4M report

Supporting functionality

  • In order to easily add an exemption to your code without using a CC4M report, you can use function getExemption:

    >> theTag = monkeyproof.cc4m.getExemption('checkAvoidFunctions');
    

    This will return the exemption tag for the given check name as it can be used in your code (for example %@ok<FCNPF>). You can provide the full check name including packages, only the check name or even a partial check name as the input.

  • The exemption tags of each of the checks are also given in this document under each individual description of the checks in section Checks.

  • To get an overview of all exemption tags, use getAllExemptions:

    tagsTable = monkeyproof.cc4m.getAllExemptions();
    

    This will return a table containing the exemption tag for every check:

    Top of the table returned by monkeyproof.checks.getAllExemptions

Limitation

  • Note that adding exemptions is always disabled for MATLAB-installed files since you are not allowed to change these.

Rerun functionality

In the report, in the Meta Data and in the Summary sections, a Rerun all button can be used to quickly rerun CC4M using the settings that were used to create the report you are currently viewing. This is very useful to check if the changes you made after viewing the report result in improved rule compliance. It can also be useful if the configuration file has changed.

Remarks

  • The settings used for the rerun are stored in CC4M and not in the report. This has the following consequences:

    • Clicking the Rerun all button in an older report could result in using different settings for the rerun than were used for the initial run that resulted in the report. It is therefore recommended to use the rerun functionality from the most recently created report.

    • Clearing the CC4M code or calling clear all, clear classes, clear functions or clear java causes the stored inputs to be lost. Clicking the Rerun all button will then result in an error.

    • MATLAB sessions in which no CC4M report was created yet will trigger an error when a report is opened and the Rerun all button is clicked.

  • The rerun functionality does not directly use a list of files to check. Instead, it uses the settings used during the last run. This has to be kept in mind in the following situations:

    • If you checked a folder before, the folder will be checked again and any newly added files will be checked as well.

    • If you checked the MATLAB file that was opened in the editor, the rerun function will run the checks on the file that is open in the editor at the time of clicking the Rerun all button.

    • If you selected the option to check only the files changed with respect to a SubVersion repository, the list of files may change when you edit other files or commit your changes.

  • If no new CC4M run was started for over 72 hours within the same MATLAB session, you will be required to do so before being able to use the rerun functionality.

Automatic fixes

For several checks, auto-fixers are available. By clicking the Fix all button in the report (see figure Link to an auto-fixer in the CC4M report all violations for a specific (configuration of a) check are fixed. By clicking the Fix all in this file button all violations for a specific (configuration of a) check in a checked file are fixed. There is also a Fix on this line button, to fix individual violations. For this to work, the lines at which the violations were encountered should not have been edited between running the check and clicking the auto-fix link. Doing so might result in a warning. Similarly, fixing the same line twice will fix the violations the first time, and could trigger a warning on the second attempt. After a button has been clicked and its fix has been applied, the button will be disabled. This feature helps to keep track of the fix buttons that have been clicked previously, but they do not reflect the most up-to-date state of the code. After fixes have been applied, it is advised to run the check again to verify that the code now passes the check. Automated fixes are not available from the Model Advisor. This feature for convenience purposes automatically modifies your code - it is your responsibility to make sure your code is (functionally) correct after these modifications.

The checks for which fixes are currently available are:

Link to an auto-fixer in the CC4M report

Limitation

  • Note that automatic fixes are always disabled for MATLAB-installed files since you are not allowed to change these.

Starting from MATLAB R2016a, Live Editor files (.mlx) and App Designer apps (.mlapp) can be created. CC4M supports checking these files as well as MATLAB code in Simulink models. However, there are some differences compared to the functionality for MATLAB code (.m):

  • For Live Editor files and App Designer files, conversion from binary to text must take place before checking the code, which may involve opening the file in the Live Editor. This impacts performance and may focus the Live Editor.

  • In MATLAB versions before R2020a, when the active file in the editor is a Live Editor file, the text field in the GUI is empty and the run cannot be started until a file is selected through different means.

  • Auto-fixing Live Editor files, App Designer and Simulink files is disabled.

  • Adding exemptions to Live Editor files, App Designer and Simulink files directly from the report is not possible. The exemption tag is provided in the Command Window and can be pasted in the appropriate place manually.

  • For Live Editor Files, App Designer apps and Simulink models, compatibility issues between MATLAB releases may exist. If a file cannot be used in a MATLAB release, CC4M can also not check it in that release. It is recommended to verify if errors or warnings occur when opening files before running the checks.

  • Links in the HTML report use MATLAB's opentoline function to link to the code. For App Designer apps, in some MATLAB releases this does not always put the cursor at the correct position in the code. In those cases you may hover your mouse cursor over the link in the report and look at the status bar (bottom left) to see the line and column numbers.


2

checkUserDefinedFunctionCasing only checks the names of user-defined functions that are not methods. The names of methods are checked elsewhere. Furthermore, when this check is used in combination with checkFunctionPrefix, prefixes are subtracted before checking if the functions are cased according to the configured values.

3

the checkStructFieldCasing check suffers from the same limitation as checkStructFieldNaming: casing of dynamically assigned field names will not be checked.

4

checkMethodCasing does not report declarations of methods that are incorrectly cased if their functionality is specified in a separate function file. Additionally, getter and setter methods are ignored in this check, because their names are derived from property names that have a separate check. Constructor names are ignored during this check because they are named after the class. Finally, methods that overload a method of a superclass, are not checked here because those method names are not defined by the checked classdef file. Note, if a superclass has its own superclass(es), this is not taken into account.

1

This aligns equals signs in groups of expressions at multiples of the indentation length configured for checkIndentationLength. This way, the equals signs can be easily realigned after changes using the Tab key.

Checks

There are a number of checks available within CC4M. These can be enabled and configured as described in section Configuration Editor. The checks are explained in the following sections. For every check, an exemption tag is given. For more information about this, see section Exemptions. If a check fails, its results hold the following information:

  • A relative path from the root folder to the file in which the violation was encountered.

  • The part of the code that violates the coding standards including a link.

  • The scope of the failing feature/variable (if appliccable).

  • A message stating why the check failed at that location.

  • A link for quickly adding an exemption for the violation.

  • Rule information.

  • Configured check and parameter values.

Note: In the HTML report at most one violation of the same type per line of code will be shown for several checks, this is indicated per check in the following sections.

Overview

The checks are organized per topic. some checks could be applicable to more topics, but are mentioned just once. The topics are:

Generic checks

checkArgumentsBlockUsed

Checks whether an arguments block is used for input validation for the specified categories of functions among the files selected for checking. The arguments block introduced in MATLAB R2019b is very useful for input argument validation and can also be used for automatic casting. It provides a more readable and more performant alternative to functions such as inputParser, narginchk, nargin and varargin. If your code does not need to support older MATLAB releases, you might want to enable this check. Its parameters facilitate only checking publicly available functions for the presence of an arguments block. This check ignores functions that:

  • Have no input arguments.

  • Are local (subfunctions), including any functions in a script.

  • Are nested. These are not allowed to have arguments blocks anyway.

  • Have all their inputs ignored (with the ~-notation).

If a function only uses arguments blocks with the Output attribute (introduced in MATLAB R2022b), the function is reported as a violation.

Configurable parameters

  • OnlyPublicFunctions (boolean): Set this to true (default) to only check if public, visible functions and methods use arguments blocks. In addition to the list above, enabling this parameter makes the check ignore:

    • Functions in a private folder.

    • Methods with any access restriction.

    • Hidden methods.

    • Getter and setter methods.

    If the function is a method in a separate file and its class information could not be obtained (usually because of an error in the classdef file or while initializing its property values), the function will be checked and reported if there is no arguments block.

  • IgnoreSingleInputOrdinaryMethods (boolean): Set to true (default) to have this check ignore all ordinary (non-static) methods with a single input (one or more objects) that are not constructors. Adding an arguments block for these types of methods is generally not needed, and this parameter helps to prevent reporting unnecessary violations.

  • ExemptFolders (list): A list of folder-names whose files should be ignored by this check. This can be useful, for example, if you have a package folder that is not for public use. The folders of this parameter are checked for at the end of the path of a checked file. This means that specifying test as an exempt folder, makes this check ignore C:\somefolder\test\myFile.m, but it will still check C:\test\somefolder\myFile.m and C:\somefolder\foldertest\myFile.m.

    Alternatively, you can provide multiple layers for one folder. By specifying test\+internal as an exempt folder, you ignore C:\test\+internal\myFile.m, but will still check C:\otherFolder\+internal\myFile.m and C:\test\myFile.m. By default, the list is empty.

Exemption tag: %@ok<CARBU>

checkAvoidFunctions

Checks if the code depends on functions that should be avoided. For example: using eval is often discouraged because it can result in code that is unreliable and difficult to read. Other reasons to discourage use of certain functions and keywords are to prevent system damage or to ensure automation or code generation. You can also specify entire MATLAB folders to avoid using functions from.

Configurable parameters

  • AvoidFunctions (list): A list of functions and keywords that are to be avoided. This can include user-defined functions if necessary.

  • AvoidFolders (list): A list of folders in the MATLAB installation folder whose functions to avoid using. Provide the folders with respect to <matlabroot>\toolbox where matlabroot is the installation folder of the current MATLAB session that is also returned by calling matlabroot(). For example, configuring the value matlab\graphics for this parameter will make this check report calls to any function in the folder

    C:\Program files\MATLAB\R2020b\toolbox\matlab\graphics.

Exemption tag: %@ok<AVFUN>

checkCopyrightNotice

Checks if a specific copyright notice is found in the checked files. A copyright notice can be used as a deterrent against copyright infringement. There are a few configurable parameters for this check. If a copyright notice is lengthy, it may be split across multiple lines in the checked file(s). This is supported by this check. It is required to have your copyright notice on a separate line, so without any code on it.

Configurable parameters

  • Notice (string): The copyright notice that must be included in the files. In order to facilitate checking for a copyright notice of different years, use #YEAR# in the configuration parameter to indicate any year in this century. This will match copyright notices containing a year such as 2011-2018, 2019, 2001 - 2008. In the configuration file, define the copyright notice on a single line, without line breaks or % characters to indicate a comment. For example, a notice defined as Copyright #YEAR# My Company. All rights reserved. will pass this check if your checked file contains %% Copyright 2016-2019 My Company. All rights reserved..

  • Location (list): Indicate the expected location of the copyright notice. May be one of the following:

    • Top: Place the copyright notice at the top of the file, even before any function or classdef headers.

    • BeforeMainCode: Place the copyright notice right after the function or classdef header, but before other code. If the checked file is a script, the copyright notice is searched for at the top of the file.

    • Bottom: Place the copyright notice at the bottom of the file, after all code (also after local functions).

    • Any: All three locations described before are allowed.

This check has an auto-fixer. Clicking the Fix all button in the report fixes all violations for this check, clicking the Fix for this file button fixes the violation for one file.

Exemption tag: %@ok<COPYR>

checkScriptFileUsed

Checks if there is a script file used. Scripts are not always desired, use functions and classes instead.

Exemption tag: %@ok<SCRFU>

checkCharacterArray

Checks the usage of character arrays. If one intends to use strings instead of character arrays, an overview of where character arrays are used is provided. The maximum number of reported character arrays per line is one. This does not report using outputs of MATLAB-installed functions that return character arrays. For example: mfilename or datestr. In the HTML report at most one violation of the same type per line of code will be shown for this check.

Exemption tag: %@ok<CHARA>

checkStringDataType

Checks if the string data type is used in the code. The string data type was introduced in MATLAB R2016b and the double quote notation was introduced in MATLAB R2017a. For backwards compatibility purposes, it can therefore be desired not to use this data type. It may also be for consistency reasons that you want to check if this data type is used. This check reports a violation when the double quote notation is used to indicate a string or when the MATLAB-installed string() or strings() function is used. When multiple strings are defined on a single line using double quotes, only the first violation is reported. In the HTML report at most one violation of the same type per line of code will be shown for this check.

Note that this check only reports the cases described above. This mostly means that MATLAB-installed functions that can output a string are not reported as violations. For example: data = readtable('test.csv', 'TextType', 'string'); will output a table containing strings, but no violation is reported.

Exemption tag: %@ok<STRDT>

checkGetterAndSetter

Checks if methods such as get.MyProperty() and set.MyProperty() have been declared. The rationale behind this check is that nothing should happen when you set or get a property when it is used directly to make sure that the code stays readable and does not produce any unexpected side effects. If it is necessary that actions are performed when getting or setting a property, make the property private and implement explicit getters and setters (for example getMyProperty() and setMyProperty()).

Exemption tag: %@ok<GETST>

checkTestSuffix

Checks if the configured suffix is reserved for unit test files. Unit test files can be classdefs, functions or scripts. What is considered to be a unit test file by CC4M is defined as follows:

  • Classdef files: A method is defined within a methods block that has the Test attribute. If the class meta information could not be obtained (for example because the calculation of a default value of a property triggered an error), the file is not considered a test file.

  • Function files:

    • The MATLAB-shipped functiontests function is called in the main function of the file.

    • The file name starts or ends with test (case-insensitive).

  • Scripts: The file name starts or ends with test (case-insensitive).

This check reports files in two situations:

  1. If the file is considered a test file but it is not suffixed with the configured suffix.

  2. If the file is not considered a test file but it is suffixed with the configured suffix.

Configurable parameters

  • Suffix (string): The suffix to reserve for unit test files.

Exemption tag: %@ok<TSTSF>

Naming convention checks

CC4M has several checks on the casing of names of certain aspects in the code. There is a separate check for each aspect, which means that every casing check can have their own parameter values.

Code aspect name checkedName of the checkExemption tagNote
VariablescheckVariableCasing%@ok<CVARI>
User-defined functionscheckUserDefinedFunctionCasing%@ok<CUDFU>1
Structure fieldscheckStructFieldCasing%@ok<CSFIE>2
MethodscheckMethodCasing%@ok<CMETH>3
Name-value pairs in arguments blockscheckNameValuePairCasing%@ok<CNVPC>4
ClassescheckClassCasing%@ok<CCLAS>
Class propertiescheckPropertyCasing%@ok<CPROP>
PackagescheckPackageCasing%@ok<CPACK>
EventscheckEventCasing%@ok<CEVEN>
Enumeration memberscheckEnumMemberCasing%@ok<CENME>
Constant propertiescheckNamedConstantCasing-5
1

checkUserDefinedFunctionCasing only checks the names of user-defined functions that are not methods. The names of methods are checked elsewhere. Furthermore, when this check is used in combination with checkFunctionPrefix, prefixes are subtracted before checking if the functions are cased according to the configured values.

2

the checkStructFieldCasing check suffers from the same limitation as checkStructFieldNaming: casing of dynamically assigned field names will not be checked.

3

checkMethodCasing does not report declarations of methods that are incorrectly cased if their functionality is specified in a separate function file. Additionally, getter and setter methods are ignored in this check, because their names are derived from property names that have a separate check. Constructor names are ignored during this check because they are named after the class. Finally, methods that overload a method of a superclass, are not checked here because those method names are not defined by the checked classdef file. Note, if a superclass has its own superclass(es), this is not taken into account.

4

The arguments block was introduced in MATLAB R2019b.

5

Constant properties may be subject to different casing rules. This is made available with checkNamedConstantCasing. This casing check behaves different from the other casing checks:

  • Constant properties are not required to be cased as specified in the parameters of the check on named constant casing. They are still allowed to be cased like any other property.
  • The check does not have its own results table in the report.
  • When this check is enabled and a constant property does not satisfy the coding standards of regular properties or those of constant properties, the property is listed in the results table of checkPropertyCasing.

Configurable parameters

The parameters for each of the casing checks are:

  • Casing (string): Sets the type of casing that needs to be checked. This value can be either UpperCamelCasing, lowerCamelCasing, snake_casing, SCREAMING_SNAKE_CASING or lowercasing.

  • MaxConsecUpper (double): The allowed maximum number of upper case characters in a row. This value can be increased to allow acronyms in upper case. The value must be between 0 and 50.

  • MaxConsecLower (double): The allowed maximum number of lower case characters in a row. This value can be decreased to be able to detect names that lack upper case characters where needed. The value must be between 0 and 50.

  • AllowNumbers (boolean): Set this to true to allow numbers in the name.

These parameters combined are used to check the casing of names as follows:

  • UpperCamelCasing: One or more repetitions of: between one and MaxConsecUpper upper case characters followed by between one and MaxConsecLower lower case characters. The name is allowed to end with upper case characters. Only letters are allowed. If AllowNumbers is true, any number of numbers is allowed in the name.

  • lowerCamelCasing: Between one and MaxConsecLower lower case characters in a row followed by one or more repetitions of: between one and MaxConsecUpper upper case characters followed by between one and MaxConsecLower lower case characters. The variable name is allowed to end with upper case characters. Only letters are allowed. If AllowNumbers is true, any number of numbers is allowed in the name.

  • snake_casing: Starts with between one and MaxConsecLower lower case characters followed by one or more repetitions of: an underscore followed by between one and MaxConsecLower lower case characters. If AllowNumbers is true, any number of numerical characters is allowed. Note: this does not allow a name to end in an underscore, and it does not allow for multiple consecutive underscores.

  • SCREAMING_SNAKE_CASING: Starts with between one and MaxConsecUpper upper case characters followed by one or more repititions of: an underscore followed by between one and more MaxConsecUpper upper case characters. If AllowNumbers is true, any number of numerical characters is allowed. Note: this does not allow a name to end in an underscore, and it does not allow for multiple consecutive underscores.

  • lowercasing: Can only contain lower case characters (so no underscores) and -optionally- numbers.

Upon a rule violation, the casing checks provide the same information as the other checks do: A path to the checked file, the part of the code violating the coding standards, the scope (if appliccable), and a feedback message.

Other checks

checkAvoidNames

Checks if the code uses names not to use for classes, functions and variables etcetera. For example: using myFunc or temp is often discouraged because it is not descriptive and it gives the impression that work is still under construction.

Configurable parameters

  • AspectsToCheck (list): A list of aspects to check, classes, functions, variables etcetera.

  • AvoidNames (list): A list of names that are to be avoided.

  • ReportCaseSensitive (boolean) : Set to true to report case-sensitive matches for 'AvoidNames', the default value for this parameter is true.

  • AvoidRegexps (list): A list of regular expressions that are to be avoided. More information about regular expressions can be found here.

Exemption tag: %@ok<AVNAM>

checkFunctionPrefix

Checks if the names of local functions (also referred to as subfunctions) and nested functions are prefixed with specified prefixes. By prefixing these functions, calls to local or nested functions can easily be distinguished from other function calls. This check ensures that the prefixes are actually used as prefixes: at the start of the name and followed by at least one character.

Configurable parameters

  • LocalFunctionPrefix (list): A list of prefixes for local functions that are allowed to be used. If the list is empty, local functions do not have to be prefixed with anything.

  • NestedFunctionPrefix (list): A list of prefixes for nested functions that are allowed to be used. If the list is empty, nested functions do not have to be prefixed with anything.

Exemption tag: %@ok<FCNPF>

checkLoopIteratorNaming

Checks if iterator variables are prefixed with i, j, k etc. Depending on the parameters for variable casing, this can mean that iterator variables can be of the form iRow, jTest (lower/upper Camel casing), i_row, j_test (Snake casing), iROW, jTEST (screaming Snake casing) or or irow, jtest (lower casing). When enabled, this check fails if:

  • The iterator variable name does not start with i, j, ..., z.

  • The first character is not followed by an upper case character (lower/upper Camel/screaming Snake casing), a lower case character (lower casing) or an underscore followed by a lower case character (Snake casing).

Configurable parameters

  • SubsequentLettering(boolean): True if, in nested for-loops, the starting letters of the iterator names shall be subsequent letters in the alphabet.

  • MinimumLength(double): The minimum length for iterator variable names, the name should be descriptive. The default value for this parameter is 3 and it can be changed to anywhere between 1 and 20.

  • UseVariableCasing(boolean): Set to 1 to use the casing parameters for variable casing. If set to 0, iterator variable names can be of the forms lower/upper Camel casing, Snake casing, screaming Snake casing or lower casing.

By maintaining a convention on iterator variables, these can easily be distinguished within the code.

Exemption tag: %@ok<IDXNA>

checkNameIsShadowing

Checks for all variables and functions in the file(s) whether they shadow any existing functionality. For example: if a variable named pi is defined, you will no longer have access to the actual value of within that file. This can cause unexpected and undesired behaviour. Variables and functions are reported if they have the same name as one or more of the following:

  • MATLAB-installed functions. As described here, certain method names are supposed to overload MATLAB-installed functions. When used as the right type of method, these are ignored by this check, regardless of whether or not they are configured as exceptions.

  • Classes

  • Packages

  • MATLAB executable files (MEX): .mexw32, .mexw64, .mexa64, .mexmaci64

  • Simulink files: .mdl, .slx. Detecting the shadowing of a Simulink file requires a Simulink license.

  • Other MATLAB files: .m, .mlx, .mlapp, .p

Configurable parameters

  • Exceptions (list): A list of names that do not need to be checked for shadowing. Add names to this list if you want to shadow certain files/functions or if you do not mind shadowing specific files. Suggestions for exceptions include input/output-related functions: nargin, nargout, varargin and varargout.

Exemption tag: %@ok<NSHAD>

checkNameLength

Checks if the length of function and/or variable names are within the allowed minimum and maximum length according to the coding standards. Limiting the lenght of function and variable names increases the readability of the code.

Configurable parameters

  • MinFuncNameLength (double): The minimum length for function names. The default value for this parameter is 3 and it can be changed to anywhere between 5 and 63.

  • MaxFuncNameLength (double): The maximum length for function names. The default value for this parameter is 30 and it can be changed to anywhere between 5 and 63.

  • MinVarNameLength (double): The minimum length for variable names. The default value for this parameter is 3 and it can be changed to anywhere between 1 and 63.

  • MaxVarNameLength (double): The maximum length for variable names. The default value for this parameter is 25 and it can be changed to anywhere between 1 and 63.

Exemption tag: %@ok<NALEN>

checkStructFieldNames

Checks whether any structure field names contain the name of the struct. For example: sensor.SensorWeight. This is a case insensitive check. This check checks fields that are defined in the following manner: test.TestLength = 10;. Additionally, field names defined using the struct() function liketest = struct('TestLength', 10);are also checked.

Limitations

Dynamically assigned field names are not checked by this check because the field names cannot be collected. Therefore, structures defined as follows will not result in violating this check:

fieldNames     = {'my_field', 'my_2nd_field'};
myStruct       = struct(fieldNames{1}, [], fieldNames{2}, []);

str            = 'TEST';
myStruct.(str) = [];

An additional limitation related to this check is given in section Considerations and Known Limitations.

Exemption tag: %@ok<SFNAM>

Compatibility checks

checkBuiltinFunctionCompatibility

Checks if all MATLAB-installed functions that are used by the checked code were introduced before or at the first supported MATLAB release of the code. For example, if your configuration states that the first supported MATLAB release is R2016b, this check will report all calls to MATLAB-installed functions that were introduced in R2017a and later. It is advised to run this check on the most recent MATLAB release you have available to see the best results (see the limitation).

Configurable parameters

  • FirstSupportedRelease (string): Can be any value between 2006a and the latest supported MATLAB release. The default value is 2017b.

  • ViolationUniqueness(list): Specify if you want to see unique violations global, per file or all violations. By default, this parameter is set to All.

Limitations

  • CC4M can only detect calls to MATLAB-installed functions if they were at least introduced in the MATLAB release you are currently using. Consider a parameter configuration that specifies that the checked code must run on R2016b. Calls to functions introduced in R2018b will only be detected as MATLAB-installed functions if CC4M is run on R2018b or later. This means that running this check using MATLAB R2016b will not result in a violation for that MATLAB-installed function.

Exemption tag: %@ok<BFCNC>

checkCoderCompatibilityFunctionCalls

Reports the MATLAB-installed functions used in the code that are (partially) MATLAB Coder-compatible or not. Three levels of support for C/C++ code generation can be reported: Fully supported, supported with limitations, and not supported. The violations in the report contain links to the documentation of the MATLAB-installed functions so that you can easily check the limitations (if any) or find alternatives that are (more) Coder-compatible.

Configurable parameters

  • SupportLevel (string): Allowed values are:

    • Supported: Reports calls to MATLAB-installed functions that are Coder-compatible without limitations or sidenotes. Using this setting makes it so that the check does not fail (since only supported features are reported). This means that in order to see the results for this check when this parameter value is used, you have to enable Include passed checks in the Report tab of the GUI.

    • Supported with limitations: Reports calls to MATLAB-installed functions that are Coder-compatible with limitations or sidenotes. The link to the documentation provided in the report can help you to quickly find these limitations and act accordingly.

    • Unsupported: Reports calls to MATLAB-installed functions without support for C/C++ code generation. The link to the documentation provided in the report may help you to find alternatives for these functions that are Coder-compatible.

  • Release (string): The MATLAB release for which you would like to check Coder-compatibility. Allowed values are 'R2017b' through the latest supported MATLAB Release and 'MostRecent'. The 'MostRecent' option automatically applies the level of Coder-compatibility of the most recent MATLAB release supported by CC4M.

  • ViolationUniqueness(list): Specify if you want to see unique violations global, per file or all violations. By default, this parameter is set to All.

If you would like to see the level of Coder-compatibility for every MATLAB-installed function call, you can configure this check multiple times, but with different settings for the SupportLevel parameter. That way, the report generated after the check contains a separate table for each of the support levels. For more information on configuring the same check multiple times, see section Multiple configurations per check.

This check only reports known MATLAB-installed functions. This means that if you use a MATLAB-installed function that was introduced in a MATLAB release after the one you are using, it is not reported by this check. You can use checkBuiltinFunctionCompatibility for that. For example if you set the Release parameter to R2020b and you are using R2017b. Conversely, if you use a MATLAB-installed function that was introduced in a MATLAB release after the one you have configured under Release, but that is known in the MATLAB release you are using, the function call will be reported. This is because the function is not supported in the configured MATLAB release, so it is also not Coder-compatible. For example, you set the Release parameter to R2017b and you are using R2020b to run the check.

Exemption tag: %@ok<CCFCN>

checkConcatenateExpandedArray

Checks if brackets are used to concatenate struct array field values or object array property values. Performing concatenation on an expanded array is not supported by the Coder before MATLAB R2020b.

An example that will be reported:

s = struct("xCoordinate", {1, 3, 4});
x = [s.xCoordinate];

Instead use:

s = struct("xCoordinate", {1, 3, 4});
x = zeros(size(s)); 

for iX = 1 : numel(x) 
    x(iX) = s(iX).xCoordinate; 
end

Limitation

Dynamic field and property references are not reported, like:

s       = struct("xCoordinate", {1, 3, 4});
myField = "xCoordinate"; 
x       = [s.(myField)] 

Exemption tag: %@ok<CONAR>

checkDynamicFields

Reports use of any dynamic struct field names and property names. Aside from personal preferences regarding this construct, this check is especially useful when the code must be MATLAB Coder-compatible (generating C/C++ code from your MATLAB code). This is because dynamic struct field and property names are not supported by the MATLAB Coder. Some examples of what will be reported by this check are (where the variable and name can be a struct and fieldname, or an object and property name):

s.(theField)     = 12;
s.x.(otherField) = 10;
a                = s.(b + "cd");
c                = s.(['test', 'cat'])

Exemption tag: %@ok<DYNFI>

checkJavaUsed

Checks if the code uses Java. It may be that one wants to be independent of Java, for example because Java packages and subpackages will not be available in MATLAB in a future release.

Exemption tag: %@ok<JAVUS>

Testability checks

checkAbstractClassInstantiation

This checks if any abstract classes are instantiated in the code that is checked. Running the code would result in an error, because abstract classes cannot be instantiated.

Exemption tag: %@ok<ABSCI>

checkAssertInputs

This checks if all calls to assert have an ID and a message as second and third inputs. These inputs can improve readability by showing the reader what it means if the assert fails. Additionally, the feedback to the user on a failed assertion will be much more informative.

Exemption tag: %@ok<ASINP>

checkAvoidVararginout

Checks if the code uses varargin and varargout as variable length input and output argument list. Avoiding the use of these variable length arguments increases the readability of the code.

Configurable parameters

  • AvoidVarargin (boolean) : Set to true to report the usage of varargin, the default value for this parameter is true.

  • AvoidVarargout (boolean): Set to true to report the use of varargin, the default value for this paramter is true.

Exemption tag: %@ok<VARIO>

checkCodeInterpretable

Report files that cannot be interpreted by MATLAB due to invalid code. Files might contain a parse error or have invalid characters. These files will be reported by this check, since files should not contain an error. Files with errors are also listed in the summary as described in section Meta data and summary.

Note that it is not possible to add an exemption for this check since there's no reason to allow invalid code.

checkFunctionCallExcessInputs

Check that functions are not called with more inputs than expected. If a function is called with more input arguments than expected, it will result in an error when the code is run. Calls to MATLAB-shipped and calls to mex-functions are ignored by this check. In case the function contains a Repeating arguments block or name-value arguments no violation will be reported.

Exemption tag: %@ok<FCTMI>

checkGlobalUsed

Checks if the keyword global is used. Use of this keyword is often discouraged (not in MATLAB specifically) because (among many other reasons) it becomes very difficult to determine which functions access these variables. This keyword has its own check because its priority is often higher than that of the keywords and functions listed under checkAvoidFunction.

Exemption tag: %@ok<GLOBU>

checkIfElse

Checks if every if has a matching else section. Defining an else section for every if improves readability by showing more clearly what it means when the if (and possible elseif's) condition are not satisfied.

Exemption tag: %@ok<IFELS>

Configurable parameters

  • AllowIfWithoutElse (boolean): Set to true to allow an if, that does not have an elseif section, without a matching else section. The default value for this parameter is false.

checkLogicalOperator

Checks for usage of logical operators && and || in logical expression. The short-circuit operators && and || only work on scalars and are therefore not useful for general logical expressions. Use elementwise logical operators & and | instead. In the HTML report at most one violation of the same type per line of code will be shown for this check.

Exemption tag: %@ok<LOGOP>

checkMixedTypesExpression

Checks expressions and conditions to see if operands or operators of logical and numerical types were mixed. Mixing operand types in an expression or condition decreases code readability and robustness. Some examples of expressions that will be reported by this check are:

a = 8.9 || 9.1;         % Numbers and logical operator ||.
b = isempty(a) * 3;     % MATLAB-installed function 'isempty' and the multiplication operator.
c = a * b & a > b;   % Multiplication and the logical operator &.
d = a / ~c;           % Division and the 'not' operator.

Since CC4M cannot reliably determine a variable's type, this check does not use such information. Only information known at the expression or condition itself will be used. Aside from the operators themselves, a non-exhaustive list of MATLAB-installed functions (including isempty as shown in the example) is used to determine the operand types.

Exemption tag: %@ok<MIXOT>

checkNestingDepth

Check on the nesting depth of blocks. Limiting the nesting depth of blocks increases the readability of the code.

Configurable parameter

  • MaxNestDepth (double): The maximum nesting depth of a block. The default value for this parameter is 3 and it can be changed to anywhere between 1 and 10.

Exemption tag: %@ok<NSTDP>

checkNumberOfInputsOutputsFunction

Checks if there are any functions with too many inputs or outputs. For readability of the code it is advisable to limit the number of input and output parameters of a function. It is recommended to group related parameters into structures.

Configurable parameters

  • MaxNumberOfInputs (double): The maximum allowed number of input parameters of a function. The default value for this parameter is 5 and it can be changed to anywhere between 1 and 10.

  • MaxNumberOfOutputs (double): The maximum allowed number of output parameters of a function. The default value for this parameter is 5 and it can be changed to anywhere between 1 and 10.

  • ExemptConstructor (boolean): Set to true to have this check exempts constructors. The default value for this parameter is false.

Exemption tag: %@ok<NINOF>

checkPersistentUsed

Checks if the keyword persistent is used. Use of this keyword is often discouraged (not in MATLAB specifically) because (among many other reasons) it becomes very difficult to determine which functions access these variables. This keyword has its own check because its priority is often higher than that of the keywords and functions listed under checkAvoidFunction.

Exemption tag: %@ok<PERSU>

checkReuseIteratorVariableName

Checks if iterator variable names are reused as iterator variable within a function. Not reusing iterator variable names prevents renaming all iterators when only the one for a specific loop must be renamed. Not reusing iterator variable names also improves readability.

If both this check and checkLoopIteratorNaming are enabled, possible violation messages contain a note that the user should be aware of it.

Exemption tag: %@ok<RUIVN>

checkSuperclassPropertyImplementation

Checks classdef files to see if it implements any superclass properties (if any). If this is the case, the class cannot be instantiated and an error will be thrown indicating this problem.

Limitations

If the classdef file could not be analyzed due to another problem, it could be that no violation is reported by this check, depending on the nature of the other problem.

Exemption tag: %@ok<SUPPI>

checkSwitchOtherwise

Checks if every switch statement has a matching otherwise section. Defining an otherwise section improves readability by clearly showing what happens when none of the case's are triggered. It also allows for defining error messages if required.

Exemption tag: %@ok<SWOTH>

checkTryExceptionHandling

Run this check to check if all try blocks are only used for exception handling. Although not recommended, try statements could also be used to suppress errors or to express a simple condition. checkTryExceptionHandling checks the following for every try:

  1. Is there a catch block with at least one line of executable code?

  2. Is an exception object assigned or created in the catch?

    1. Assigned: catch`` ME

    2. Created: ME = MException(errorID, msg);

  3. Is at least one of the list of exception handling MATLAB-installed functions or keywords used in the catch?

This does not check if points 2 and 3 hold for all execution paths within the catch, so if you use an if-else within the catch and only call an exception handling function in one of the two, it is not reported by this check.

Configurable parameters

  • RequireExceptionObject (boolean): When set to true (default), perform check 2. When set to false, do not require an exception object to be assigned or created in the catch.

  • ExceptionHandlingFunctions (list): List of functions or MATLAB keywords (return etc.), at least one of which must be called within every catch. The default list is error, throw, rethrow, throwAsCaller. Other suggestions are: errordlg, warning, return or some user-defined exception handling function.

Exemption tag: %@ok<TRYEH>

checkTryUsed

Checks if MATLAB's try - catch construct is used. Using this construct is often discouraged because it can degrade code readability. It can be unclear what is expected to go wrong within the try and it is therefore generally advised to write code around what could go wrong.

Exemption tag: %@ok<TRYUS>

checkWarningUsed

Checks if warnings are used. Do not throw warnings, if necessary throw errors instead. Using errors instead of warnings improves the robustness of the code. Warnings cannot reliably be caught and handled and therefore often accomplish little. The check ignores calling warning for disabling, enabling, or querying a warning. This means that using for example warning('off', 'matlab:my:identifier'); is not reported by this check.

Limitations

This check also reports cases where a warning state is set using a variable. Consider the following example:

warningState = 'off';
warning(warningState, 'matlab:my:identifier');

The statements do not issue a warning when run, but this check reports the second statement.

This check also reports calls to warning when you have shadowed the MATLAB-installed function with a local one..

Exemption tag: %@ok<WARNU>

checkUseIteratorVariableNameOutsideLoop

Checks if loop iterator variables are used outside the for-loop. Using a loop iterator variable name outside the for-loop might indicate a programming error.

Exemption tag: %@ok<UIVOL>

Layout and readability checks

checkWhiteSpaceEndOfLine

Checks if white space is used at the end of a line. For readability purposes do not use white space at the end of a line, comments are not taken into account, empty lines are ignored.

This check has an auto-fixer as well. Clicking the Fix all button in the report fixes all violations for this check, clicking the Fix all in this file button fixes all violations for this check for one file. The Fix on this line button applies the fix on one indivual line. For more information, see section Automatic fixes.

Exemption tag: %@ok<WSEOL>

checkZeroBeforeDecimalPoint

Checks if the decimal point in numeric expressions has a zero before it, a zero before the decimal point increases the readability of the code The following example shows what will be reported and what should be used instead:

threshold = .5;
value_x   = .1e9;

% Instead use:
threshold = 0.5;
value_x   = 0.1e9;

This check has an auto-fixer as well. Clicking the Fix all button in the report fixes all violations for this check, clicking the Fix all in this file button fixes all violations for this check for one file. The Fix on this line button applies the fix on one indivual line. For more information, see section Automatic fixes.

Exemption tag: %@ok<CZBDP>

checkCodeLength

Checks the length of the code where only executable lines of code are taken into account. Possible arguments blocks do not count towards the number of lines in a function. Limiting the length of functions increases the readability of the code.

Configurable parameters

  • MaxMainFuncLength (double): The maximum length for the main function. The default value for this parameter is 100 and it can be changed to anywhere between 10 and 500.

  • **MaxSubFuncLength (double):**The maximum length for a sub-function. The default value for this parameter is 50 and it can be changed to anywhere between 10 and 100.

  • MaxNestFuncLength (double): The maximum length for a nested function. The default value for this parameter is 10 and it can be changed to anywhere between 5 and 100.

  • MaxConstructLength (double): The maximum length for a constructor. The default value for this parameter is 100 and it can be changed to anywhere between 10 and 500.

  • MaxMethodLength(double): The maximum length for a method in a classdef file, methods in a separate file are treated as main function. The default value for this parameter is 10 and it can be changed to anywhere between 5 and 100.

Exemption tag: %@ok<COLEN>

checkCommandSyntax

Checks if command syntax statements are used in the code. Readability and maintanability of the code decreases by the use of command syntax statements.

Here an example, avoid

fcn in1 in2

Instead use

fcn("in1", "in2")

Configurable parameter

  • FixWithDoubleQuotes (boolean): Set to true to make the auto-fix option fix the violations with double quotes. If set to false, single quotes are used by the auto-fix. The default value for this parameter is true.

This check has an auto-fixer. Clicking the Fix all button in the report fixes all violations for this check, clicking the Fix all in this file button fixes all violations for this check for one file. You can use the Fix on this line button to apply the fix to the violations in an individual block of code. The auto-fixer adds quotes and brackets around the input arguments. For more information, see section Automatic fixes.

Exemption tag: %@ok<COSYN>

checkConstantDefinitionAtTop

Checks whether all constants are defined at the top of the function or script. Constant definitions are allowed to come before or after persistent and global declarations. Similar, constant definitions are allowed to come before or after import statements. Starting in MATLAB R2019b, the arguments block is available. Since no code can come before this block, all constant definitions will automatically come after it. For this check, a variable is considered to be a constant if it meets all of the following criteria:

  • The value is assigned once. Also no elements of the variable are allowed to be altered.

  • The value of the variable does not depend on function calls, including most MATLAB-installed functions. The only MATLAB-installed functions that can be used after which the variable may still be considered a constant are: pi, eps, sqrt, and factorial.

  • The value does not depend on other variables.

  • No dot notation is used to assign the variable. For example, struct field assignments will not be considered constants.

Aside from numbers and the MATLAB-installed functions listed above, several operators and constructs can be used in a variable declaration and it can still be considered a constant:

  • The expression for assigning the value can contain zero or more of the following operators: ^, :,*, /,+and -.

  • The expression can also be a row or column vector and use the transpose operator (').

  • It can contain strings or character vectors (single and double quotes).

Here are some examples of what are considered constants by CC4M:

a = 100;
b = 1 + 3;
c = 1.3e-9;
d = sqrt(2)/2;
e = pi^2;
f = 3 : 2 : 11;
g = "Test";
h = [3, 5, 10]';

The following variable declarations are not considered constants by CC4M:

k(3) = 5;
l = 100; % The value changes on the next line.
l = 200;
m = v + 1; % Where v is not seen as a constant.
n.field = 10;
p = cumsum([3, 5, 8]);

Exemption tag: %@ok<CNDAT>

checkContiguousStructFieldDefinitions

Checks whether for every struct, the fields are defined in a single, contiguous block of code. For this check, a single, contiguous block of code is defined as a block of code without empty lines in it. For example:

s.a = 2;
s.b = 3;

s.c = 100; % Separate block of code, so will be reported.

Additionally, this reports cases where the struct is used before all fields are added, even when it is a contiguous block of code. This only holds when the struct is used as an input to an assignment or function call in its entirety. The individual fields of the struct are allowed to be used before all fields are added. For example:

s.a = 2;
s.b = 3;
myCustomFcn(s);
s.c = 100; % The same code block, but the struct has already been used. This will be reported.

Conversely, the following will not result in a violation being reported by this check:

s.a = 2;
s.b = 3;
myCustomFcn(s.b, s.a);
s.c = 100; % The struct fields are used, but that is fine. No violation to report.

Some remarks about this check:

  • Addition of fields to nested structs will not be reported.

  • Addition of fields using dynamic field names is ignored by this check. This can affect the outcome of the check in two ways:

    str = 'myFieldName';
    s.a = 2;
    s.(str) = 3;
    
    s.myFieldName = 100; % Even though the field already exists, it is still reported as a violation because it was added dynamically.
    
    str = 'myFieldName';
    s.a = 2;
    s.b = 3;
    
    s.(str) = 100; % Even though the field does not exist yet, it will not be reported as a violation because it is a dynamic field assignment.
    
  • This check supports structs being defined as in the examples as well as those defined using the MATLAB-installed struct function.

  • This check is scoped per function. That means that if the input of your function is a struct, no violation is reported when a new field is added to it in the function.

  • When a new field is added in multiple conditional statements (for example in an if and else), it will only be reported once.

Exemption tag: %@ok<CSTFD>

checkDuplicateAttributes

Checks classdef files and reports any methods or properties blocks with duplicate attribute values. Decrease the number of methods and properties blocks by combining blocks that have identical attribute values into one. This check considers setting an attribute to its default value equal to omitting the attribute. See what the default values for all attributes are in the [MathWorks documentation]{style="color: blue"}. Keep the following in mind for this check:

  • The following sets of attributes are considered equal: (Hidden = true), (Hidden = 1) and (Hidden)

  • The order of attributes is ignored, so these are considered equal: (Hidden, Constant, Access = private) and (Constant, Access = private, Hidden)

  • An empty list of classes that can access the properties or methods is equal to setting private access: (Access = {}) equals (Access = private)

  • Because setting an attribute to its default value is considered equal to omitting the attributes, these are considered equal: (Access = protected, Constant = false, Transient = false) and (Access = protected)

Exemption tag: %@ok<DUPAT>

checkEditorWarnings

Checks if any warning messages are shown to the user in the MATLAB editor. With this check, the user does not need to open a file to see the editor warnings. Warning messages that are suppressed in the MATLAB editor are ignored by this check.

Configurable parameters

  • MlintSettings (string): Choose what settings to use when checking for editor warnings. Options are:

    • Local (default): Use the currently active local settings. This means that the editor warnings as shown in the MATLAB editor will be reported. For more information on changing these settings locally, see this page.

    • Coder-compatibility: Use settings related to coder-compatibility when checking for editor warnings.

    • Factory: Use the factory default settings when checking for editor warnings as shipped with MATLAB.

    • FromFile: Apply changes to the factory settings as defined in a txt-file whose location is given with the SettingsLocation parameter of this check. For more information on creating such a file, see this documentation.

  • SettingsLocation (string): This parameter is only used if the MlintSettings parameter is set to FromFile. It specifies where the settings file that must be used for checking for editor warnings, is located. The file must have extension .txt. It can be an absolute path. If it is not an absolute path, the file is expected to be on the MATLAB path. Keep possible namespaces in mind. The file must be findable using MATLAB-installed function which. If the file is not found this way, it is searched for in the currently active configuration folder (which does not have to be on the MATLAB path). For more information on the manipulation of the configuration folder, see .

  • MessageIDs(list): Define a list of message IDs to warn for, an empty list or 'all' reports all warning messages found. For example, the message ID 'AGROW' reports violations related to: The variable <name> appears to change size on everly loop iteration. Consider preallocating for speed.

See Check Code for Errors and Warnings Using the Code Analyzer for more information about checking MATLAB code for errors and warnings.

Note that this check can be configured multiple times, but the warning messages are obtained once. Which means that only one combination of the parameters 'MlintSettings' and 'SettingsLocation' can be used. Therefore it is necessary to configure those two parameter identical for all configuration of this check. If this is not the case when editing a configuration in the Configuration Editor, a dialog will pop up and you will get notified about non-identical parameter values.

Exemption tag: %@ok<EDWRN>

checkExpressionAlignment

Reports code blocks with expressions that are not properly aligned. In order to make your code more readable, consider aligning equals signs of the assignment expressions in a code block. This check reports contiguous blocks of assignments that do not have their equals signs aligned. Any non-assignment line (includes empty lines) indicates the end of a contiguous block of assignments. Some examples that will be reported are:

a = 12;
foobar = 101;

b = 1 ...
    + 3.1415 ^ 2;
eggs = 3;
more = 'test';

These examples after fixing will look as follows:

a       = 12;
foobar  = 101;

b       = 1 ...
    + 3.1415 ^ 2;
eggs    = 3;
more    = 'test';

Here are some examples of pieces of code that will not be reported by this check.

a = 12;

foobar = 101;

b = 1 ...
    + 3.1415 ^ 2;
someFunctionCall(b);
eggs = 3;

Alignment is checked based on the number of characters before the equals signs. A tab is treated as a single character, which means that equals signs may seem aligned, but a violation is reported anyway because for a different setting of the tab size, they are not aligned. Sets of method declarations, properties blocks and arguments blocks will not be reported by this check.

This check has an auto-fixer. Clicking the Fix all button in the report fixes all violations for this check, clicking the Fix all in this file button fixes all violations for this check for one file. You can use the Fix on this line button to apply the fix to the violations in an individual block of code. The auto-fixer insert spaces, not tabs. For more information, see section Automatic fixes.

Exemption tag: %@ok<EXPAL>

checkFollowedBySpace

Checks if commas, semicolons and keywords are followed by a space. Per default, this does not report commas, semicolons and keywords that are only followed by white space until the end of the line. This check also does not report any violations that are found in strings or comments. Enable this check to help improve readability of the code.

All MATLAB keywords in alphabetical order are: arguments (from R2019b), break, case, catch, classdef, continue, else, elseif, end, for, function, global, if, otherwise, parfor, persistent, return, spmd, switch, try and while.

This check has an auto-fixer as well. Clicking the Fix all button in the report fixes all violations for this check, clicking the Fix all in this file button fixes all violations for this check for one file. The Fix on this line button applies the fix on one indivual line. For more information, see section Automatic fixes. In the HTML report at most one violation of the same type per line of code will be shown for this check.

Exemption tag: %@ok<FOLSP>

checkFunctionIndented

Used to check whether or not functions are indented. Rules may specify that the contents of every function must be indented or that they should not be. The following rules apply to this check:

  • A line of code is considered indented if it has at least IndentationLength whitespace characters at the start, with IndentationLength a parameter value.

  • Comments are ignored during this check.

  • A function block is only considered indented if all of its code is indented.

  • A function block is considered non-indented if at least one line of code has zero indentation.

Configurable parameters

  • DoIndent (boolean): Set to 1 to require a function block to be indented. Set to false if function blocks should not be indented.

  • IgnoreTabs (boolean): Set to 1 to ignore violations related to tabs, the check does not result in unnecessary violations when using another computer with a different MATLAB preference 'EditorSpacesPerTab'. The default value for this parameter is false.

  • IndentationLength (double): The minimum indentation length. If a function block must be indented, code must at least be indented by this amount of whitespace characters. Note: this value is ignored when DoIndent is set to 0, because in that case, the code should not be indented at all. The value must lie between 1 and 8.

Exemption tag: %@ok<CFIND>

checkIfTrue

Checks if constructs such as if`` true are used. Using this type of if-statements reduces readability and can generally be left out. The full list of constructs of this type that is checked is: if`` true, ``if`` false, if`` 1 and if`` 0. Note that in some of these cases, MATLAB's Code Analyzer will display a warning message already.

Exemption tag: %@ok<IFTRU>

checkIndentationLength

Check if all indented lines have an indentation length divisible by parameter indentation length, except for white lines. Consistent indentation increases the readability of the code. This check may not work as expected when tabs do not insert whitespace, but tab characters.

Configurable parameter

  • IndentationLength (double): The indentation length of indented code should be divisible by the parameter IndentationLength. The default value for this parameter is 4 and it can be changed to anywhere between 1 and 12.

Exemption tag: %@ok<CINLE>

checkLineLength

Checks if the length of a line exceeds the maximum line length according to the coding standards, for readability it is advisable to have a maximum on the line length. Check includes comments and whitespaces.

Configurable parameters

  • MaxLineLength (double): Lines that are longer than this value are reported. The default value for this parameter is 120 and it can be changed to anywhere between 50 and 200.

Exemption tag: %@ok<LILEN>

checkMagicNumber

Reports use of so-called magic numbers or unnamed numerical constants in your code. These are numbers used directly in the code without being assigned to a variable first. For example, replace

x = 9.81 ``*`` t;

with

g = 9.81; % Gravity constant.

x = g ``*`` t;

Using magic numbers in your code can degrade readability and the author's intent for them may not be apparent. There are some situations that will not be reported. For example, comparing the output of nargin or exist to a number that would normally be reported. Aside from these exceptions, this check's strictness can be configured using the parameters described below. In the HTML report at most one violation of the same type per line of code will be shown for this check.

Configurable parameters

  • IntegerExemptionMin & IntegerExemptionMax (double): Integer numerical constants may be exempt of this check. These parameters set the lowest and highest integer value that is allowed to be used in the code. Especially the numbers 0, 1, and 2 should probably be exempt of this check. These parameters let you configure that. Defaults are -2 and 4, respectively.

  • ExemptWholeDecimals (boolean) : Whether or not this check should allow whole decimal numbers in the range IntegerExemptionMin to IntegerExemptionMax. The default value for this parameter is set to true, so for example 0.0 and 2.00 will be allowed.

  • AllowOrderConversion (boolean): By setting this to true (default), numerical constants are allowed to be used directly in the code if they are used to multiply or divide a number by an order of ten. The following examples will be reported when this parameter is set to false, and will not be reported when set to true:

    • x = y / 100;

    • x = 1e-3 ``*`` y;

    • x = 0.01 ``*`` y;

    • x = y / 1e12;

    This parameter is especially useful for allowing unit conversions in the code.

  • IgnoreValidationBlocks (boolean): By setting this to true (default), this check will not report any violations in properties or arguments blocks.

Exemption tag: %@ok<MAGNR>

checkMissingComma

Check if any rows lack properly placed commas to separate the elements. Some examples that will be reported as violations by this check and their accepted equivalents:

txt     = ['test ' var ' text.'];
values  = [1 1 2 3 5 8 13];
myCells = {obj1 ,obj2};
multi   = ['The multi-' ...
    'line char array.'];

% Accepted equivalents:
txt     = ['test ', var ', text.'];
values  = [1, 1, 2, 3, 5, 8, 13];
myCells = {obj1, obj2};
multi   = ['The multi-', ...
    'line char array.'];

This check has an auto-fixer as well. Clicking the Fix all button in the report fixes all violations for this check, clicking the Fix all in this file button fixes all violations for this check for one file. The Fix on this line button applies the fix on one individual line. For more information, see Automatic fixes.

When multiple function outputs are not separated by commas, it can reported by . In the HTML report at most one violation of the same type per line of code will be shown for this check.

Exemption tag: %@ok<MCOMM>

checkMissingSemicolon

Reports lines of code that could result in output to the command window because they are not terminated with a semicolon. Use this check to determine the part of your code that produces unwanted or unexpected output. In the HTML report at most one violation of the same type per line of code will be shown for this check.

Configurable parameters

  • ReportAll (boolean): Set to true to have CC4M report all lines that could result in output to the command window due to not being terminated with a semicolon. For example, this includes calls to the error function. This setting can be used when your coding standards require that all lines of code are terminated with semicolons. When set to false, this check only reports lines that have a MATLAB warning about missing semicolons (lines that will definitely generate output to the command window when executed). By default, this parameter is set to false.

This check has an auto-fixer as well. Clicking the Fix all button in the report fixes all violations for this check, clicking the Fix all in this file button fixes all violations for this check for one file. The Fix on this line button applies the fix on one individual line. For more information, see section Automatic fixes.

Exemption tag: %@ok<MSEMC>

checkNegatedBoolean

Checks if there are no variables that have negated boolean names such as notValid, is_not_ok. Using such variables in conditional expressions can be confusing and difficult to read and therefore, this check may be enabled. Based on the casing used for variables, this reports variables with names that:

  • Lower Camel casing: Starts with not followed by anything other than a lower case character, or it contains Not followed by anything other than a lower case character.

  • Upper Camel casing: Contains Not followed by anything other than a lower case character.

  • Snake casing: Starts with not_, it contains _not_, or it ends with _not.

By using these settings instead of just looking for not, names such as notation and myNotifier will not be reported as fails of this check.

Configurable parameters

  • VariableCasing (string): This check automatically uses the Casing setting from the checkVariableCasing check to determine how to detect negated boolean variable names. This means that the check on variable casing must be enabled if this check is enabled.

Exemption tag: %@ok<NEGBO>

checkNestedFunction

Checks if there are any nested functions used. Using nested functions is often discouraged because it can degrade code readability.

Exemption tag: %@ok<CNSTF>

checkNoInputArg

Checks if all function calls without input arguments have empty parentheses. Most importantly, using empty parentheses instead of leaving them out helps to distinguish between accessing an object's properties and using it's methods. Additionally, it clearly shows where functions are called. In order to prevent copious amounts of fails to this check, a number of MATLAB-installed functions will be ignored when called with no input arguments and with no empty parentheses. These are: false, true, pi, eps, nargin, nargout, mfilename, pwd, cd, Inf, NaN, clc, clear, rand, randn, i, j, filesep, tempname, tempdir, drawnow, NaT, date and now.

This check has an auto-fixer as well. Clicking the Fix all button in the report fixes all violations for this check, clicking the Fix all in this file button fixes all violations for this check for one file. The Fix on this line button applies the fix on one indivual line. For more information, see section Automatic fixes.

Configurable parameters

  • Exceptions (list): A list of additional functions that do not require empty parentheses when called with no input arguments.

  • IgnoreBuilt-ins (boolean): Set to true to have this check ignore MATLAB-installed functions and toolbox functions. If set to true, function names in the Exceptions list are still taken into account.

Limitations

  • Does not report calls to methods that have no input arguments besides an object and no empty parentheses. For example params = obj.getParameters will not be reported by this check.

Exemption tag: %@ok<INPAR>

checkOneStatementPerLine

Checks if there is at most one statement per line. For readability, it is advisable to have at most one statement per line.

Configurable parameters

  • AllowMultipleGlobalVars (boolean): Whether or not multiple global variables are allowed to be defined on the same line. The default value is true.

  • AllowMultiplePersistentVars (boolean): Whether or not multiple persistent variables are allowed to be defined on the same line. The default value is true.

Exemption tag: %@ok<OSTPL>

checkOperatorsLineContinuation

Checks if multi-line statements are split before or after binary operators. For example, consider the difference between the following two statements:

isValid = testsPass ...
    && validationPassed;

isValid = testsPass && ...
    validationPassed;

This check has an auto-fixer as well. Clicking the Fix all button in the report fixes all violations for this check, clicking the Fix all in this file button fixes all violations for this check for one file. The Fix on this line button applies the fix on one individual line. For more information, see section Automatic fixes.

Configurable parameters

  • OperatorPosition (string): Desired position of binary operators in multi-line statements. Can be StartOfLine (top example) or EndOfLine (bottom example). The default is StartOfLine.

  • CheckAssignmentEqualsSigns(boolean): Whether or not equals signs used in assignments need to be checked as well. The default is false.

Exemption tag: %@ok<OPLCO>

checkParenthesesLogicalOperators

This check reports any statements in which insufficient parentheses are used to clarify the precendence of logical operators. Any statement where the operator precedence affects the outcome must use sufficient parentheses. For example:

x = a && b || c; shall becomex = (a && b) || c;or x = a && (b || c);

When only one type of logical operator is used, operator precedence is irrelevant and no parentheses are required for this check. For example: x = a && b && c;

Configurable parameters

  • RequireParenthesesAroundCondition (boolean): Set to true to require parentheses around if and elseif-statements, even though these are not required to clarify operator precedence. For example:if a && bshould become if (a && b).

Exemption tag: %@ok<PARLO>

checkParenthesesMathematicalOperators

Checks if all statements with mixed mathematical operators use sufficient parentheses to clarify operator precedence. The mathematical operators that are checked are: +, -, /, *, and .``*. As an exception, + and - are allowed to be used successively without requiring parentheses for clarifying operator precedence because the order in which the operators are treated does not matter. In the HTML report at most one violation of the same type per line of code will be shown for this check. Some examples of code that will be reported by this check are:

x = 6 * 2 + 1;
y = 1 / 2 * 3;
z = 2 * pi + 2;

Some examples of code that will not be reported by this check are:

a = 6 * 2 * 1;
y = 1 + 2 - 3 + 5;
z = (2 * 3) + (5 * 2);

Exemption tag: %@ok<PARMO>

checkSubFunction

Checks if there are any sub functions used. Using sub functions is often discouraged because it can degrade code readability, testability and re-use. Use seperate function files instead of sub functions.

Exemption tag: %@ok<CSUBF>

checkSuppressAll

Checks if there are any MATLAB Code Analyzer messages being suppressed throughout the file. Code Analyzer messages should generally be prevented. If they are not prevented, they should be suppressed and have an accompanying comment stating the reason for suppression (not checked by checkSuppressAll). It is advisable not to do this throughout an entire file because the same warning may be helpful elsewhere.

Exemption tag: %@ok<SUPAL>

checkSurrBySpaces

Checks if certain operators are surrounded by spaces. Surrounding for example '=' by spaces makes the code more readable. This check excludes strings and comments.

This check has an auto-fixer as well. Clicking the Fix all button in the report fixes all violations for this check, clicking the Fix all in this file button fixes all violations for this check for one file. The Fix on this line button applies the fix on one indivual line. For more information, see section Automatic fixes. In the HTML report at most one violation of the same type per line of code will be shown for this check.

Configurable parameters

  • Operators (list): List of operators that must be surrounded by spaces. Allowed values are: =, :, ^, .^, ==, <=, >=, ~=, >, <, &, &&, |, ||, +, -, *, .``*, /, ./ and .\. By default, the value of this parameter equals the list of allowed values.

    • When you configure the check to look for :, code will not be reported as a violation when it is used for indexing. For example x(:, 1) or y{:} will not result in a violation, but 1:10 will.

    • If you configure the check to look for -, the check will only report violations if it is used as a subtraction, not to negate a value. So -5 ``*`` 2 will not be reported and 10-2 will.

  • SurroundNameValueEqualsSigns (boolean): Whether or not equals signs in name-value pairs when using the Name=value syntax should be surrounded by spaces (available since MATLAB R2021a). For example, when set to true, the following will be reported: plot(x, y, LineWidth=2) and when set to false, this will be reported as a violation: plot(x, y, LineWidth = 2). The default value is false. The behaviour of this check regarding equals signs in name-value pairs is applied regardless of the value of the Operators parameter. When you are not using MATLAB R2021a or newer, this parameter is ignored.

Exemption tag: %@ok<SURSP>

checkTabCharacterUsed

Checks if tab characters are used, since the length of a tab can vary it is therefore advised to use spaces instead. Using \t or char(9) is not reported instead. In case of multiple violations per line of code, only one violation per line is shown in the report. This check has an auto-fixer. Clicking the Fix all button in the report fixes all violations for this check, clicking the Fix all in this file button fixes all violations for this check for one file. The Fix on this line button applies the fix on one individual line. The auto-fixer inserts spaces. For more information, see section Automatic fixes. In the HTML report at most one violation of the same type per line of code will be shown for this check.

Exemption tag: %@ok<TABCU>

checkAvoidComments

This checks if undesired phrases like, for example, '% TODO' and '% WRONG' are present in the comments of your code. Such comments reduce the readalibity of the code and increase the uncertainty of readers and maintainers. This check only searches for the phrases at the start of comments.

Configurable parameter

  • AvoidComments (list): A list of phrases that are to be avoided in comments.

Exemption tag: %@ok<AVCOM>

checkBlockComment

Checks if any comment blocks are used. These may not be recommended because they could comment out more or less than you want. The comment blocks are recognized by %{ and %} on a line (optionally surrounded by whitespace).

Exemption tag: %@ok<BLCKC>

checkMethodAccessPermissions

Checks classdef files to see if any methods use different access permissions than their superclass (if any). If this is the case, the class cannot be instantiated and an error will be thrown indicating this problem. This checks method declarations as well as implementations thereof in the classdef file.

Limitations

If the classdef file could not be analyzed due to another problem (for example, invalid property definitions), no violation is reported by this check.

Exemption tag: %@ok<METAP>

checkMethodsInClassdef

Check if all methods that are declared in a classdef file are also implemented, and that the declaration is the same as the implementation. Also check that the declaration is the same as the implementation (i.e. do not declare varargin but have a method with (x,y,x) input arguments). Check that all methods that have an implementation in a seperate file are also declared.

Configurable parameters

  • AllowDifferentInputOutputNames (boolean): Set to true to have CC4M allow for differences in method input and output names between method declaration and implementation. By default, this parameter is set to false.

  • AllowVararginout(boolean): Set to true to have CC4M allow the use of varargin/varargout in method input and output declaration and implementation.

Exemption tag: %@ok<MDAMI>

checkNumberOfOutputsConstructor

Checks the number of outputs of a constructor, it is often desired to have only one output: an object of the class.

Exemption tag: %@ok<NOOCS>

checkPropertiesBeforeMethods

Checks if all properties blocks are before all method blocks in classdef files. For readability, it is advisable to have all properties blocks before the method blocks in classdef files.

Exemption tag: %@ok<PBBMB>

checkPropertyClassRedundancy

Checks if there are properties that contain the name of the class. For readability, it is advisable to not have redundancy in a property name.

Exemption tag: %@ok<PRCLR>

Security Checks

checkSecurityCertificateFilename

Checks if the weboptions and matlab.net.http.HTTPOptions classes are used securely:

  • The CertificateFilename property value shall not be empty. Using an empty certificate file name disables certificate validation.

Exemption tag: %@ok<SECCF>

checkSecurityConstantNames

Check if specific variable names are assigned as constants, names such as 'username', 'loginname', password, 'credentials' etc. The check is case-insensitive.

Configurable parameter

  • AvoidNames (list): A list of names that are to be avoided.

Exemption tag: %@ok<SECCN>

checkSecurityUsernamePassword

Checks if weboptions, matlab.net.http.Credentials, urlread and urlwrite are used securely:

  • The Username and Password properties shall not be directly set using strings or character arrays. Instead, their values shall be obtained externally.

Exemption tag: %@ok<SECUP>

checkSecurityXml

Checks if XML files are accessed securely. Insecure deserialization results in code execution. Specifically for XML this can result in DoS (Denial of Service) attacks when allowing the use of DOCTYPE declarations. This is well documented here.

Since MATLAB R2019b, you can prevent reading XML files that contain DOCTYPE declarations by setting the 'AllowDoctype' name-value pair of the xmlread function to false. This check will report a violation if the xmlread function is used without setting AllowDocType to false. For more information, see the xmlread reference page.

Since MATLAB R2021a, you can read XML files using the matlab.io.xml.dom.Parser class. By default, the AllowDoctype property of the parser's Configuration property is set to false. Therefore, this check reports a violation if the property is explicitly set to true, and not if the property is not set at all.

Exemption tag: %@ok<SCXML>

checkShellEscape

Checks if the shell escape function is used in the code. An exclamation point (!) indicates that the rest of the line is a command to the operating system. This is called a shell escape. As an alternative, you can use the MATLAB-installed function system. If your coding standards dictate that no system calls should be used, configure checkAvoidFunctions such that use of the system function is reported in addition to the shell escape function.

Exemption tag: %@ok<SHESC>

Metrics

There are a number of metrics that can be run by CC4M. These are explained in the following sections. When selecting the option Include metrics in the GUI, the full results of all metrics are shown. If this option is not selected, only the violations and errors encountered by the metrics are reported. For every metric, an exemption tag is given. For more information about this, see section Exemptions.

Meta data and summary

Under meta data, the following things are listed:

  • The time the check has finished.
  • The user that initiated the Code Checker.
  • A user comment that the user added to the report's content (if any), for example the pull request URL related to the run.
  • The selected job type/settings.
  • Environment information such as the CC4M version, MATLAB release, and platform.
  • The root folder of the selection. This can take on one of three shapes:
    • The full path of a file when a single file was selected.
    • The present working directory.
    • A selected folder.
  • The file(s) checked. If only one file was selected, this displays the name of the file. If more files were selected, this will show the number of checked files.
  • The number of files that could not be checked due to an error in the file (if any).
  • The number of failing checks (if any), sorted by priority.
  • The configuration file that was used to obtain the settings for each check. It includes a link to open the file.
  • The number of enabled checks and reports after applying priority filtering.
  • The number of disabled checks and reports and a link to an overview of the disabled checks/reports. This is not shown if there are no disabled checks.
  • Number of configuration problems:
    • Checks that have not been configured.
    • Check parameters that have not been configured.
    • Check parameters that have been configured more than once.
  • The reports folder in which CC4M reports and the installed toolbox information are stored.

The summary shows which checks have failed for at least one of the checked files. In case the Include passed checks option, see section Report, is enabled the summary contains information on all checks ran, which might include passed checks as well. The summary provides the following things:

  • Name of the report or check that failed.
  • Link to the results of that report/check. Click the name of the report/check to follow the link.
  • Status of the report/check per checked file. Since multiple files can be checked for the same rules, there can be more than one status per report/check.
  • Relative path to the checked file(s) that failed the check. Again, multiple paths per report/check can be reported.

If a file contains a parse error or invalid characters, CC4M cannot check it. The summary will include a list of all the checked files that contain a parse error or invalid character. The files can be clicked which will open the file in the MATLAB editor so that you can easily target the errors. These errors will also be reported by checkCodeInterpretable, see section checkCodeInterpretable.

Configuring reports folder

By default, any reports are stored as .html files in the default folder that contains the reports. For Windows this is:

%APPDATA%\Roaming\cc4m\cc4m_reports

For Mac this is:

~/Library/Application Support/cc4m/cc4m_reports

For Linux this is:

~/.matlab/cc4m/cc4m_reports

This folder can be changed by using the Report tab in the GUI. If you enter a reports folder that does not exist, CC4M will create it and activate it. From then on, the selected folder will be used to store CC4M reports and a list of installed toolboxes. If you select an invalid folder name (for example with invalid characters in it), CC4M reports will be stored in the folder you had enabled before. Changing the reports folder can also be done from the command window using:

monkeyproof.cc4m.setReportsFolder('C:\Software\CC4M\Reports');

reportFunctions

reportFunctions gives a list of all functions defined in the file, including nested functions and sub functions. For every function, the following data is given:

  • The name of the function and a link to its definition

  • The type of function (constructor, method, function, sub-function, nested function)

  • The number of inputs and outputs of the function

  • Whether or not the function ends with end

Note: this does not report declarations of methods whose function is defined in a separate file. For example, the following method definition will be reported:

methods (Static)
    function nrOut = powerSix(nrIn)
        nrOut = nrIn^6;
    end
end

but the next method declaration (with powerSix in a separate function file) will not:

methods (Static)
    nrOut = powerSix(nrIn)
end

Exemption tag: %@ok<RFUNC>

reportVariables

reportVariables provides a list of all variables defined in the file that is checked. For every variable, the following data is given:

  • The name of the variable and a link to the line on which the variable is initiated.

  • The scope of the variable. The scope indicates the function that has knowledge of the variable. In case of shared variables in nested functions, only the function scopes where variables are assigned or updated are mentioned in the report.

  • The type of the variable. This can be: Input, Output, Input & Output, Shared (nested), Global or Persistent. In case of an empty Type, the variable is a local variable.

  • The data type of the variable. In case the data type is detected, it will be reported.

  • The use of the variable - if it is a constant, a computed index (For example: a = find(``[``0 0 1``]``);) or the index of a FOR-loop.

Exemption tag: %@ok<RVARI>

reportDependencies

The file may use functions not defined in the file itself. These dependencies and additional information, are listed under reportDependencies.

For every valid dependency, the following is given:

  • The name of the dependency

  • The call itself and a link to the line on which the function is called

  • The type of function if known (Local, nested etc.)

  • The file on which the current file depends

  • The function that uses the dependency (Caller)

An example of two dependencies as reported by CC4M is given in figure Two examples of reported dependencies.

Two examples of reported dependencies

Two examples of reported dependencies

Unknown dependencies can be recognized by the Function source column. A dependency is considered unknown if:

  • The function does not exist.

  • The function is not on the path during the CC4M run. As described in section General, the code selected for checking is temporarily added to the path.

  • It is a function handle, or created/used in an eval-like construction.

  • It is a dynamic reference to a package function or method.

Limitations

  • Accessing undeclared variables or variables loaded with the load function without outputs could lead to unknown dependencies being reported.

  • If a dependency is used as a variable within the same scope, the dependency is not reported. This also holds when the dependency is used as a function before the variable is declared.

Configurable parameters

  • DoReportBuiltinDependency (boolean): If set to true, MATLAB-installed functions must be shown in the dependency report. The default value for this parameter is true.

  • DependenciesUniqueGlobal (boolean): If set to true, uniqueness of dependencies is global shown over all checked file, only relevant if multiptle files checked. If set to false, uniqueness of dependencies is per file. The default value for this parameter is true.

  • DependenciesUniquePerFunction (boolean): If set to true, uniqueness of dependencies is shown per function, only relevant if single file checked. If set to false, uniqueness of dependencies is shown per file. The default value for this parameter is true.

Exemption tag: %@ok<RDEPE>

reportComplexity

In this report, you can find the cyclomatic complexities of all checked scripts and functions. The cyclomatic complexity is a measure of the number of linearly independent paths through a script or function. Higher cyclomatic complexity generally means more complex code.

Configurable parameters

  • MaxComplexityMainFunc (double): The maximum complexity for the main function. The default value for this parameter is 15 and it can be changed to anywhere between 3 and 50.

  • MaxComplexityScript (double): The maximum complexity for a script. The default value for this parameter is 20 and it can be changed to anywhere between 3 and 50.

  • MaxComplexityConstr (double): The maximum complexity for a constructor. The default value for this parameter is 20 and it can be changed to anywhere between 50 and 250.

  • MaxComplexityMehod (double): The maximum complexity for a method in a classdef file, methods in a separate file are treated as main function. The default value for this parameter is 15 and it can be changed to anywhere between 3 and 50.

  • MaxComplexitySubFunc (double): The maximum complexity for a sub-function. The default value for this parameter is 10 and it can be changed to anywhere between 3 and 50.

  • MaxComplexityNestFunc (double): The maximum complexity for a nested function. The default value for this parameter is 3 and it can be changed to anywhere between 1 and 10.

Exemption tag: %@ok<RCOMP>

reportBinaryExpressions

This report is especially relevant for m-code that will be used for code generation. It reports all binary expressions for which the order of evaluation might matter. For this report, an expression is a binary expression if it uses a binary operator. These operators are: :, ^, ==, <=, >=, ~=, >, <, &, &&, |, ||, +, -, *, .``* and /. An expression will be reported by reportBinaryExpressions if any of these are met:

  • A user-defined function is called on both sides of the operator.

  • A user-defined function is called on one side of the operator and a relevant variable is accessed on the other side of the operator. Relevant variables are:

    • Handle objects.

    • Persistent variables

    • Global variables

If a variable is accessed for which the datatype could not be reliably obtained, it is also considered a relevant variable when the fourth preference described in section Preferences is set to false. The datatype of variables used in the code are unknown for example for the inputs of the checked main function, or outputs of user-defined function calls. Disabling the preference may lead to fewer (incorrect) results being reported.

Exemption tag: %@ok<BINEX>

reportCellArrays

reportCellArrays reports all expressions that assign or create cell arrays that are not arrays of character arrays or arrays of heterogeneous objects. Cell array assignments where the cells are of unknown type are reported based on a parameter value. Using cell arrays for for example numbers or logicals is often discouraged because it is unnecessary, more difficult to read, or because it leads to poorer performance. By using the fourth preference described in section Preferences, you can choose whether or not to ignore cells of unknown datatype for this report. CC4M cannot reliably determine the datatype of the cell assigned in every case. For the unknown cases, you can choose whether to report them or not. If this is set to false, all results that are reported are violations for which it is certain the assigned cell is not an object nor a character array.

Note: Since R2023a is it possible to assign values in dictionaries with cell values using curly braces, {}. These will be treated in the same fashion as assignments in cell arrays.

Exemption tag: %@ok<CELAR>

reportComparisons

In this report, all comparisons made with == or ~= are reported if any of its operands may be a non-integer number. Comparing two doubles using == or ~= that are not guaranteed to be whole numbers is not recommended because it can lead to unexpected results. This report lets you inspect the relevant comparisons yourself to make sure the comparisons work as intended. If necessary, you can adjust certain comparisons by adding a tolerance. The code analysis of CC4M attempts to determine what data types the operands of the comparison have. This can have three different results:

  • When any of the operands is known to be a single or double that is not always a whole number, the comparison is reported as a violation and you will see the result in red text.

  • When both operands are known to be whole numbers or non-numeric, the comparison is not reported.

  • In other cases, the comparison is reported and manual inspection is required to determine whether the comparison is acceptable, or whether a tolerance must be added. These cases will only be reported if the Report violations when not entirely sure preference is switched on. See section Preferences for a description of this preference.

The following example shows what will be reported and what should be used instead:

out = myFcn(in) == sqrt(3);

% Instead use:
out = abs(myFcn(in) - sqrt(3)) < 1e-12;

Exemption tag: %@ok<COMPA>

reportMexFiles

This reports the mex-files the checked code depends on, and also reports whether or not the mex-files for the specified platforms are found. This information provides insight into what mex-files are used, and it can also be used to determine whether the code has a chance to work on different platforms.

Configurable parameters

  • RequiredExtensions (list): Mex-files with these extensions must be checked by this report. Allowed values are: mexa64, mexmaci64, mexw32, and mexw64.

Exemption tag: %@ok<RMEXF>

Configuration Editor

The Configuration Editor lets you interactively configure the CC4M's checks such that they reflect your coding rules. You can also adjust one of the predefined configurations to your liking.

Opening the Configuration Editor

The Configuration Editor can be opened in multiple ways:

  • From the GUI using the Open button on the Configuration tab.

  • By calling monkeyproof.cc4m.openConfigurationFile(configFile); where configFile is an optional input: the configuration file to edit and activate. If left out, the currently active configuration file is opened.

  • By clicking one of the links in a CC4M report:

    • In the Metadata section, the Open button next to the configuration file path.

    • At a check's information, the Open check configuration link. If the check is not yet configured, you will be prompted to add it to your configuration file so that you can edit it.

    • In the parameter information table of a check, the Open link. If the parameter is not yet configured, you will be prompted to add it to your configuration file so that it can be edited.

As the Configuration Editor opens, the active configuration file is validated against a Schema file. If it succeeds, you will see an interface as shown in the figure below. If the Schema validation fails, you will see a message describing why it fails. The configuration file can not be loaded and you will have to either open another configuration file, or edit the current configuration file in a text editor and try to open it in the Configuration Editor again.

After successfully opening your file, you will see the following things:

  • The full path of the currently opened configuration file.

  • The editable description of the configuration file.

  • A list of CC4M checks and reports with for each check/report the following information:

    • Rule identifier

    • Reference number

    • Description

    • Name

    • Whether or not they are enabled.

If you already have an opened Configuration Editor in the current MATLAB session, the actions listed above will simply bring the window forward.

Note: In MATLAB R2017b, minimized Configuration Editor windows will remain minimized when one of these actions are performed. Resizing the application may not work properly for MATLAB R2017b. Maximizing the window makes sure all controls are at least accessible.

The Configuration Editor after it has just opened

The Configuration Editor after it has just opened

Editing the configuration of a check

You can enable or disable checks by checking or unchecking the checkbox on their respective rows. You can also enable or disable all checks at once using the Enable all/none button right above the Enabled column. Clicking a check's name or description will display its configurations on the right, like shown in the figure below. You can now see and/or edit the following:

  • The buttons Clone and Remove, will be discussed in Clone and remove check configurations.

  • The check's description. This will also be displayed in CC4M reports.

  • Whether or not to enable the check.

  • The priority of the check. Options are Recommended, Strongly recommended, and Mandatory.

  • The severity level of the check, can be in the range from 1 to 10. The most important ones are of severity level 1 and next levels are reserved for more pedantic issues. The severity levels are derived from the following webpage.

    • 1 - Certainly a programming error

    • 2 - Very likely a programming error

    • 3 - Programming pitfall/undesired programming construct/accident waiting to happen

    • 4 - Design issue with high impact on reliability or maintainability'

    • 5 - Design issue with low impact on reliability or maintainability

    • 6 - Portability or performance issue or high impact other issue

    • 7 - Comment related issue or medium impact other issue

    • 8 - Naming convention or low impact other issue

    • 9 - Style related issue

    • 10 - Controversial issue or issue with a relatively high false positive rate

  • Categories of the check. Use this to tie the checks to groups of coding standards. The value shall be a semicolon-separated list of categories.

  • A rule link for linking the check to a rule. Weblinks should start with https:// or http://.

  • The Go to button that goes to where the rule link is pointing, if the rule link field is empty, this button is disabled.

  • The rule identifier.

  • If the check has configurable parameters, their names and descriptions are shown. By default, the first parameter in the table is selected and its details are shown below the table.

The Configuration Editor after a check is selected

The Configuration Editor after a check is selected

Selecting a parameter will show the parameter description and its value(s). By default, the first parameter of a check is selected (if there are any) when the check is selected in the checks table. Depending on the data type of the parameter, different components are used to edit the parameter value:

  • For boolean parameters, a switch to choose between True and False is shown. This is also shown in the figure below.

  • For parameters of type double, a numeric text field is shown that applies the minimum and maximum values of the parameter.

  • If parameters of type string have any allowed values, a dropdown menu is shown that lets you select one value.

  • Parameters of type string that have no allowed values, a textbox is shown that lets you type the parameter value.

  • For parameters of type list, a dropdown menu is shown if there are allowed values. Depending on the parameter, one or more parameter values can be selected.

  • If there are no allowed values, parameter values of type list can be typed in a text box using one value per line.

The Configuration Editor after a check and parameter have been selected

The Configuration Editor after a check and parameter have been selected

Selecting a different check or parameter after editing one will store any edited values so these will not be lost. Clicking Save or Save as... lets you save the configuration file such that the updated configuration file can be used for checking your code. Please note that the configuration file is generated using the global description and the checks and parameters as they are in the Configuration Editor. This means that if your configuration file contained comments or empty lines before, they will no longer be there. If you are editing a predefined configurations file shipped with CC4M (see section Predefined Configurations), the Save button will be disabled because it is not allowed to save configuration files in the folder for predefined configurations. You will have to save the file in a different location.

Note: Creating, opening or saving a configuration, selects it as the active configuration in CC4M.

Find checks efficiently

With the large amount of checks CC4M provides, it may be difficult to find what you are looking for. For this reason, you can use the search bar above the table of check configurations to filter the rows in the table. When searching, keep the following in mind:

  • Separate multiple search terms using spaces.

  • A check configuration is found if at least one of the search terms is found in (part of):

    • The rule identifier (column 1 in the table)

    • The rule description (column 3 in the table)

    • The check's name (column 4 in the table)

    • The categories of the check's configuration

    • The parameter descriptions of the check configuration. These are not editable.

  • You can filter the checks by priority by entering Mandatory, Strongly recommended or Recommended.

  • Show only the enabled/disabled checks by searching for Enabled or Disabled.

  • The search is case-insensitive.

  • Show all check configurations by clearing the search bar.

Adding missing checks and parameters

If you update the CC4M release you are using, checks and parameters may have been added to the tool that are not configured in your configuration file yet. If you load such a configuration file in the Configuration Editor, you will see the Add missing elements button above the configuration's description. The checks and parameters do not show up in the table of checks or the table of parameters (on the right). Clicking Add missing elements will add the missing checks and parameters to the bottom of the configuration using default values. A dialog will show which checks and parameters were added, such that you can easily configure them to have them reflect your coding standards.

Clone and remove check configurations

As discussed before in section Multiple configurations per check, it is possible to have more than one configuration per check, provided that the ruleID is different for all configurations of the check. If a check that has configurable parameters is selected in the Configuration Editor, the Clone button will be enabled. Clicking Clone will clone the selected check and you can start editing this new configuration of the check. In figure The Configuration Editor after a check and parameter have been selected a check with configurable parameters is selected and therefore the Clone button is enabled. In case a check is configured more than once, it is possible to remove additional configurations. Clicking Remove will remove the selected check configuration. The Remove button is only present in case a check is selected that is configured more than once.

Reference configurations

As discussed before in section Referencing configurations it is possible to reference other configurations from within the Configuration Editor. This can be done from the second tab, the Referencing tab, see the figure below. One can reference a custom configuration file by browsing to the file. The custom configuration file will be added after the Confirm button has been clicked. One can reference a predefined configuration by selecting via the dropdown menu. The predefined configuration will be added after the Confirm button has been clicked.

The Configuration Editor when predefined configuration MonkeyProof MATLAB Coding Standard++ has been selected.

The Configuration Editor when predefined configuration *MonkeyProof MATLAB Coding Standard++* has been selected.

If a custom configuration file or a predefined configuration has been successfully incluced a confirmation dialog will be shown. The dialog contains information on how many checks have been included. Only enabled checks will be included. Identical check configurations from a referenced configuration (file) will not be included since they do not lead to unique results. After including a referenced configuration, a tree of the referenced configurations will be shown in the Configuration Editor, see the figure below. After including predefined configuration MonkeyProof MATLAB Coding Standard++, a number of check configurations have been added. To distinguish between the check configurations that originate from the active configuration file and the ones that are referenced, all check configurations will have a Reference number as can be seen in the second column (Ref) of the list of CC4M checks and reports. For check configurations that originate from the active configuration file Reference number = 1 , for check configurations referenced from the predefined configuration MonkeyProof MATLAB Coding Standard++, Reference number equals 2. To remove all check configurations from a referenced configuration, click the Remove button.

The Configuration Editor after predefined configuration MonkeyProof MATLAB Coding Standard++ has been included.

The Configuration Editor after predefined configuration *MonkeyProof MATLAB Coding Standard++* has been included.

After selecting a referenced check in the the list of CC4M checks and reports the following icon image illustrates that it's about a reference. If one wants to delete a referenced check configuration, after selecting the specific referenced check, click the Delete button, similar to the Remove button as discussed in section Clone and remove check configurations. If one wants to clone a referenced check configuration, after selecting the specific referenced check, click the Clone button. After cloning the clone will be part of the active configuration file and will no longer be linked to the referenced configuration file.

Predefined Configurations

As described in section Configuration, you can select a predefined configuration and use it for checking your code.

The predefined configurations currently available are:

  • MonkeyProof MATLAB Coding Standard: A generic and complete set of configurations that reflects the MonkeyProof MATLAB Coding Standard created in agreement with renowned companies that use CC4M.

  • MonkeyProof MATLAB Coding Standard++: This set of configurations contains the configurations of the MonkeyProof MATLAB Coding Standard and adds naming conventions to it. It is useful for anyone who wants to write clean, readable and stable m-code. The coding standards document for this is available on our website.

  • MATLAB Coder-compatibility: Use this configuration to help you identify parts of your code that are (potentially) not Coder-compatible - or might result in different behaviour. M-code that is not Coder-compatible cannot be used to generate C or C++ code. The coding standards document for this is available on our website.

  • MATLAB Compiler-compatibility: Use this configuration to help you identify parts of your code that are (potentially) not Compiler-compatible - or might result in different behaviour. M-code that is not Compiler-compatible cannot be used for deployment of your code. C++ code. The coding standards document for this is available on our website.

  • MAB/MAAB: The latest MAB (Mathworks Advisory Board) coding standards (previously MAAB) incorporate the modeling rules of JMAAB v5.1 and MAAB v3.0. Also see the Mathworks. The MAB coding standards are for the usage of MATLAB, Simulink, Stateflow and Embedded Coder. The standards for MATLAB are configured in this predefined set of configurations.

  • JMAAB: The JMAAB (Japan MATLAB Automotive Advisory Board) has developed a set of coding standards mostly for Simulink models. There are several standards for the MATLAB code of your models, which are configured in this predefined set of configurations.

After installing the CC4M toolbox, the predefined configuration MonkeyProof MATLAB Coding Standard++ becomes active.

If you want to open one of these configurations, switch to Predefined on the Configuration tab of the CC4M GUI, select the configuration of your choice and click Open and the Configuration Editor opens. If you want to save the configuration, the Save button will be disabled, because it is not allowed to save configuration files in the folder for predefined configurations. You will have to save the file in a different location, with Save as. The configuration file is then considered a Custom configuration.

You can obtain a list of all available configurations by using

configFiles = listPredefinedConfigurations()

which returns a cell array of all predefined configurations shipped with CC4M.

From the MATLAB command window a predefined configuration can be activated by using

monkeyproof.cc4m.activateConfigurationFile('MonkeyProof MATLAB Coding Standard++')

(with MonkeyProof MATLAB Coding Standard++ the name of the predefined configuration set) and a configuration will open in the Configuration Editor by using

monkeyproof.cc4m.openConfigurationFile('MonkeyProof MATLAB Coding Standard++')

Pro Features

This section describes the features available when you have obtained a Pro license for CC4M. These features are about the MATLAB command window interface. You can check whether or not you have a Pro license by tyring to use the command window interface. As example, have a file open in the MATLAB editor and call

>> monkeyproof.cc4m.start('-editor');

If this is not working you do not yet have the Pro license. If you are interested in the Pro license, contact us at info@monkeyproofsolutions.nl. For support, Pro users can send an e-mail to support@monkeyproofsolutions.nl. We aim to get back to you within one workday. Alternatively, you can check out our Code Checker for MATLAB forum.

Run from the command window

Calling monkeyproof.cc4m.start without input arguments opens the graphical user interface that lets you choose what files to check and how. Almost all of these options are also available from the MATLAB command window. In the different options and syntaxes described in this section, character vectors and cell arrays thereof are used. The same options can also be used using strings and string arrays.

Select files for checking

The file(s) or folder to run CC4M on can be set using the following syntaxes:

>> monkeyproof.cc4m.start('file', location);

Runs the checks on the file(s)/folder location (absolute path).

  • If location is a MATLAB file (.m or .mlx), only that specific file is checked.

  • If location is a cell array of MATLAB file names or a semicolon-separated list of MATLAB file names, these are all checked.

  • If location is a folder, all MATLAB files in that folder (non-recursively) are checked.

  • If location is a file with extension .txt, the file is read and the list of MATLAB files within it is checked. All files listed in the txt-file must be on a separate line.

  • If location is a file with extension .prj, the files in the given MATLAB project are checked. The project will be loaded (closing the open project if any) before checking the code.

Instead of providing the file/folder/project to check directly in the input, the following options can be used:

>> monkeyproof.cc4m.start(option);

Where option can be one of the following:

  • '-editor' runs the checks on the file that is currently open in the MATLAB editor (if there is one open and it is an m-file). Even though Live Editor files can be checked using CC4M, this option does not support it and you will have to enter the Live Editor file using another option.

  • '-pwd' runs the checks on the current working directory (as would be returned by MATLAB when calling function pwd).

  • '-browse' lets you browse for a folder whose files to check. Browsing for a file to check is not supported by this option.

  • '-currentProject' runs the checks on the files of the currently open MATLAB project.

Additional options

The runPriorities parameter can be used to run only the checks with the given priorities. The syntax for doing this is as follows:

monkeyproof.cc4m.start(_, 'runPriorities', {'Recommended', 'Strongly recommended'});

This would run all checks (that are not disabled by your configuration file) with priority Strongly recommended and Recommended. The supported priorities are: Mandatory, Strongly recommended, and Recommended. If the parameter is omitted from the inputs, checks with all priorities will run. This option applies check filtering on top of what is configured in your configuration file.

The runSeverities parameter can be used to run only the checks with a severity level below or equal to the maximum level set. The syntax for doing this is as follows:

monkeyproof.cc4m.start(_, 'runSeverities', 5);

This would run all checks (that are not disabled by your configuration file) with a severity level between 1 and 5. The supported severities are in the range of 1 through 10. The most important ones are of severity level 1 and next levels are reserved for more pedantic issues. If the parameter is omitted from the inputs, checks with all severity levels will run. This option applies check filtering on top of what is configured in your configuration file.

Additional options can be provided as input arguments to further customize the run. The syntax is as follows:

monkeyproof.cc4m.start(_, option1, _, optionN);

where option1 through optionN can be the following:

  • '-recursive' is used when a folder is selected. It makes sure all files in all subfolders of the selected folder are also checked.

  • '-changedOnly' removes files that have not changed with respect to a Git or SVN repository from the list of files to check. If no repository is found or the selected folder is outside a repository, no files are checked.

  • Including '-includeMetrics' in the inputs causes CC4M to include full reports of all metrics, even if there are no violations.

  • '-reportPassed' causes the CC4M report to contain results for all checks, even those that have passed. If a check passed without violations, only its configuration values are shown.

  • '-ignoreExemptions' runs the checks and all exemptions are ignored. This means that if code is marked as exempt from specific checks, it is still reported as a violation if it violates the rules.

  • When checking the files in a MATLAB project, you can add option '-skipTests' to have CC4M skip all project files labeled Test. When not checking a MATLAB project, this option is ignored.

  • '-doNotOpenReport' disables opening of the created report after the run.

  • '-skipLargeFiles' lets you automatically skip large files so that they will not be checked when selected. You can set which files are considered 'large' by using

    monkeyproof.cc4m.setPreference('FileSizeThresholdKb', sizeInKb);

Additionally the file location of the created report can be returned:

fileLocation = monkeyproof.cc4m.start(_);

Setting the MATLAB path

In order to make sure that the right folders are on the MATLAB path at the time of checking, an additional input parameter can be provided. The syntax is as follows:

monkeyproof.cc4m.start('matlabPath', 'C:\Files\myFolder;C:\AnotherFolder');
monkeyproof.cc4m.start('matlabPath', 'C:\Files\MyDocuments\MyPath.txt');

The MATLAB path to set can be a semicolon-separated character array of the different parts of the path. Alternatively, the path can be provided in a txt-file. This text file can have the different parts of the path on separate lines, or they can be separated by semicolons.

The path used during the CC4M run is set as follows:

  1. Keep all folders that contain MATLAB-installed functionality on the path.

  2. Keep all CC4M code on the path.

  3. Add the parts of the path specified in the input by the user to the path.

The approach listed above allows you to specify only the paths of the code that you want to check and of the local code it depends on.

Some additional remarks regarding this feature:

  • It is not a problem if the same folders are added to the path multiple times.

  • After the report has been generated, the original MATLAB path is restored.

  • If this option is used, the code selected for checking is not added to the MATLAB path if the path you specify does not say so.

Adding an additional comment to the report

It's optional for the user to add an additional comment to the report, for example the URL of the pull request that triggered the CC4M run. The syntax is as follows:

>> monkeyproof.cc4m.start(..., 'comment', 'I-Triggered-The-CodeCheckerForMATLAB-Run');

System integration

In order to integrate CC4M in your (continuous integration) systems, you may want to utilize the additional capabilities described in this section. The feature to generate a JSON report is not available with a Pro license by default. If you wish to use them, please contact us at info@monkeyproofsolutions.nl. The feature to generate a JSON summary is available with a Pro license.

Generating JSON reports

By adding '-generateJSON' to the inputs of your call to monkeyproof.cc4m.start, a JSON report will be generated instead of an HTML report. The versatility of JSON allows you to integrate the results with other tools or programming languages. Together with the command window interface described in section Run from the command window, your code can be checked automatically (for example using hooks, or periodic triggers) and the results can easily be stored and interpreted at a later point in time. This facilitates analyzing your coding rules compliance over time, which can be especially advantageous to your development process when running CC4M on a designated computer.

The JSON report is saved to the same location as HTML reports would be. This location can be obtained using monkeyproof.cc4m.getReportsFolder() and changed using

monkeyproof.cc4m.setReportsFolder(<The/Folder>). The report has extension .json. This option is not available from the graphical user interface.

The elements of the JSON report are as follows:

  • MetaData: Global information regarding the run.

    • CheckPrioritiesRun: The priorities of the checks that were run.

    • MatlabPath: Can assume one of several forms:

      • “Custom” indicates that a custom MATLAB path was provided for the CC4M run.

      • “Local” means that no changes were made to the path for the CC4M run.

      • “xxxx.txt” where xxxx is the absolute path to a text-file indicates that the MATLAB path was provided using a text-file.

    • Version: CC4M release number.

  • MatlabErrors: Information on what files could not be checked due to errors in them.

    • FileName: Path of the file containing the error(s).

    • ErrorMessages: One or more error messages and the location of their source.

      • Msg: The error message as given in the MATLAB editor.

      • LineStart: The line number at which the error is shown.

      • LineEnd: The end line of the cause of the error.

      • ColumnStart: The start column at which the error is shown.

      • ColumnEnd: The end column of the error.

  • CheckResults: Per checked file, the results.

    • FileName: Path to the file that is checked.

    • Checks: List of checks and their results.

      • Name: Unique name of the check.

      • CheckResult: Status of the check. For example “fail”.

      • RuleID: Identifier of the rule.

      • RuleLink: URL of the rule.

      • Priority: Priority of the check as configured. Can be “Recommended”, “Strongly recommended”, or “Mandatory”.

      • SeverityLevel: Severity level of the check as configured. Severity level of the rule can be in the range from 1 to 10. The most important ones are of severity level 1 and next levels are reserved for more pedantic issues.

      • DefaultConfig: true if the default values of a check or parameter were used due to problems with the configuration. This is the case when a check is configured multiple times, if it is missing from the configuration file, or if a check's parameters are configured more than once or not at all.

      • ReferencedConfig: If applicable, the referenced set of configurations the check configuration came from. This field is not there if the check configuration is defined in the active set of configurations.

      • Results: Information on the possible violations of the check. Per violation:

        • Msg: Description on what went wrong.

        • LineNr: Line number at which the violation was detected.

        • ColNr: Column at which the violation was detected.

        • IsExempt: Whether or not the violation is exempt from the rules.

        • ExemptionReason: The comment on the line of code after the exemption (if any).

Generating JSON summary

By adding '-generateJSONSummary' to the inputs of your call to monkeyproof.cc4m.start, a JSON summary will be generated together with the HTML report. The JSON summary can easily be integrated with other tools or programming languages. Together with the command window interface described in section Run from the command window, your code can be checked automatically (for example using hooks, or periodic triggers). This facilitates analyzing your coding guideline compliance over time. And if, based on the information in the JSON summary, you want to see all detailed results, one can open the HTML report corresponding to the run.

The JSON summary is saved to the same location as HTML reports. The summary has extension .json. This option is not available from the graphical user interface but unlike the JSON report, this feature is available with a Pro license by default.

The elements of the JSON summary are as follows:

  • MetaData: Global information regarding the run.

    • RunDuration:Message containing the number of violations for X rules in Y files out of Z files with the elapsed time.

    • TimeOfCheck:Date and time the run is executed.

    • UserName:Name of user that executed the run.

    • UserComment:A user comment that the user added to the report's content (if any), for example the pull request URL related to the run.

    • Settings:Settings for the run. Such as: file/folder/project, including subfolder, all files or only local changes, priorities selected etc.

    • EnvironmentInfo:lnformation about the environment.

      • CodeCheckerVersion:CC4M release number.

      • MATLABVersion:MATLAB release number.

      • OperatingSystem:The operating system.

    • RootFolder:Comon root of the files checked.

    • ReportsFolder:Folder that contains both the JSON summary and the HTML report.

    • HTMLReport:Link to the HTML report that contains the complete set of results.

    • TrialInfo:If applicable, information about the expiring trial license.

  • Results: The results.

    • FilesChecked:Path to the files that are checked.

    • NrChecksRun:The total number of checks ran.

    • NrViolations:The total number of violations.

      • PerCheck:Results per check.

        • RuleID: Rule identifier the check is related to.

        • CheckName: Name of the check.

        • Priority: Priority of the rule.

        • SeverityLevel: Severity level of the rule.

        • NrViolatedFiles: The number of files that violate this rule.

        • NrViolations: The number of violations.

    • PerPriority:Results per priority.

      • Mandatory: The number of rules with priority Mandatory that got violated.

      • StronglyRecommended:The number of rules with priority Strongly Recommended that got violated.

      • Recommended:The number of rules with priority Recommended that got violated.

    • FilesWithError:List of files that could not be checked due to errors in them.

  • Configuration: Information about the used configuration.

    • Type:The type of the configuration used; Predefined or Custom.

    • Name:The name of the configuration used.

    • NrChecks:The number of enabled checks and reports after applying priority filtering.

    • NrReferencedChecks: The number of check configurations that came from referenced sets of configurations (if any).

    • NrReferencedConfigs: The number of referenced sets of configurations used for the currently active set of check configurations (if any).

    • ReferencedConfigs: A list of referenced sets of configurations used for the currently active set of check configurations (if any).

    • NrCustomChecks:The number of custom checks in the configuration.

    • NrDisabledChecks:The number of disabled checks and reports.

    • NrMissingConfigs:The number of missing checks configurations.

    • MissingConfigs:The missing checks configurations.

    • NrDuplicateConfigs:The number of duplicate checks configurations.

    • DuplicateConfigs:The duplicate checks configurations.

    • NrMissingParamConfig:The number of missing parameter configurations.

    • MissingParamConfig:The missing parameter configurations.

Function Reference

Generic:
monkeyproof.cc4m.startOpen the CC4M GUI.
monkeyproof.cc4m.showLicenseAgreementShow license agreement
monkeyproof.cc4m.showLicenseDialogShow license dialog
Manage Configuration:
monkeyproof.cc4m.getConfigurationFolderGet folder where configurations are stored.
monkeyproof.cc4m.setConfigurationFolderSet folder where configurations are stored.
monkeyproof.cc4m.getActiveConfigurationFileGet current active configuration file.
monkeyproof.cc4m.activateConfigurationFileActivate a configuration file.
monkeyproof.cc4m.getConfigurationFilesGet available configuration files in the configuration folder
monkeyproof.cc4m.createConfigurationFileCreate a new configuration file using default values and optionally activate it.
monkeyproof.cc4m.updateConfigurationFileAdd missing check configurations to a configuration file.
monkeyproof.cc4m.openConfigurationFileOpen a configuration file in the Configuration Editor.
monkeyproof.cc4m.listPredefinedConfigurationsReturn a list of predefined configurations.
Manage reports folder:
monkeyproof.cc4m.getReportsFolderGet the location where CC4M reports are stored
monkeyproof.cc4m.setReportsFolderChange the location where CC4M reports are stored. If the given path refers to a non-existing location, the folder is created.
Exemptions:
monkeyproof.cc4m.getExemptionGet the exemption tag for a given check name.
monkeyproof.cc4m.getAllExemptionsGet a table with the exemption tag for every check.

start

showLicenseAgreement

showLicenseDialog

getConfigurationFolder

setConfigurationFolder

getActiveConfigurationFile

activateConfigurationFile

getConfigurationFiles

createConfigurationFile

updateConfigurationFile

openConfigurationFile

listPredefinedConfigurations

getReportsFolder

setReportsFolder

getExemption

getAllExemptions

System Requirements

  • MATLAB R2017b or newer with JAVA running.

  • Optional: Simulink supported,

  • Optional: Stateflow supported,

  • Optional: Simulink Check (Simulink Validation & Verification) integration with Model Advisor provided.

  • Optional: For version control integration, Git and/or SVN must be installed.

  • For optimal performance and availability of options, it is recommended to use the most recent MATLAB release available.

Considerations and Known Limitations

Platform-specific:

  • When using Linux, you may encounter an error when trying to open the CC4M GUI. This problem can be solved by following the steps described here.

  • When using MAC combined with R2020b, hyperlinks in the report generated by the Code Checker may not work. The issue is fixed with R2021a or R2020b update 3.

Generic:

  • PDF version of the manual has no working links to the detailed function references in.

  • If you use a version of CC4M within a unsupported (newer) MATLAB release, you may experience unexpected behavior or see unexpected results. A warning will be shown in the command window that can easily be disabled for future Code Checker runs. In the CC4M Release notes the supported versions of MATLAB releases is announced.

Simulink & Model Advisor Integration:

  • The Simulink Model Advisor is only supported for M-functions in Simulink or Stateflow - checking a set of M-files is only supported using monkeyproof.cc4m.start.

  • Automated fixes are not available.

Code analyis:

  • MATLAB files with invalid names can not be analyzed.

  • Methods in a classdef file can not be separately analyzed, only as part of the classdef file they are defined in. The code analysis is performed on a code file, not on a part of that file.

  • The code analysis relies on undocumented features.

  • The detection of data types of variables is imperfect. This may cause unexpected results. See Appendix Datatype detection for more information on what is and what is not detected.

  • During the analysis, property values may be initialized when gathering class information, if the checked code has class definitions among them. This may cause unexpected behaviour if the calculation of the initial values of properties deals with peripherals such as printing to the command window or reading from or writing to files. Potential errors during the initialization of properties are caught and will not interfere with the code analysis.

Code Checks and Code Reports:

  • Class properties are sometimes reported as fields (of a structure) when assigned values in functions or methods.

  • The dependency analysis ignores function handles or eval-like constructions.

  • In MATLAB versions before R2018b, dependencies on MATLAB-installed functions can be reported as local when an overloaded implementation of the function exists higher on the MATLAB path.

  • In MATLAB versions before R2021b, checks depending on editor warnings might give inaccurate results and incorrect line number information.

Other:

  • A disabled fix button in the report indicates that the fix callback has been executed. It does not reflect the current state of the code. To assure that the code has been fixed correcly, rerun the check and verify that the offending code is no longer reported.

  • Calling clear classes after using the CC4M user interface or the Configuration Editor can cause warnings about not being able to clear certain classes because objects exist of those classes. In order to prevent these warnings, call close force all before clear classes. As an alternative, you can choose to ignore or suppress these warnings because the classes that cannot be cleared are generally not the reason for calling clear classes.

  • In MATLAB R2017b, the color of the switches in the CC4M GUI may differ from those in more recent MATLAB releases.

Release notes

v2.14.0 - April 2024

  • Supports MATLAB R2023b.

v2.13.2 - March 2024

  • Added examples to Example section of MATLAB

v2.13.1 - March 2024

  • Fix for domain detection (server license)

v2.13.0 - November 2023

  • Supports MATLAB R2023b.
  • Added support for checking App Designer files.
  • Added preference to exclude Live Editor files and App Designer files from being checked (default false).
  • Added preference to exclude Simulink files from being checked (default false).
  • Added Compiler Compatibility configuration.
  • Deselected mexw32 as being required in default configuration.
  • Fixed report link to code for MATLAB Function blocks in a Simulink model.
  • Fixed missing default reports folder.
  • Fixed false positives on number of input arguments check.
  • Fixed false positives for use of Java check.
  • Fixed false positivies where file shadowed itself.
  • Fixed callback error when deselecting check in configuration editor.
  • Fixed files with only comments breaking cyclomatic complexity check.
  • Fixed copyright notice detection.

v2.12.2 - August 2023

  • Improved error handling for files that could not be analyzed.

  • Fix for false positive on try-catch without error handling.

v2.12.1 - July 2023

  • Improved change detection for Git repositories.

v2.12.0 - June 2023

v2.11.0 - October 2022

v2.10.0 - April 2022

v2.9.0 - November 2021

  • Added a Fix all button to the report. By clicking this button, all violations for a specific check in all checked files are fixed. Applicable to checks for which fixes are currently available. See section Automatic fixes.

  • Added a new Preference to the Preferences tab, with Smart indent files before checking enabled CC4M smart indents the selected files before checking them. See section Preferences.

  • When large files are selected for checking, you are now prompted to skip or check them. You can set a default response and the threshold for what is considered a 'large' file in the Preferences tab. See section Preferences.

  • Links to violations in Live Editor files no longer refer to incorrect line numbers for MATLAB R2020a and newer.

  • Added a parameter to checkCoderCompatibilityFunctionCalls that lets you choose whether or not to filter for unique violations.

  • Added a parameter to checkBuiltinFunctionCompatibility that lets you choose whether or not to filter for unique violations.

  • Added a parameter to checkMagicNumber that lets you choose whether or not to allow whole decimal numbers.

  • checkFunctionIndented no longer errors when a function is completely indented and it should be.

  • When configured, checkSurrBySpaces now reports equals signs in for-loop definitions if they are not surrounded by spaces.

  • Added a New button to the Configuration tab of the GUI.

  • Improved support for the Simulink Model Advisor. All configurations are available as "CC4M Task" and every individual check can be configured from the Model Advisor, when using them from the "By Product" section, see .

  • Supports MATLAB R2021b.

  • New checks:

v2.8.0 - March 2021

  • Added the Preferences tab with several new preferences. See section Preferences.

    • Use the Report violations when not entirely sure preference to possibly reduce the number of reported violations that are not actually violations of your coding standards. This replaces the IgnoreUnknownTypeVariables parameter of reportBinaryExpressions and the IgnoreUnknownTypeCells parameter of reportCellArrays.
  • The Any option was added to parameter Location of checkCopyrightNotice that allows the copyright notice to be placed at the top, before the main code, or at the bottom.

  • Added a parameter to checkLoopIteratorNaming that lets you choose whether or not to use subsequent alphabetical starting letters for iterator names in nested for-loops.

  • Added a parameter to checkSurrBySpaces that checks whether equals signs in Name=value syntax introduced in MATLAB R2021a are surrounded by spaces or not.

  • Improved detection of data types of variables, most notably for inputs of local and nested functions. This reduces the number of incorrect results, especially for struct-related checks. See Appendix Datatype detection.

  • Added the MAB predefined configuration file. See section Predefined Configurations.

  • Compatible with MATLAB R2021a.

  • checkNestingDepth no longer considers main and sub-functions as nesting depth 1.

  • New checks:

v2.7.0 - February 2021

  • Added Git support for the File and Folder options of the General tab.

  • Added the option to search for check configurations in the Configuration Editor. See section Find checks efficiently.

  • Added a parameter to checkFunctionIndented that lets you ignore violations related to tab characters.

  • Added two parameters to checkOneStatementPerLine that lets you choose whether or not multiple global or persistent variables are allowed to be declared on a single line.

  • Added two parameters to checkLoopIteratorNaming that lets you define a minimum length for iterator variable names, and that lets you choose whether or not to use the casing parameters for variable casing.

  • The lowercasing option was added for all casing checks (see section Casing checks).

  • New checks and reports:

  • Added an auto-fixer for checkMissingComma.

  • checkMagicNumber no longer reports lines of code where a number is compared to the output of nargin, nargout or exist.

v2.6.0 - December 2020

v2.5.1 - November 2020

  • Bug fix for running Code Checker for MATLAB in the Model Advisor.

v2.5.0 - October 2020

v2.4.0 - May 2020

v2.3.0 - August 2019

v2.2.4 - April 2019

v2.1.2 - September 2018

Acknowledgement

The folder "licenses" includes a list of licenses related to open-source tooling/scripts/functions that are used as-is or as inspiration during development of CC4M.

Version Information

DateCC4M versionInfo
November 20232.13.0See release notes.
June 20232.12.0Converted documentation to new tooling.
October 20222.11.0Included documentation of referencing configuration files.
April 20222.10.0Included documentation of the Pro Features.
December 20202.6.0Documented the predefined configurations and the MATLAB project integration.
October 20202.5.0Removed documentation on the old GUI (no longer supported) and manual editing of the configuration file (no longer recommended).
May 20202.4.0Documented the Configuration Editor and several new checks.
August 20192.3.0Improved report, added eleven new checks, and added auto-fixes for threetests. Improved reliability of code analysis and Code Checker for MATLAB checks.
April 20192.2.3Added exemptions and expanded object detection. Added Live Editor file support.
December 20182.1.2New GUI available. Added limited object detection.
June 20182.1.0Documented all checks and described parameter configurations.
November 20172.0.0Code Checker for MATLAB no longer dependent on Simulink Validation & Verification / Simulink Checks.

In order to upgrade CC4M to a newer version, obtain the toolbox you wish to install and then follow the steps described in this forum post. This process requires closing and restarting MATLAB, so it is advised to save your work and close all other running MATLAB sessions prior to starting the upgrade.

The first time using CC4M, you can check if installation succeeded by calling monkeyproof.cc4m.start. The user interface should pop up.

Troubleshooting

License Errors

When starting CC4M, a license check is performed. Depending on your license type, one of the following messages may appear.

  • FLOATING_LICENSE_ALLOWED_USE_COUNT_REACHED Allowed license use count reached. Please wait for licenses to be released by other users.

  • FLOATING_LICENSE_ALLOWED_USE_TIME_REACHED Allowed license usage time limit reached.

  • FLOATING_LICENSE_CLIENT_REJECTED Applicable to floating license text only, will be returned when client is rejected.

  • FLOATING_LICENSE_NOT_AVAILABLE_ALL_IN_USE All licenses are in use. Please wait for licenses to be released by other users.

  • FLOATING_LICENSE_NOT_FOUND License with given product id does not exist on floating license server. Please check with the license server administrator.

  • FLOATING_LICENSE_OVERUSED License is overused. Please wait for licenses to be released by other users.

  • FLOATING_LICENSE_SERVER_NOT_AVAILABLE Floating license server not available, either not running or client can not connect. Please check your network settings. If the problem persist contact the license server administrator.

  • INCORRECT_SYSTEM_TIME System date/time is incorrect, at least 24 hours difference with checked online time source.

  • LICENSE_EXPIRED License has expired.

  • LICENSE_INVALID License file is invalid.

  • LICENSE_MAINTENANCE_EXPIRED License maintenance has expired.

  • MISMATCH_HARDWARE_ID License signature is valid, but the hardware id is different from the licensed one.

  • MISMATCH_PRODUCT_EDITION License signature is valid, but the product edition is different from the licensed one.

  • MISMATCH_PRODUCT_ID License signature is valid, but the license is for another product.

  • MISMATCH_PRODUCT_VERSION License signature is valid, but the product version is different from the licensed one.

Issues with mex-files on macOS

In some cases, macOS may decide that the developer of the mex-files included in CC4M cannot be verified, blocking use of CC4M. To resolve this, the files must be whitelisted as described here.

Datatype detection

CC4M attempts to derive the datatypes of the variables created in the code that is checked. However, this analysis is imperfect and therefore unexpected results may be encountered. This section provides a non-exhaustive overview of the situations in which variables are detected as objects of a specific class. This information allows CC4M to distinguish objects from structs, which is used in multiple checks.

  • The first input of a non-static method.

  • The first output of a constructor in a classdef file.

  • The first output of a non-MATLAB-installed constructor call and the variable was not defined earlier.

  • The output of a selection of MATLAB-installed functions returning an object. This means outputs of for example figure and waitbar are treated as objects if the MATLAB-isntalled version is not shadowed.

  • The target of a subscript assignment like obj = objs(idx) where objs was detected as an object before.

  • An input of a local or nested function and the data types of the inputs of all calls to that function are the same.

  • The output of a call to empty, copy or copyobj (if the input datatype is known). For example: obj = tools.MyClass.empty(); or newObj = copy(obj);