Code Checker for MATLAB
Checking Conventions in MATLAB code and Simulink models
© 2025 MonkeyProof Solutions BV
T: +31 (0)76 8200 314
Table of Contents
- Introduction
- Getting Started
- User Guide
- Checks
- Generic checks
- Naming convention checks
- Compatibility checks
- Testability and functionality checks
- checkAbstractClassInstantiation
- checkAssertInputs
- checkAvoidVararginout
- checkCodeInterpretable
- checkComparisons
- checkFunctionCallExcessInputs
- checkGlobalUsed
- checkIfElse
- checkLogicalOperator
- checkMixedTypesExpression
- checkNestingDepth
- checkNumberOfInputsOutputsFunction
- checkPersistentUsed
- checkReuseIteratorVariableName
- checkSuperclassPropertyImplementation
- checkSwitchOtherwise
- checkTryExceptionHandling
- checkTryUsed
- checkWarningUsed
- checkUseIteratorVariableNameOutsideLoop
- checkSuperclassConflict
- Layout and readability checks
- checkWhiteSpaceEndOfLine
- checkZeroBeforeDecimalPoint
- checkCodeLength
- checkCommandSyntax
- checkConstantDefinitionAtTop
- checkContiguousStructFieldDefinitions
- checkDuplicateAttributes
- checkEditorWarnings
- checkExpressionAlignment
- checkFollowedBySpace
- checkFunctionIndented
- checkIfTrue
- checkIndentationLength
- checkLineLength
- checkMagicNumber
- checkMissingComma
- checkMissingSemicolon
- checkNegatedBoolean
- checkNestedFunction
- checkNoInputArg
- checkOneStatementPerLine
- checkOperatorsLineContinuation
- checkParenthesesLogicalOperators
- checkParenthesesMathematicalOperators
- checkSubFunction
- checkSuppressAll
- checkSurrBySpaces
- checkTabCharacterUsed
- checkAvoidComments
- checkBlockComment
- checkMethodAccessPermissions
- checkMethodsInClassdef
- checkNumberOfOutputsConstructor
- checkPropertiesBeforeMethods
- checkPropertyClassRedundancy
- checkFunctionEnd
- Security Checks
- Metrics
- Configuration Editor
- Predefined Configurations
- Command line interface
- Function Reference
- start
- showLicenseAgreement
- showLicenseDialog
- getConfigurationFolder
- setConfigurationFolder
- getActiveConfigurationFile
- activateConfigurationFile
- getConfigurationFiles
- createConfigurationFile
- updateConfigurationFile
- openConfigurationFile
- listPredefinedConfigurations
- getReportsFolder
- setReportsFolder
- getExemption
- getAllExemptions
- System Requirements
- Considerations and Known Limitations
- Release Notes
- Acknowledgement
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.
Metrics and configurable checks are provided, along with a set of Configuration Files. To divert from the predefined configurations, the Configuration Editor allows for creating your own configuration file. If needed, it is also possible to add custom, user-defined checks to CC4M. If you are interested in authoring your own checks, please contact us at info@monkeyproofsolutions.nl so that you can receive the documentation for this.
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.

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.
Prevent Java path issues
CC4M relies on Java functionality. To prevent issues with the Java path, CC4M adds all the Java code to the static javaclasspath. After installing a restart of MATLAB is required.
Online activation
- Once installed run the software by entering
monkeyproof.cc4m.start()
at the MATLAB command line. - The first time the software is run (i.e. when no valid license file can be found), the license dialog pops up.
- Enter the license information you received per email:
- Product key
- User name
- Company
Off-line activation
- Once installed run the software by entering
monkeyproof.cc4m.start()
at the MATLAB command line. - The first time the software is run (i.e. when no valid license file can be found), the license dialog pops up.
- Press the "Show hardware IDs" button and return these IDs to us by replying to this email.
- We will then provide you with a license file.
- Save this license file to the default license file location (keep the filename intact); when you run the commands below in MATLAB, it will give you the default folder (and create it):
Alternatively, you can save the license file to any convenient location and then set an environment variabletheSettings = settings(); defaultFolder = fullfile(theSettings.matlab.addons.InstallationFolder.ActiveValue, 'Licenses') folderCreated = mkdir(defaultFolder)
MONKEYPROOF_LICENSE_FILE_FOLDER
to point to the folder containing the license file.- The environment variable can be set at system level (the environment variable will only be visible afterwards in a new MATLAB session).
- From within MATLAB (for the duration of the MATLAB session) you can set the environment variable by issuing the following command before starting CC4M (assuming the license file is in the current working directory):
setenv('MONKEYPROOF_LICENSE_FILE_FOLDER', pwd)
.
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:
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:
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, contact us via support@monkeyproofsolutions.nl . 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
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 Contact support for assistance.
- Expiration date This is the expiration date of the license.
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.
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.
Enter Modification Key
If you receive a license modification key, you can enter it here.
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 missing.
- 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.
Using CC4M from Simulink
Since R2021b Simulink has a toolstrip. From this toolstrip you can run CC4M on your model. From the toolstrip CC4M can be used on the current Simulink model. The default configuration used is the MonkeyProof Coding Stadard for MATLAB, but all available configurations can be activated from the toolstrip. When running CC4M on the model, first the complete model is searched for MATLAB functions. Both the code from the MATLAB Functions Blocks and MATLAB Functions within Stateflow Charts are analyzed.
When generating code from Simulink models, the following predefined configurations may be valuable:
Using the "Browse" option from the CC4M user interface allows for selecting models as well.
Simulink integration limitations
- Analysis is performed on the complete model
- MATLAB Function Blocks are reported as "file" in the reports
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
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.
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
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 thebutton will be disabled until the selection is valid.
-
The switch labeled Changed files only (when enabled:
) 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 (
), 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
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
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
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.
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
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
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.
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:
-
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.
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. However, the preferences only apply when running checks via the user 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);
-
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 violatescheckStructFieldCasing
. 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 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);
About
The About tab as shown in the figure 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 subreddit r/cc4m.
-
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.

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.
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 unused checks. 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. 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.
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.
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
- Although the report is intended to be portable, differences may occur due to external circumstances, such as using a different version of CC4M, different MATLAB toolboxes being installed, a different MATLAB path configuration, etc.
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:
Limitation
- Note that automatic fixes are always disabled for MATLAB-installed files since you are not allowed to change these.
Live Editor files, App Designer files and Simulink models
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 and App Designer is disabled.
-
Adding exemptions to Live Editor files and App Designer 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 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.
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
- Naming convention checks
- Compatibility checks
- Testability and functionality checks
- Layout and readability checks
- Security Checks
Unique identifers
Every check has a unique identifier, that can be used as exemption tag. Below an overview of all exemption tags. The list can be obtained using the command:
tagsTable = monkeyproof.cc4m.getAllExemptions();
The list:
ABSCI checkAbstractClassInstantiation
ALFUN checkAllowedFunctions
ASINP checkAssertInputs
AVCOM checkAvoidComments
AVDDT checkAvoidDatatypes
AVFUN checkAvoidFunctions
AVNAM checkAvoidNames
BFCNC checkBuiltinFunctionCompatibility
BLCKC checkBlockComment
CARBU checkArgumentsBlockUsed
CCFCN checkCoderCompatibilityFunctionCalls
CCLAS checkClassCasing
CENME checkEnumMemberCasing
CEVEN checkEventCasing
CFEND checkFunctionEnd
CFIND checkFunctionIndented
CHARA checkCharacterArray
CINDE checkIndentation
CINLE checkIndentationLength
CMETH checkMethodCasing
CNCON checkNamedConstantCasing
CNDAT checkConstantDefinitionAtTop
CNSTF checkNestedFunction
CNVPC checkNameValuePairCasing
COINT checkCodeInterpretable
COLEN checkCodeLength
COMPA checkComparisons
CONAR checkConcatenateExpandedArray
COPYR checkCopyrightNotice
COSYN checkCommandSyntax
CPACK checkPackageCasing
CPROP checkPropertyCasing
CSFIE checkStructFieldCasing
CSTFD checkContiguousStructFieldDefinitions
CSUBF checkSubFunction
CSUPC checkSuperclassConflict
CUDFU checkUserDefinedFunctionCasing
CVARI checkVariableCasing
CZBDP checkZeroBeforeDecimalPoint
DUPAT checkDuplicateAttributes
DYNFI checkDynamicFields
EDWRN checkEditorWarnings
EXPAL checkExpressionAlignment
EXERA checkExemptionsRationale
FCNPF checkFunctionPrefix
FCTMI checkFunctionCallExcessInputs
FOLSP checkFollowedBySpace
GETST checkGetterAndSetter
GLOBU checkGlobalUsed
IDXNA checkLoopIteratorNaming
IFELS checkIfElse
IFTRU checkIfTrue
INPAR checkNoInputArg
JAVUS checkJavaUsed
LILEN checkLineLength
LOGOP checkLogicalOperators
MAGNR checkMagicNumber
MCOMM checkMissingComma
MDAMI checkMethodsInClassdef
METAP checkMethodAccessPermissions
MIXOT checkMixedTypesExpression
MSEMC checkMissingSemicolon
NALEN checkNameLength
NEGBO checkNegatedBoolean
NINOF checkNumberOfInputsOutputsFunction
NOOCS checkNumberOfOutputsConstructor
NSHAD checkNameIsShadowing
NSTDP checkNestingDepth
OPLCO checkOperatorsLineContinuation
OSTPL checkOneStatementPerLine
PARLO checkParenthesesLogicalOperators
PARMO checkParenthesesMathematicalOperators
PBBMB checkPropertiesBeforeMethods
PERSU checkPersistentUsed
PRCLR checkPropertyClassRedundancy
RCOMP checkComplexity
RDEPE checkDependencies
RMEXF checkMexFiles
RUIVN checkReuseIteratorVariableName
SCRFU checkScriptFileUsed
SCXML checkSecurityXml
SECCF checkSecurityCertificateFilename
SECCN checkSecurityConstantNames
SECUP checkSecurityUsernamePassword
SFNAM checkStructFieldNames
SHESC checkShellEscape
STRDT checkStringDataType
SUPAL checkSuppressAll
SUPPI checkSuperclassPropertyImplementation
SURSP checkSurrBySpaces
SWOTH checkSwitchOtherwise
TABCU checkTabCharacterUsed
TRYEH checkTryExceptionHandling
TRYUS checkTryUsed
TSTSF checkTestSuffix
UIVOL checkUseIteratorVariableNameOutsideLoop
VARIO checkAvoidVararginout
WARNU checkWarningUsed
WSEOL checkWhiteSpaceEndOfLine
Generic checks
- checkArgumentsBlockUsed
- checkAvoidFunctions
- checkCopyrightNotice
- checkScriptFileUsed
- checkCharacterArray
- checkStringDataType
- checkGetterAndSetter
- checkTestSuffix
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 usearguments
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.
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 anarguments
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 ignoreC:\somefolder\test\myFile.m
, but it will still checkC:\test\somefolder\myFile.m
andC:\somefolder\foldertest\myFile.m
.Alternatively, you can provide multiple layers for one folder. By specifying
test\+internal
as an exempt folder, you ignoreC:\test\+internal\myFile.m
, but will still checkC:\otherFolder\+internal\myFile.m
andC:\test\myFile.m
. By default, the list is empty. -
RequireSize (boolean): Set to true (default false) when input argument size is required.
-
RequireClass (boolean): Set to true (default false) when input argument class is required.
-
RequireValidators (boolean): Set to true (default false) when input argument validators are required.
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
wherematlabroot
is the installation folder of the current MATLAB session that is also returned by callingmatlabroot()
. For example, configuring the valuematlab\graphics
for this parameter will make this check report calls to any function in the folderC:\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 as2011-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 asCopyright #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
orclassdef
headers. -
BeforeMainCode: Place the copyright notice right after the
function
orclassdef
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. 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 theTest
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:
-
If the file is considered a test file but it is not suffixed with the configured suffix.
-
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>
checkComplexity
In this check, 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>
checkDependencies
The file may use functions not defined in the file itself. These dependencies and additional information, are listed under checkDependencies.
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.
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 istrue
. -
DependenciesUniqueGlobal (boolean): If set to
true
, uniqueness of dependencies is global shown over all checked file, only relevant if multiptle files checked. If set tofalse
, uniqueness of dependencies is per file. The default value for this parameter istrue
. -
DependenciesUniquePerFunction (boolean): If set to
true
, uniqueness of dependencies is shown per function, only relevant if single file checked. If set tofalse
, uniqueness of dependencies is shown per file. The default value for this parameter istrue
.
Exemption tag: %@ok<RDEPE>
checkMexFiles
Checks the availability of the platform-specific binaries for the mex-files in the selected folder or project. The available MEX-file extensions are documented in the MATLAB help.
Configurable parameters
- RequiredExtensions (list): Mex-files with these extensions must
be checked by this report. Allowed values are:
mexa64
,mexmaci64
,mexw32
, andmexw64
.
Exemption tag: %@ok<RMEXF>
checkExemptionsRationale
This check searches for exemption tags that suppress CC4M check violations or MATLAB Code Analyzer warnings, and checks whether the exemption tag is followed by a rationale.
Configurable parameters
-
CodeCheckerExemptions (boolean): Enable checking rationale on CC4M exemption tags.
-
MatlabCodeAnalyzerExemptions (boolean): Enable checking rationale on MATLABs Code Analyzer exemption tags.
-
MinimumCommentLength (double): Minimum number of characters for the rationale (after trimming whitespace).
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 checked | Name of the check | Exemption tag | Note |
---|---|---|---|
Variables | checkVariableCasing | %@ok<CVARI> | |
Constant variables | checkNamedConstantCasing | %@ok<CNCON> | |
User-defined functions | checkUserDefinedFunctionCasing | %@ok<CUDFU> | 1 |
Structure fields | checkStructFieldCasing | %@ok<CSFIE> | 2 |
Name-value pairs in arguments blocks | checkNameValuePairCasing | %@ok<CNVPC> | 3 |
Packages | checkPackageCasing | %@ok<CPACK> | |
Classes | checkClassCasing | %@ok<CCLAS> | |
Class properties | checkPropertyCasing | %@ok<CPROP> | |
Constant class properties | checkPropertyCasing | %@ok<CPROP> | |
Methods | checkMethodCasing | %@ok<CMETH> | 4 |
Events | checkEventCasing | %@ok<CEVEN> | |
Enumeration members | checkEnumMemberCasing | %@ok<CENME> |
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, the configured prefixes should match.
the checkStructFieldCasing check suffers from the same limitation as checkStructFieldNaming: casing of dynamically assigned field names will not be checked.
The arguments
block was introduced in MATLAB R2019b.
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.
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
orlowercasing
. -
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
- checkFunctionPrefix
- checkLoopIteratorNaming
- checkNameIsShadowing
- checkNameLength
- checkStructFieldNames
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
for camel case,
i_row
, j_test
for snake case, iROW
, jTEST
for screaming snake
case or irow
, jtest
for lower case. 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/snake case), a lower case character (lower case) or an underscore followed by a lower case character (snake case).
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 true to use the
Casing
parameter fromcheckVariableCasing
to verify the correct casing of the iterator variable. IfcheckVariableCasing
is not configured in the same configuration file,UseVariableCasing
defaults to false.
By maintaining a convention on iterator variables, these can easily be distinguished.
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 scope. This can cause unexpected and undesired behaviour.
The MATLAB documentation
desribes the precedence order in detail, the goal of this check is to prevent any
conflicts with the documented order of precedence.
Variables and functions are reported if they have the same name as one or more of the following:
-
MATLAB-installed functions.
-
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
Hard exceptions
When implementing classes, there are use cases where overloading the functionality of superclasses is required. The functions listed below are ignored by this check when their implementation corresponds with the signature defined in the superclass, regardless of whether they are configured as exceptions.
- As described in Methods That Modify Default Behavior,
certain method names are supposed to overload MATLAB-installed
functions.
cat
,horzcat
,vertcat
,empty
(Static),disp
,display
,double
,char
,loadobj
(Static),saveobj
,permute
,reshape
,repmat
,ctranspose
,transpose
,isscalar
,isvector
,ismatrix
,isempty
,
- MATLAB operators, when used to overload default behaviour, as described in Operator Overloading:
plus
,minus
,uminus
,uplus
,times
,mtimes
,rdivide
,ldivide
,mrdivide
,mldivide
,power
,mpower
,lt
,gt
,le
,ge
,ne
,eq
,and
,or
,not
,colon
,subsref
,subsasgn
,subsindex
,
- MATLAB functions, related to Customize Object Indexing:
listLength
,numArgumentsFromSubscript
- Other MATLAB functions allowed to overload/implement as method:
delete
: see Handle Class Destructorjsonencode
: see Customize JSON Encoding for MATLAB Classesstruct
Other relevant documentation links:
- Overloading
end
: reported as violation. For more information see Overload end for Classes - Handle Classes
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.
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
- checkCoderCompatibilityFunctionCalls
- checkConcatenateExpandedArray
- checkDynamicFields
- checkJavaUsed
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 is2017b
. -
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 (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 (see https://mathworks.com/help/matlab/matlab_external/java-packages-to-be-removed.html - publicly announced in 2021).
Exemption tag: %@ok<JAVUS>
Testability checks
- checkAbstractClassInstantiation
- checkAssertInputs
- checkAvoidVararginout
- checkCodeInterpretable
- checkFunctionCallExcessInputs
- checkGlobalUsed
- checkIfElse
- checkLogicalOperator
- checkMixedTypesExpression
- checkNestingDepth
- checkNumberOfInputsOutputsFunction
- checkPersistentUsed
- checkReuseIteratorVariableName
- checkSuperclassPropertyImplementation
- checkSwitchOtherwise
- checkTryExceptionHandling
- checkTryUsed
- checkWarningUsed
- checkUseIteratorVariableNameOutsideLoop
- checkSuperclassConflict
checkAbstractClassInstantiation
This checks if any abstract classes are instantiated. Running the code would result in an error, because abstract classes cannot be instantiated.
For more information on abstract classes, see Abstract Classes and Class Members.
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.
checkComparisons
In this check, 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 check 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
ordouble
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>
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 anif
, that does not have anelseif
section, without a matchingelse
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 the class redefines properties already implemented by any superclass (if any). If this is the case, the class cannot be instantiated and an error will be thrown indicating this problem.
If the superclass declares a property as "Abstract", the check passes, regardless of the property in the class is implemented, or not (making the class abstract as well).
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:
-
Is there a
catch
block with at least one line of executable code? -
Is an exception object assigned or created in the
catch
?-
Assigned:
catch`` ME
-
Created:
ME = MException(errorID, msg);
-
-
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 tofalse
, do not require an exception object to be assigned or created in thecatch
. -
ExceptionHandlingFunctions (list): List of functions or MATLAB keywords (
return
etc.), at least one of which must be called within everycatch
. The default list iserror
,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.
Possilbe fault scenarios are:
- When the loop is not entered, results might be unexpected.
- MATLAB Coder documentation warns for possible runtime issues, see documentation.
Exemption tag: %@ok<UIVOL>
checkSuperclassConflict
Checks if superclasses do not define conflicting methods or properties and that handle and value classes are not mixed. Running code that uses classes that violate this check will result in errors.
Exemption tag: %@ok<CSUPC>
Layout and readability checks
- checkWhiteSpaceEndOfLine
- checkZeroBeforeDecimalPoint
- checkCodeLength
- checkCommandSyntax
- checkConstantDefinitionAtTop
- checkContiguousStructFieldDefinitions
- checkDuplicateAttributes
- checkEditorWarnings
- checkExpressionAlignment
- checkFollowedBySpace
- checkFunctionIndented
- checkIfTrue
- checkIndentationLength
- checkLineLength
- checkMagicNumber
- checkMissingComma
- checkMissingSemicolon
- checkNegatedBoolean
- checkNestedFunction
- checkNoInputArg
- checkOneStatementPerLine
- checkOperatorsLineContinuation
- checkParenthesesLogicalOperators
- checkParenthesesMathematicalOperators
- checkSubFunction
- checkSuppressAll
- checkSurrBySpaces
- checkTabCharacterUsed
- checkAvoidComments
- checkBlockComment
- checkMethodAccessPermissions
- checkMethodsInClassdef
- checkNumberOfOutputsConstructor
- checkPropertiesBeforeMethods
- checkPropertyClassRedundancy
- checkFunctionEnd
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. 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
, andfactorial
. -
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 or commenting in it. For example:
s.a = 2;
s.b = 3;
s.c = 100; % Separate block of code, so will be reported.
The above example will not be reported, if the parameter AllowEmptyLinesAndComments is set to True.
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
andelse
), it will only be reported once.
Exemption tag: %@ok<CSTFD>
Configurable parameters
- AllowEmptyLinesAndComments (boolean): Set to
true
to allow empty lines and comment lines within the block of code that defines the structure.
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 functionwhich
. 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.
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<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. These are numbers used directly 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 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. Especially the numbers
0
,1
, and2
should probably be exempt of this check. These parameters let you configure that. Defaults are-2
and4
, 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 tofalse
, and will not be reported when set totrue
:-
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 inproperties
orarguments
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 theerror
function. This setting can be used when your coding standards require that all lines of code are terminated with semicolons. When set tofalse
, 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 tofalse
.
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. This check reports variables with names that:
- Start with
not
orNot
followed by anything that is not a lowercase character. - Start with
not_
orNOT_
. - Contain
_not_
or_NOT_
.
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) orEndOfLine
(bottom example). The default isStartOfLine
. -
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
andelseif
-statements, even though these are not required to clarify operator precedence. For example:if a && b
should becomeif (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 examplex(:, 1)
ory{:}
will not result in a violation, but1: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 and10-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 totrue
, the following will be reported:plot(x, y, LineWidth=2)
and when set tofalse
, this will be reported as a violation:plot(x, y, LineWidth = 2)
. The default value isfalse
. 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.
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<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.
Exemption tag: %@ok<METAP>
checkMethodsInClassdef
Check if all methods that are declared in a classdef file are also implemented, 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 separate file are also declared.
Abstract methods
Abstract methods cannot be implemented in the class itself, but instead must be implemented in each subclass. Please note that abstract classes can have non-abstract methods:
classdef (Abstract) Example
% This class is abstract and cannot be instantiated directly. This does not
% require the subclass to implement anything.
methods
% These methods are *not* abstract and need an implementation in this
% class. The implementation can be provided in a function block right
% here. When only a declaration is provided, the method must be
% implemented in the class @-folder.
%
% Subclasses *may* override this method, but it is not mandatory.
function x = create(obj)
x = obj.x;
end
end
end
classdef Example
methods (Abstract)
% These methods are abstract (and therefore also the class) and are not
% allowed to have an implementation in this class. Subclasses cannot be
% instantiated unless they implement all methods.
%
% A function body here is an error:
% Illegal value for attribute 'Abstract' in class 'Example'. In the
% 'Example' class, the 'create' method has both the Abstract
% attribute and a function body.
%
% An implementation in the class @-folder will give a warning followed
% by an error when creating an instance of the Subclass:
% Warning: In the 'Example' class, the 'create' method has both the
% Abstract attribute and a function body.
%
% Error: Abstract classes cannot be instantiated. Class 'Subclass'
% inherits abstract methods or properties but does not implement
% them. See the list of methods and properties that 'Subclass' must
% implement if you do not intend the class to be abstract.
x = create(obj)
end
end
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>
checkFunctionEnd
This check verifies whether functions use the end
keyword to end the function.
Configurable parameter
- RequireEnd (boolean): If true, all functions must have an
end
. If false, functions are not allowed to have anend
. The latter prevents nested functions from being created and does not allow methods or local functions to be implemented in a classdef file.
Exemption tag: %@ok<CFEND>
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.
Possible use of the check is to avoid hard-coded sensitive data as readable and recognizable as such.
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
andPassword
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. 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.
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
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.
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.
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 istrue
. -
DependenciesUniqueGlobal (boolean): If set to
true
, uniqueness of dependencies is global shown over all checked file, only relevant if multiptle files checked. If set tofalse
, uniqueness of dependencies is per file. The default value for this parameter istrue
. -
DependenciesUniquePerFunction (boolean): If set to
true
, uniqueness of dependencies is shown per function, only relevant if single file checked. If set tofalse
, uniqueness of dependencies is shown per file. The default value for this parameter istrue
.
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.
reportBinaryExpressions
This report is especially relevant for m-code that will be used for code generation.
Generated code does not enforce the order of evaluation in expressions. For most expressions, the order of evaluation is not significant. For expressions that have side effects, the generated code might produce the side effects in a different order from the original MATLAB code.
This report lists 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 (+
, -
, >
, >=
, &
, &&
, :
, etc.).
An expression will be reported by reportBinaryExpressions if any of these are met:
-
A function is called on both sides of the operator.
-
A 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 Report violations when not entirely sure described in section Preferences is set to true
.
The data types of variables are unknown for example for the inputs of the main function, or outputs of user-defined function calls.
Disabling the preference may lead to fewer false positives being reported.
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.
reportMexFiles
This report lists the mex-files found in the selected folder or project. It is merely an overview of the present files, and it can be used to determine whether the code has a chance to work on different platforms.
Configuration Editor
The Configuration Editor lets you interactively configure the CC4M's checks such that they reflect your coding guidelines. You can also clone one of the predefined configurations and modify it 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);
whereconfigFile
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, 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 ot the selected configuration file (or just the name in case of a predefined configuration).
- 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
- Enabled checkbox
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.
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 Clone button clones the check configuration and adds it the list. This allows using the same check with multiple parameter configurations.
-
The Remove button removes the check configuration from the list.
-
The Override button allows to override referenced check configurations. Since referenced check configurations cannot be edited, this allows enabling/disabling of the referenced check and modifying its parameters.
-
The check's Description. This will also be displayed in CC4M reports.
-
The Source of the check can be a reference configuration or the current configuration.
-
Enable checkbox.
-
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. Level 1 indicates issues of critical importance and the severity decreases with each level. 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 guideline. The link should be a valid URL starting with
https://
orhttp://
.- 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 ID.
-
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.
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.
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.
Add new check configurations
In order to be able to add new check configurations to the list, checks that already have an existing configuration can be cloned. To add checks that are not configured yet, click the Add unused checks button to add all unconfigured checks in disabled state.
Checks that have one or more unconfigured parameters are indicated with a warning sign in the checks list. When selected, the unconfigured parameter is indicated as well. After saving the configuration, all parameters are considered to be configured, regardless of whether they were reviewed and changed or not.
Reference configurations
To add a reference to another configuration file, use the options on the Referencing tab shown in the figure below. A custom configuration file can be referenced by browsing to the file, and clicking the Confirm button. A predefined configuration can be referenced by selecting it via the dropdown menu and clicking the Confirm button.
If a custom configuration file or a predefined configuration has been successfully included a confirmation dialog will be shown. The dialog contains information on how many checks have been included. After including a referenced configuration, a tree of the referenced configurations will be shown in the Configuration Editor.
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,
so the first actual reference gets number 2. A visual indication for a check coming from a reference is the link icon .
When a check overrides a referenced check, the icon changes to a broken link
and its reference number corresponds to the file that contains the override.
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 Coding Standard for MATLAB
A generic and complete set of configurations that reflects the MonkeyProof Coding Standard for MATLAB created in agreement with renowned companies that use CC4M. The standard references the following configurations that cover specific elements of the compelte standard: - Layout - Configuration that covers all checks related to the layout of the code. - Naming - Configuration that covers all checks related to naming conventions. - Security - Configuration that covers all checks related to potential security issues. - Testability - Configuration that covers all checks related to the testability of the code.
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.
TargetLink_Compatibility
Use this configuration to help you identify parts of your code that are (potentially) not compatible with code generation using dSPACE TargetLink version 2023-B.
M-code that is compatible cannot be used to generate C or C++ code. The coding standards document for this is under a separate license.
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. The coding standards document for this is available on our website.
MAB
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.
MISRA
MISRA AC ACG version 1.0 compliance configuration. For more information see https://misra.org.uk/product/misra-ac-agc/ and https://misra.org.uk/misra-autocode/.
JMAAB
The JMAAB (Japan MATLAB Automotive Advisory Board) has developed a set of coding standards mostly for Simulink models.
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')
Command line interface
Calling monkeyproof.cc4m.start
without input arguments opens the graphical user interface that lets you choose what files to check and how.
These options are also available from the MATLAB command window.
Syntax
-
monkeyproof.cc4m.start()
opens the graphical user interface. -
monkeyproof.cc4m.start(_, Name, Value)
specifies additional named input arguments, example:monkeyproof.cc4m.start('runSeverities', 5)
. -
monkeyproof.cc4m.start(_, Flag)
specifies additional flags, example:monkeyproof.cc4m.start('-editor')
. -
fileLocation = monkeyproof.cc4m.start(_)
returns the path to the created report. -
[_, out] = monkeyproof.cc4m.start(_)
additionally returns a structure. In case of the HTML report this is equivalent to the JSON summary, in case of a JSON report it is equivalent to the report contents.
Named arguments
-
configFile
The configuration file path. -
file
Absolute path(s) of the file(s) or folder to check.- MATLAB file (
.m
,.mlx
,.mlapp
,.slx
,.mdl
), only that specific file is checked. - Cell array of MATLAB file names or a semicolon-separated list of MATLAB file names, these are all checked.
- Folder, all MATLAB files in that folder (non-recursively) are checked.
- 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. - 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.
- MATLAB file (
-
fileSizeThreshold
The file size threshold inkB
for skipping large files. Only used in combination with the-skipLargeFiles
flag. -
matlabPath
Path to set before starting the run. The current path is restored after the run. If this option is used, the files selected for checking are not added to the MATLAB path if the path you specify does not say so.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:
- Keep all folders that contain MATLAB-installed functionality on the path.
- Keep all CC4M code on the path.
- Add the parts of the path specified in the input by the user to the path.
-
reportsFolder
Reports output folder. -
runPriorities
Only run the checks with the specified priorities (cell or string array). Allowed values are:Mandatory
,Strongly recommended
, andRecommended
. If the input argument is not provided, checks with all priorities will run. -
runSeverities
Only the checks with a severity level below or equal to the specified value (1
-10
). -
showReportEntries
Number of report entries to show in one page.
Flags
-
-browse
Open a file dialog to browse for a folder to check. Browsing for a file is not supported by this option. -
-changedOnly
Check only files that have uncommitted changes in a Git or SVN repository. If the selected folder is not inside a repository, no files are checked. -
-comment
A user provided comment that will be added to the report's content. -
-currentProject
Run the checks on the files of the currently open MATLAB project. -
-doNotOpenReport
The created report will not be opened at the end of the run. -
-editor
Run 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. -
-excludeOxml
Exclude mlx and mlapp files. -
-excludeSimulink
Exclude Simulink models. -
-generateJSON
Generate a JSON report instead of an HTML report. -
-generateJSONSummary
Generate a JSON summary report.
-
-ignoreExemptions
Ignore exemptions and report the violations that are found. -
-license
Used to refresh the license. -
-openReportInNewTab
Open the created report in a new tab. -
-pwd
Run the checks on the current working directory (as would be returned by MATLAB when calling functionpwd
). -
-recursive
Check files in subfolders of the selected folder as well. -
-reportPassed
Report results for checks that have no violations. -
-reportViolationsWhenUnsure
Report violations when unsure. May lead to false positives.
-
-skipLargeFiles
Skip files larger than the threshold specified with named argumentfileSizeThreshold
. -
-skipTests
Skip files labeled 'Test' (MATLAB project only).
System integration
In order to integrate CC4M in your (continuous integration) systems, you may want to utilize the additional capabilities described in this section.
Generating JSON reports
Generating JSON reports requires the feature to be enabled in your CC4M license
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 guidelines compliance over time, which
can be especially advantageous to your development process when running
CC4M on a designated machine.
The JSON report is saved to the same location as HTML reports. The
summary 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"
: wherexxxx
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 less severe 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.
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
: Information about the environment.CodeCheckerVersion
: CC4M release number.MATLABVersion
: MATLAB release number.OperatingSystem
: The operating system.
RootFolder
: Common 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.NrMissingParamConfig
: The number of missing parameter configurations.MissingParamConfig
: The missing parameter configurations.
Function Reference
Generic: | |
monkeyproof.cc4m.start | Open the CC4M GUI. |
monkeyproof.cc4m.showLicenseAgreement | Show license agreement |
monkeyproof.cc4m.showLicenseDialog | Show license dialog |
Manage Configuration: | |
monkeyproof.cc4m.getConfigurationFolder | Get folder where configurations are stored. |
monkeyproof.cc4m.setConfigurationFolder | Set folder where configurations are stored. |
monkeyproof.cc4m.getActiveConfigurationFile | Get current active configuration file. |
monkeyproof.cc4m.activateConfigurationFile | Activate a configuration file. |
monkeyproof.cc4m.getConfigurationFiles | Get available configuration files in the configuration folder |
monkeyproof.cc4m.createConfigurationFile | Create a new configuration file using default values and optionally activate it. |
monkeyproof.cc4m.updateConfigurationFile | Add missing check configurations to a configuration file. |
monkeyproof.cc4m.openConfigurationFile | Open a configuration file in the Configuration Editor. |
monkeyproof.cc4m.listPredefinedConfigurations | Return a list of predefined configurations. |
Manage reports folder: | |
monkeyproof.cc4m.getReportsFolder | Get the location where CC4M reports are stored |
monkeyproof.cc4m.setReportsFolder | Change the location where CC4M reports are stored. If the given path refers to a non-existing location, the folder is created. |
Exemptions: | |
monkeyproof.cc4m.getExemption | Get the exemption tag for a given check name. |
monkeyproof.cc4m.getAllExemptions | Get a table with the exemption tag for every check. |
monkeyproof.cc4m.start
Run the available code checks on the specified files using the selected settings.
Syntax
monkeyproof.cc4m.start()
starts the code checker in interactive mode and asks the user to choose from the available options.
monkeyproof.cc4m.showLicenseAgreement
Show the license agreement of CC4M.
Syntax
monkeyproof.cc4m.showLicenseAgreement()
opens the license agreement in the MATLAB editor.
monkeyproof.cc4m.showLicenseDialog
Show the license dialog.
monkeyproof.cc4m.getConfigurationFolder
Get the folder that contains the configuration files.
Syntax
folder = monkeyproof.cc4m.getConfigurationFolder()
returns the folder as used for the configuration.
Defaults
During the installation the default configuration folder is defined.
For Windows this is:
%APPDATA%\Roaming\cc4m\cc4m_configurations
For Mac this is:
~/Library/Application Support/cc4m/cc4m_configurations
For Linux this is:
~/.matlab/cc4m/cc4m_configurations
See also
- monkeyproof.cc4m.setConfigurationFolder
monkeyproof.cc4m.setConfigurationFolder
Set the folder that contains the configuration files.
Syntax
isOk = monkeyproof.cc4m.setConfigurationFolder(newfolder)
returns true
in case the folder newfolder
exists and is set as the configuration folder.
See also
- monkeyproof.cc4m.getConfigurationFolder
monkeyproof.cc4m.getActiveConfigurationFile
Obtain the path to the configuration file that is active in the user interface.
Description
getActiveConfigurationFile
only returns the file name of the file currently active, unless input argument
'full'
is provided.
Syntax
file = monkeyproof.cc4m.getActiveConfigurationFile()
returns the current active configuration file.
file = monkeyproof.cc4m.getActiveConfigurationFile('full')
returns the current active configuration file including path.
See also
- monkeyproof.cc4m.getConfigurationFolder
monkeyproof.cc4m.activateConfigurationFile
Activate a configuration file in the user interface.
Description
activateConfigurationFile
accepts only filenames relative to the configuration folder, or a full file name. If
the file name contains a path, the configuration folder is updated. During activation of the file, the file is not
verified against the expected xml format.
Syntax
isOk = monkeyproof.cc4m.activateConfigurationFile(file)
returns true
in case file
is activated with success.
See also
- monkeyproof.cc4m.getConfigurationFolder
monkeyproof.cc4m.getConfigurationFiles
Obtain all available configuration files in the folder of the currently active configuration file.
Description
getConfigurationFiles
returns the file names of the available configuration files.
All files that have extension ".xml" are returned as configuration file, so no check on the content is done while creating the list of files.
Syntax
files = monkeyproof.cc4m.getConfigurationFiles()
returns the found configuration files.
See also
- monkeyproof.cc4m.getConfigurationFolder
- monkeyproof.cc4m.getActiveConfigurationFile
monkeyproof.cc4m.createConfigurationFile
Create a configuration file.
Description
All available checks are added to a configuration file with the provided name. The file is created in the folder where all configurations are stored. In case the filename already exists, a similar name is created and used (existing files are not overwritten)
Syntax
[isOk, newName, folderName] = monkeyproof.cc4m.createConfigurationFile(file)
[isOk, newName, folderName] = monkeyproof.cc4m.createConfigurationFile(file, makeActive)
Inputs
- file: Filename of new configuration - location and extension are not needed / ignored.
- makeActive:
true
(default) if the created configuration file is to be made activate.
Outputs
- isOk:
true
in case the configfile is created. - newName: In case of success, the name of the file created (which might deviate from the provided name).
newName
includes the file extension'.xml'
. In caseisOk
isfalse
,newName
contains the error message. - folderName: Folder in which the configuration file is created.
See also
- monkeyproof.cc4m.getConfigurationFolder
monkeyproof.cc4m.updateConfigurationFile
Update a configuration file: add missing checks and parameters.
Syntax
updateInfo = updateConfigurationFile(varargin)
Inputs
- configFile: (Optional) Path of the configuration file to update.
- showDialog: (Optional) Whether to show a dialog (true) or display on the command window (false).
Output
- updateInfo: Information about what checks and parameters were added.
openConfigurationFile
Launch the Configuration Editor and load the input configuration file (or the default one). If the Configuration Editor is not available yet, this opens the XML file as plain text in the MATLAB editor.
Syntax
openConfigurationFile()
opens the default configuration file.
openConfigurationFile(configFile)
opens the specified configuration file.
monkeyproof.cc4m.listPredefinedConfigurations
Return a cell array of predefined configurations.
Syntax
configFiles = listPredefinedConfigurations()
returns the predefined configurations.
Outputs
- configFiles: Cell array of predefined configurations.
monkeyproof.cc4m.getReportsFolder
Get the folder that contains the reports.
Syntax
folder = monkeyproof.cc4m.getReportsFolder()
returns the folder as used for the results.
Defaults
During the installation the default configuration folder is defined.
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
See also
- monkeyproof.cc4m.setReportsFolder
monkeyproof.cc4m.setReportsFolder
Set the folder that contains the CodeCheckerForMATLAB reports. Creates the folder if it does not exist yet.
Syntax
[isOk, msg] = monkeyproof.cc4m.setReportsFolder(newfolder)
returns true
in case the folder newfolder
exists or was successfully created and is set as the reports folder.
See also
- monkeyproof.cc4m.getReportsFolder
monkeyproof.cc4m.getExemption
Return the exemption tag for a given check tag.
Syntax
exemption = getExemption(checkTag)
Inputs
- checkName: Tag of the check (possibly including namespace).
Outputs
- exemption: Exemption tag of the check.
See also
- monkeyproof.cc4m.getAllExemptions
monkeyproof.cc4m.getAllExemptions
Return per check the exemption tag that can be used to exempt a line (or file) from a rule.
Outputs
- exemptions: Table of checks and exemption tags. Columns are 'Check' and 'ExemptionTag'.
See also
- monkeyproof.cc4m.getExemption
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:
- 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.
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, Constant Properties are initialized when gathering class information, if the checked code has class definitions among them. CC4M uses the meta information returned by MATLAB, which infers calling the initialization code of the Constant Properties. This may cause unexpected behaviour if the calculation of the Constant 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. More on Constant Properties in Define Class Properties with Constant Values.
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.
Simulink:
- Analysis of Simulink files is currently not supported with the
generateJSON
flag. excludeSimulink
flag is set to true, in case no Simulink is installed, or no license is available.
App Designer:
- In case of a "Custom UI Component" mlapp, the report can include violations in non-editable code (code generated by the App Designer). As a workaround you can add a file-wide exemption, which prevents also reporting violations in your code.
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 correctly, 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, callclose force all
beforeclear 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 callingclear 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.18.2 - June 2025
- Fix JSON summary error when no violations are found.
v2.18.1 - June 2025
- Fix license dialog showing without license.
v2.18.0 - May 2025
-
Update forum links to refer to the CC4M subreddit r/cc4m.
-
Documented how to add custom checks (documentation available upon request).
Fixes
-
checkConstantDefinitionAtTop
now also detectsarguments
blocks for output variables. -
checkFunctionCallExcessInputs
now also recognizes named arguments inherited from class properties. -
Unlicensed MATLAB Toolbox installations no longer issue warnings at CC4M startup.
v2.17.0 - January 2025
-
CC4M toolstrip in Simulink enhanced, all predefined and custom configurations are available.
-
Added
checkExemptionsRationale
. -
Added parameters
LocalFunctionPrefix
andNestedFunctionPrefix
tocheckUserDefinedFunctionCasing
, such that it is independent ofcheckFunctionPrefix
. -
Improved
checkComplexity
such that only violations are reported. To report complexity for all functions, usereportComplexity
. -
Fixed local and nested function detection in MATLAB Function blocks.
-
Fixed reporting of superclasses as dependencies for classes without methods.
-
checkNegatedBoolean
no longer depends on parameters from other checks. Negated booleans names are reported regardless of the required casing. -
Improved
checkNameIsShadowing
for overloaded methods. -
Fixed analysis of abstract classes.
v2.16.0 - October 2024
-
Supports MATLAB R2024b.
-
Improved "Go to list" buttons behavior in reports opened in MATLAB web browser.
-
Improved validation when switching between File, Folder and Project in the GUI.
-
Improved detection of superclass method calls in releases prior to R2022a.
-
Bugfix for saving corrupt configuration file.
-
Clearer distinction between checks and reports
- Added
checkComplexity
; correspondingreportComplexity
does not produce violations. - Added
checkDependencies
; correspondingreportDependencies
does not produce violations. - Added
checkMexFiles
; correspondingreportMexFiles
does not produce violations.
- Added
-
Removed Include metrics option. Metrics are included when they are enabled in the configuration file.
-
Improved detection of properties that specify dimensions, type and/or validators.
-
Improved dependency report in recursive calls.
-
Add ConstCasing, ConstMaxConsecUpper and ConstMaxConsecLower parameters to
checkPropertyCasing
. All checks on class property casing are configured and executed from this check. The CheckcheckNamedConstantCasing
no longer checks class properties. -
Fixed
checkTryExceptionHandling
when noExceptionHandlingFunctions
are configured.
v2.15.1 - September 2024
-
Bugfix for error in report message when all checks pass.
-
Allow opening and editing configuration files that refer to non-existing checks.
-
Bugfix
start
for MATLAB install without Simulink.
v2.15.0 - September 2024
-
Update of the reference configurations system, fixing numerous issues.
- Configuration Editor changes with respect to adding and removing checks and reference configurations.
- Configuration files do not require to have all checks defined.
- All checks from reference configurations are included.
- All checks can be added multiple times to a configuration.
-
Added CC4M toolstrip to Simulink, so CC4M can be used on models.
-
Limitation removed: Exemptions and fixes can be applied to MATLAB code in a Simulink model.
-
Limitation removed: Report now stores configuration and files involved, so Rerun performs exact same analysis.
-
Removed integration with Simulink Check - still available upon request.
-
Renamed
reportComparisons
tocheckComparisons
and changed from metric to check. -
Add RequireSize, RequireClass and RequireValidators parameters to
checkArgumentsBlockUsed
. -
Add AllowEmptyLinesAndComments parameter to
checkContiguousStructFieldDefinitions
. -
Added new predefined configurations:
- MISRA Configuration detect potential MISRA violations for code generation.
- TargetLink Compatibility: TargetLink 2023-B compatibility configuration (Separate license required).
-
Removed the "MonkeyProof MATLAB Coding Standard++" from the predefined configurations.
-
Behaviour change:
monkeyproof.cc4m.activateConfigurationFile
adapts the selection in the User Interface, but no longer has impact on scripted use of CC4M.
v2.14.2 - August 2024
-
Applying more fixes from the same report no longer interferes.
-
Added new predefined configurations with a specific focus:
- Layout: Configuration with focus on layout of the code.
- Naming: Configuration to use as a starting point for applying naming conventions.
- Testability: Configuration with focus on design, testability and completeness of the code.
v2.14.0 - April 2024
- Supports MATLAB R2024a.
v2.13.2 - March 2024
- Added examples to Example section of MATLAB.
v2.13.1 - March 2024
-
Enhanced domain check for license mechanism.
-
Added three demos, accessible from the documentation.
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
-
Rename from Code Checker for MATLAB towards CC4M.
-
Supports MATLAB R2023a.
-
New checks:
v2.11.0 - October 2022
-
Updated the GUI layout.
-
Added the option to reference configuration files, see section Reference configurations.
-
Added predefined configuration MonkeyProof MATLAB Coding Standard that reflects release 1.2.0 of the MonkeyProof MATLAB Coding Standard.
-
The displayed name of the MonkeyProofSolutions predefined configuration is now MonkeyProof MATLAB Coding Standard++.
-
Added a parameter to that lets you choose whether or not to allow
varargin
/varargout
. -
Improved the usability of the results of reportVariables.
-
Supports MATLAB R2022b.
-
New checks:
- checkAbstractClassInstantiation
- checkCodeInterpretable
- checkCommandSyntax (including an auto-fixer)
- checkFunctionCallExcessInputs
- checkJavaUsed
- checkMethodAccessPermissions
- checkSecurityWebOptions
- checkSecurityXml
- checkSuperclassPropertyImplementation
- checkUseIteratorVariableNameOutsideLoop
- checkZeroBeforeDecimalPoint (including an auto-fixer)
v2.10.0 - April 2022
-
Added the option to generate a JSON summary.
-
In the HTML report at most one violation of the same type per line of code will be shown for the following checks:
-
Added severity levels to the check configurations. Existing configuration files without severity levels configured take over the default values. If the user wants to change the severity level of a check, this can be done in the Configuration Editor.
-
Supports MATLAB R2022a.
-
New checks:
- checkMethodsInClassdef
- checkPropertiesBeforeMethods
- checkTabCharacterUsed (including an auto-fixer)
- checkTestSuffix
-
Added an auto-fixer for checkCopyrightNotice.
-
Added an auto-fixer for checkMissingSemicolon.
-
Added an auto-fixer for checkOperatorsLineContinuation.
-
Added a parameter to
checkOperatorsLineContinuation
that lets you choose whether or not to check equals signs used in assignments as well. -
Bugfix
checkNoInputArg
: Scripts called from functions are now correctly considered scripts and can no longer violate this check.
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 infor
-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:
- checkArgumentsBlockUsed
- checkAvoidNames
- checkNameValuePairCasing (see Casing checks)
- checkWhiteSpaceEndOfLine (including an auto-fixer)
- checkAvoidNames
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 ofreportBinaryExpressions
and theIgnoreUnknownTypeCells
parameter ofreportCellArrays
.
- 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
-
The
Any
option was added to parameterLocation
ofcheckCopyrightNotice
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 inName=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:
- checkOperatorsLineContinuation
checkPackageCasing
(see section Casing checks)
-
Added an auto-fixer for checkMissingComma.
-
checkMagicNumber
no longer reports lines of code where a number is compared to the output ofnargin
,nargout
orexist
.
v2.6.0 - December 2020
-
Added MATLAB project integration (available from R2019a) with Git support. See section Project.
-
Added predefined configurations. See section Predefined Configurations.
-
Added a parameter to
checkAvoidFunctions
that lets you select MATLAB folders whose functions to avoid using. -
Added a parameter to
checkEditorWarnings
that lets you select which warning message to report. -
New checks and reports:
-
Classes, functions and packages imported using the
import
function are no longer reported as missing dependencies and are reported as expected. -
Bugfix: : Constructors are no longer checked against the parameter MaxComplexityMehod.
v2.5.1 - November 2020
- Bug fix for running Code Checker for MATLAB in the Model Advisor.
v2.5.0 - October 2020
-
Added rerun functionality. See section Rerun functionality.
-
Exemptions can now be added to your code by the click of a button. See section Add exemptions automatically.
-
Checks can now be configured multiple times, allowing for a more precise mapping of your rules onto your configuration file. See section Multiple configurations per check.
-
All functions accessible through the command window interface now support inputs of type string.
-
Fixed a bug where reports could not be exported to PDF/Word format form Simulink ModelAdvisor.
-
Added the option to run checks based on priority (Mandatory, Strongly recommended, Recommended).
-
Before checking the code, the containing folders are now temporarily added to the MATLAB path. See section General.
-
checkEditorWarnings
is now configurable. See section checkEditorWarnings. -
Completed
checkOneStatementPerLine
: it now checks whether only one statement per line is used. Previously only lines of code containing multiple keywords were reported by this check. -
checkSurrBySpaces
is now configurable and can check for more operators. See section checkSurrBySpaces. -
The oldest supported MATLAB release is now R2017b instead of R2016a.
-
Compatible with MATLAB R2020b.
-
New checks:
-
Numerous minor improvements to checks and usability.
v2.4.0 - May 2020
-
Added the Configuration Editor for interactively editing your rule configurations.
-
Compatible with MATLAB R2020a.
-
New checks:
v2.3.0 - August 2019
-
Add new checks and configurable parameters to your configuration file (.xml) by calling
monkeyproof.cc4m.updateConfigurationFile()
or using the Update button in the Configuration tab in the GUI. -
Auto-fixers added for
checkFollowedBySpace
,checkNoInputArg
andcheckSurrBySpaces
. -
Improved scalability and readability of the reports when checking many files.
-
Added Report and About tab to the GUI.
-
New checks and reports:
-
Fixes:
-
Integration with Simulink Model Advisor.
-
Clear descriptions for all check parameters.
-
-
Renamed the method to run Code Checker for MATLAB: It was
monkeyproof.cc4m.processChecks
and it is nowmonkeyproof.cc4m.start
.
v2.2.4 - April 2019
-
Expanded object detection (see section Considerations and Known Limitations).
-
Added exemptions (see section Exemptions).
-
Added support for checking a single or multiple files in a folder.
-
Added support for Live Editor files (
*``.mlx
), with some limitations (see section Live Editor files). -
Implemented detection of class inheritance.
-
Rule configurations file can be imported.
-
Added basic configuration-related tab to the GUI (see Configuration)
-
New checks and reports:
v2.1.2 - September 2018
-
Updated the GUI (see section The CC4M user interface).
-
Implemented limited object detection (see section Considerations and Known Limitations). This means that assigning property values is no longer in all cases reported as a struct field declaration/assignment.
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.
- html reporting: html_table by Roger Parkyn
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. See below to inspect who checked out the licenses
-
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.
Monitor Floating Licenses
The "Floating License Server management GUI tool" can be installed on computers other than the license server to monitor licenses. For more information see the "LICENSE4J FLOATING LICENSE SERVER USER GUIDE" - VERSION 4.6.7. This document is provided with the License server.
Issues with mex-files on macOS
In some cases, macOS may warn 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.
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
andwaitbar
are treated as objects if the MATLAB-isntalled version is not shadowed. -
The target of a subscript assignment like
obj = objs(idx)
whereobjs
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
orcopyobj
(if the input datatype is known). For example:obj = tools.MyClass.empty();
ornewObj = copy(obj);