CodeCheck

Reference

Manual

 

by

Loren Cobb, PhD.

 

 

CodeCheck is a product of Abraxas Software, Inc.

 

 

 

For more information, contact:

Abraxas Software, Inc.

Post Office Box 19586

Portland, OR 97280, USA

 

Phone:  503-802-0810

Fax:  206.309.0304

 

Emailsupport@abxsoft.com

www.abraxas-software.com


Table of Contents

 


Introduction...................................................................................................... v

Command-line Options:

1.1     Options.......................................................................................................... 8

1.2     CodeCheck File Names...................................................................... 13

1.3     Rules can Depend on Options....................................................... 14

1.4     Options can Transmit Parameters........................................... 15

1.5     Rules can Set Default Options................................................... 15

CodeCheck Programming Concepts:

2.1     CodeCheck Rules.................................................................................. 17

2.2     Rule Evaluation................................................................................... 19

2.3     Rule Syntax.............................................................................................. 21

2.4     CodeCheck Operators...................................................................... 22

2.5     CodeCheck Programs........................................................................ 25

2.6     Predefined and User-defined Variables............................. 26

CodeCheck C/C++ Analysis Variables:

3.1     Conversion Variables....................................................................... 29

3.2     Declaration Variables.................................................................... 31

3.3     Expression Variables........................................................................ 45

3.4     Function Variables............................................................................. 48

3.5     Identifier Variables.......................................................................... 51

3.6     Lexical Variables................................................................................ 54

3.7     Line Variables........................................................................................ 59

3.8     Module Variables................................................................................ 63

3.9     Operator Variables........................................................................... 65

3.10       Preprocessor Variables............................................................ 75

3.11       Project Variables........................................................................... 81

3.12       Statement Variables..................................................................... 84

3.13       Structure and C++ Class Variables..................................... 88

CodeCheck Functions:

4.1     General Functions.............................................................................. 93

4.2     Lexical Functions................................................................................ 97

4.3     Preprocessor Functions.............................................................. 100

4.4     Declarator Functions................................................................... 102

4.5     C++ Class Functions........................................................................... 103

4.6     Operator Functions......................................................................... 105

4.7     Character Functions...................................................................... 107

4.8     String Functions................................................................................ 108

4.9     Mathematical Functions.............................................................. 111

4.10       Statistical Functions................................................................. 112

4.11       Input/Output Functions............................................................. 114

Warning Messages........................................................................................ 116

Warnings Issued by Rules....................................................................... 116

Error Warning Functions...................................................................... 116

Warnings Issued by CodeCheck........................................................... 118

Fatal Error Messages.............................................................................. 127

Limits and Assumptions............................................................................ 137

Trouble-shooting Techniques............................................................ 139

Trouble Report Form................................................................................ 141

Index...................................................................................................................... 142

 


Introduction

Computer professionals have a large and growing collection of tools that aid in the program development process. Oddly, very few of these tools for pro­grammers are themselves fully programmable. CodeCheck is a significant addi­tion to the genre of programmable tools. It performs its primary task—analyzing and critiquing C and C++ source code—entirely under the direction of a user-written con­trol program.

CodeCheck is not a new version of that old C programmer’s standby, lint, although it can per­form some lint-like error detection. For example, Code­Check compares all declarations and macro definitions across all modules of a project, to detect inconsis­tencies.

The main thrust of CodeCheck is to de­tect noncom­pliance with codified style standards, to detect maintenance or port­ability prob­lems within code which al­ready compiles perfectly on today’s compilers, and to compute cus­tomized quan­titative indicators of code size, com­plex­ity, and den­sity.

CodeCheck is a powerful tool for analyzing C and C++ source code. Stan­dards and mea­sures can be specified by the user for a tremendous number of fea­tures of C code that have an impact on portabil­ity, maintainability, and style. Code­Check is de­signed to enhance dra­matically the effec­tiveness and effi­ciency of project man­agement in com­mercial and indus­trial pro­gram­ming ef­forts.

A custom CodeCheck pro­gram specifying code stan­dard­s and measures can be written by a pro­ject leader using the CodeCheck language (actually a re­strict­ed subset of C itself). Code­Check can be pro­grammed to:

a.  Monitor compliance with standards for programming style, rules for type-encoded prefixes for identifiers, proper use of macros and typedefs, prototypes, etc.

b.  Identify code that is not portable to or from any particular envi­ronment (machine, com­­­piler, oper­ating system, or inter­face standard).

c.   Quantify code maintainability with user-defined measures at all levels: line, statement, func­tion, file, and project. Compute McCabe and Halstead complexity measures.

Sample CodeCheck programs are provided for a variety of problems, rang­ing from portability to complexity and compliance analysis for corporate and  industry style standards.


Chapter 1:  Command-line Options

 

CodeCheck is invoked by means of a command line with either of these for­mats:

 

         check -options foo.c

         check foo.c -options

 

In this command line format foo.c refers to the name of the C source file to be analyzed. Any number of source files may be specified, arbitrarily intermixed with options.

The rules that are to be used to perform this analysis can be specified in the options list, as described below. If no rule file is speci­fied, Code­Check will look for a precompiled rule file named default.cco.cco;, first in the cur­rent directory and then in the directories specified in the CCRULES environment variable. If this file is not found, CodeCheck will per­form a simple syntactic scan of the source file without any user-defined rules. 

To analyze a multiple-file project with CodeCheck, either list all of the source filenames on the command line, or create a new file con­tain­ing the names of all of the source files, one per line (do not list header files and li­braries in the project file). Give this pro­ject file the ex­tension “.ccp”. The contents after character '#' are interpreted as comments and ignored till the end of the line. Then invoke CodeCheck, spec­ifying the pro­ject file in­stead of a source file:

     check -options myproject.ccp                # comments

CodeCheck will apply its rules to each source file named in myproject.ccp, and will apply project-level checking across all the files in the project.   The ccp ex­tension in­forms CodeCheck that the specified file is a project file rather than a C source file. This extension may be omitted in the command-line. Command-line options may also be specified in the project file, one per line. Every option placed in a project file applies to every source file in the project.

The CodeCheck functions option(char) and set_option(char,int) can be used to obtain and set simple and integer-valued command-line op­tions, e.g. –B and –N. It cannot be used to change –K, however. For those command-line options that take string operands, e.g. –Iusr/foo/bar/headers, the equivalent func­tions are str_option(char) and set_str_option(char, char *). The Code­Check function option() re­turns an inte­ger whose value depends on the command-line op­tions speci­fied by the user when CodeCheck was invoked. For exam­ple, op­tion('X') returns the value 1 if the user specifies the option –X in the com­mand line, otherwise it re­turns 0.

A user can place either an integer or a string after the option. In both cases, the value of the option can be obtained by calling function str_option( 'X' ) in rule a rule file. To use the option as an integer in a rule file, pass the value obtained via function call to str_option to another CodeCheck function atoi(). These func­tions are useful for three purposes, as out­lined in sections 1.3 – 1.5.

 

 

1.1    Options:.1  Options;

Command-line options are used to override default actions or conven­tions, or to indi­cate addi­tional actions that you want CodeCheck to perform. CodeCheck com­mand-line options are not case-sensitive. The available op­tions are:

–A Reserved for CodeCheck expansion. Please do not use.

–B Instruct CodeCheck that braces are on the same nesting level as material surrounded by the braces. If this option is not specified, then CodeCheck as­sumes that the braces are at the previous nest­ing level. This option only affects the prede­fined variable lin_nest_level.

–C Reserved for CodeCheck expansion. Please do not use.

–D Define a macro. The name of the macro must fol­low imme­di­ately. An optional macro definition can be specified af­ter an equal sign. The macro may not have any arguments. For ex­am­ple,

               check –DFOREVER=for(;;)

     has the same ef­fect as starting each source code file with

              

                  #define FOREVER for(;;)

     If no macro definition is given, then CodeCheck assigns the value 1 to the macro by default.

 

-D? Internal macro dump [ #define ]. On command line –D? will dump initial state of #define internals after –Kn initialization Dynamic dumps may be generated with rule-file set_str_option( ‘D’, “?”) function.

–E Do not ignore tokens that are derived from macro expan­sion when performing counts, e.g. of operators and operands. The de­fault (–E not specified) is for CodeCheck to ignore all macro-derived tokens when count­ing.

–F Count to­kens, lines, operators, or operands when reading header files. The de­fault (–F not specified) is for CodeCheck not to count to­kens, lines, operators, or operands when reading header files.

–G Do not read each header file more than once. Caution: Some header files are designed to be read multiple times, with con­di­tional access to different sections of the header.

–H List all header files in the listing file. The –L option is as­sumed if this option is found. If –L is found without –H, then the listing file created by CodeCheck will not display the con­tents of header files. include files

–I  Specify a path to search when looking for header files. Use a sepa­rate –I for each path.  The pathname must follow –I, e.g.

               check -I/usr/myheaderpath src.c

     Header directory pathnames identified with the –I command-line option are searched before any directory paths listed in the the INCLUDE environmental variable. CodeCheck Unix only: the default header directory path is /usr/include.

–J Suppress all CodeCheck-generated error messages, e.g. syntax warnings. This op­tion does not suppress warning messages generated by rules.

–Kn         Identify the dialect of C to be assumed for the source files. A digit should follow immediately, which identifies the di­alect. The dialects of C and C++ currently available are:

                  0     Strict K&R (1978) C

                  1     Strict ANSI standard C

                  2     K&R C with common extensions

                  3     ANSI C with common extensions (default)

                  4     AT&T C++ [  ANSI STD C++ - Stroustrup  ]  

                  5     Symantec C++

                  6     Borland C++           [ CodeBuilder ]

                  7     Microsoft C++        [ MSDEV C++ 6.0 or later ]

                  8     GNU-GCC  C/C++  [ IBM VAC++ ]

                  9     MetroWerks CodeWarrior C/C++

                10     DEC Vax C and HP/Apollo C.  

                11     Metaware High C

     If this option is not specified, then CodeCheck will assume that the source code is ANSI with common exten­sions (–K3).

     If option –K is specified with no digit following, then Code­Check will assume that the user meant strict K&R C (–K0).

–L Make a listing file for the source file or project, with Code­Check mes­sages inter­spersed at appro­priate points in the list­ing. The name of the listing file may follow im­me­diately. If no name is given then the listing file will be check.lst.  The listing file will be created in the current directory, unless a target directory is specified with the –Q option.

–M          List all macro expansions in the listing file. Each line contain­ing a macro is listed first as it is found in the source file, and second as it appears with all macros expanded. The –L op­tion is as­sumed if –M is found. If –L is found with­out –M, then the list­ing file created by CodeCheck will not ex­hibit macro expan­sions.

–N Allow nested /* ... */ comments.  

–NEST    Allow C++ nested class definitions.

–O Append all CodeCheck stderr output to the file stderr.out. This is useful for those using the MS-DOS operating system, which does not permit the redi­rec­tion of stderr output. .out;.out; .out;.out;

–P Show progress of code checking. When this option is given, Code­Check will identify each file in the project as it is opened, and each function definition as it is parsed.

–Q Specify a target directory. The pathname of the directory into which all CodeCheck output files are to be placed must follow immedi­ately, e.g.

               check -L -Q./temp mysource.c

     Ex­amples of such output files are the listing and prototype files. If this option is omitted CodeCheck will write its output files to the current working directory.

–R Specify a rule file. The name of the rule file must follow im­me­diately, e.g. if the rule file name is foobar.cc and the C or C++ source filename is mysource.c:

               check -Rfoobar mysource.c

     Code­Check first looks for a object (i.e. compiled) rule file of this name (e.g. foobar.cco). If this file is out-of-date or not found, Code­Check will recom­pile the rule file (foobar.cc) into an object file (foobar.cco) before proceeding to apply these rules to the source file.  

     More than one –R file may be specified: in this case all the rules will be compiled together into an object file named temp.cco.

     If no –R file is specified, CodeCheck first looks for an object file named default.cco.cco;. If this file is found then it’s rules are used. If it is not found then checking proceeds with no user-defined rules.

–Sn         Apply rules while reading header files. A digit should follow immediately, which identifies the kinds of header files:

                  0     No header files (default).

                  1     Headers enclosed in double quotes.

                  2     Headers enclosed in angle brackets.

                  3     All header files.

     For example, suppose that these two lines are in a source file:

 

           #include <ctypes.h>       //  A standard system header

           #include "project.h"      //  An application header

                                             When option –S1 is in effect, CodeCheck will apply it’s rules to project.h but not ctypes.h. Please note that CodeCheck must always read every header included in a source file — this op­tion only determines whether or not CodeCheck rules will be applied to the con­tents of the various headers.

     CodeCheck’s default behavior is not to apply its rules to the contents of any included header files.

     The environmental variable CCEXCLUDE, if it is used, takes prece­dence over this option. Rules are never applied to files that are found in directories listed in this variable.

–SQL      Enables embedded SQL code. Note: this option must be spelled in all uppercase. 

–T Create a file of prototypes for all functions defined in a pro­ject. The name of the prototype file may follow im­me­diately. If no name is given then the name for the prototype file will be myprotos.h.     The prototye file will be created in the current directory, unless a target directory is specified with the –Q option.

–U Undefine a macro constant. The name of the macro must fol­low im­mediately. Thus  check -UMSDOS foo.c  has the ef­fect of treat­ing foo.c as though it began with the pre­proces­sor direc­tive #undef MSDOS.

–V For CodeCheck users. See Section 1.4 for usage suggestions.

–W          For CodeCheck users. See Section 1.4 for usage suggestions.

–X For CodeCheck users. See Section 1.4 for usage suggestions.

–Y For CodeCheck users. See Section 1.4 for usage suggestions.

–Z Suppress cross-module checking. Macro definitions and vari­able and function declarations will not be checked for con­sis­tency across the modules of a project. Often required in .CCP files when checking several source files at once.

Any letter of the alphabet may be used as a command-line option. Every op­tion is remem­bered by CodeCheck and passed to the rule interpreter. Code­Check rules can refer to and change these options by calling the functions op­tion, set_option, str_option, and set_str_option (see Sec­tion 1.3–1.5 for de­tails).  Option –X is recommended for users who wish to design custom rule files whose behavior is controlled by a com­mand-line option.

Batch processing [ @file ] of large command strings is done with CodeCheck .ccp files. See below CodeCheck File Names.

 

 

1.2    CodeCheck File Names:.2  CodeCheck File Names;

The conventions used by CodeCheck for filename extensions are:

.cc        A CodeCheck rule file, containing a set of rules for com­pila­tion by Code­Check. These rules are written in a subset of the C language. Code­Check requires that this extension be used for rule filenames, though it may be omitted in the –R command-line option.

.cch      A CodeCheck header file, for inclusion in a CodeCheck rule file.

.cco      A CodeCheck object file, produced by the CodeCheck compiler. This file contains a compilation of the rules found in the rule file with the same name but extension ccp.

.ccp      A project file for CodeCheck. This file contains a simple list of the file­names of all of the source modules that comprise a pro­ject, one filename per line. Header files and li­braries should not be listed in this file. Any CodeCheck options may be listed in a ccp file, so long as each option is delimited by CR-LF. There is no limit to the number of ccp files on the command line.

 

Depending on command line options, the following files may be created by CodeCheck:

check.lst            The default filename for the listing file (–L option).

myprotos.h        The default filename for the prototype file (–T option).

stderr.out          The filename for stderr output (–O option).

temp.cco            The name of the object file created by CodeCheck when more than one rule file is compiled (several –R options).

 

 

1.3    Rules can Depend on Options:.3  Rules can Depend on Options;

The CodeCheck function option() allows rules to behave differently de­pending on the options chosen by the user. For example, by testing the value of op­tion('L') the rule can distinguish be­tween users who have asked for a list­ing file and those who have not. Here is an example which issues different warn­ings depend­ing on whether the user has requested a list file.

1    if ( dcl_any_upper )

2       {                     

3       if ( option('L') )   // This is for the list file:

4          warn(99, “Spell this name in lower case!”);

5       else                 // This is for the console:

6          warn(99, “Identifier %s should be lower case.”, dcl_name());

7       }

The message for the list file (“Spell this name…”) is appropriate because it will appear in context, directly below the offending line, with a marker under the iden­ti­fier in question. The other message is more appropriate for the con­sole, be­cause it will be seen out of context.

Sometimes it is desirable for a CodeCheck rule actually to change one of its given options. The following rule, for example, will allow CodeCheck to de­cide that nested comments  are okay as soon as it finds a nested /*.

1    if ( lin_nested_comment )

2       {                     

3       if ( ! option('N') )

4          set_option( 'N', 1 );

5       warn( 1234, “Nested comment.”);

6       }

 

 

1.4    Options can Transmit Parameters:.4  Options can Transmit Parameters;

The CodeCheck functions option() and str_option() allow the user to transmit numeric and string infor­ma­tion to CodeCheck rules. All CodeCheck com­mand-line options can be determined within CodeCheck rules. For ex­ample, if the user in­vokes CodeCheck with the command line:

check -V2 –Rerror test.c

then the function call str_option('R') will return the string "error", and option('V') will return the value 2. The former could be used to print mes­sages that refer to the name of the rule file, and the latter could be used in a CodeCheck rule to define a “verbosity” level, for example:

1    if ( stm_depth > 6 )

2       switch( option('V') )

3          {

4          case 0:  /*  one-line message   */

5             break;

6          case 1:  /*  two-line message   */

7             break:

8          case 2:  /*  extended message   */

9             break;

10         }

The command-line options –V, –W, –X, –Y are guaranteed always to be avail­able to users for any purpose. All other options have meanings pre-as­signed by Abraxas Software, or are reserved for future use.

 

 

1.5    Rules can Set Default Options:.5  Rules can Set Default Options;

Command-line options do not have to be specified in the command line itself. For example, the following rule sets up one pro­grammer’s normal op­tions, so that he does not need to type them in his com­mand line:

1    if ( prj_begin )

2       {

3       set_option('M',1);     // Expand macros in listing file.

4       set_option('B',1);     // Braces are part of compound statements.

5       set_option('E',1);     // Count macro-derived tokens too.

6

7       set_str_option( 'I', "C:\C600\INCLUDE" );

8       set_str_option( 'I', "C:\RUN286\INCLUDE" );

9       }

Defaults cannot be set on options –K and –R.


Chapter 2: CodeCheck Programming Concepts

 

 

2.1    CodeCheck Rules:.1  CodeCheck Rules;

 

A CodeCheck rule is a C if-statement, written using a restricted subset of the C gram­mar. The logical expressions that compose a rule refer to variables that are either de­clared in the CodeCheck program or are predefined by Code­Check. Here is an example of two sim­ple CodeCheck rules:

1    if ( pp_white_before > 0 )

2       warn( 2090, "Space before # is not portable.");

3

4    if ( pp_trailer )

5       warn( 2091, "Trailing tokens are not portable." );

The first rule uses the predefined variable pp_white_before, which be­comes non-zero whenever a # character is found that is separated from a new­line char­acter by whitespace (i.e. space or tab char­acters). The CodeCheck function warn() echoes its arguments (an error number and a string) to the stderr stream, with an indica­tion of the filename and line number at which the er­ror was found. The warnings look like this:

 

test.c(124): warning W2090: Space before # is not portable.

test.c(126): warning W2090: Space before # is not portable.

test.c(127): warning W2091: Trailing tokens are not portable.

If a listing file is being made (option –L), then CodeCheck will also insert the warning message into the listing file after the offend­ing line, with a letter (A, B, C, …) under the position of the er­ror. The first error message for the line refers to the position marked with the letter A; the second is marked with the letter B; etc. The listing file will look like this:

 

   123     #ifdef BSD

   124        #include <sys/dir.h>

------>    A

A: warning W2090: Space before # is not portable.

 

   125     #else

     -        #include <dirent.h>

------>    A

A: warning W2090: Space before # is not portable.

 

   127     #endif BSD

------>       A

A: warning W2091: Trailing tokens are not portable.

Note that line 126 has no line number: this indicates that it was suppressed.


2.2    Rule Evaluation:.2  Rule Evaluation;

 

The CodeCheck interpreter will evaluate a rule as often as necessary to as­sure its correct opera­tion. Thus, rules which refer to low-level lexical vari­ables will be evalu­ated most often during the code-checking process, while high-level rules will be evalu­ated least often. The order in which CodeCheck rules are found in a source rule file does not affect the order in which they are inter­preted by Code­Check.

A CodeCheck rule is triggered whenever its “if” condition is satisfied. Since CodeCheck rules can perform arithmetic and assign values to variables, it is quite possible for a CodeCheck rule to trigger other CodeCheck rules. This triggering hap­pens immediately: as soon as the value of a user-declared CodeCheck vari­able changes, all other rules using this variable are triggered. Thus Code­Check op­erates like a forward-chaining expert system, even though its rules are written in a procedural lan­guage.

It may be instructive to review the various ways in which CodeCheck both resem­bles and differs from a true expert system. For a program to be an expert system in the strict sense of the term, it must, as a minimum, have these three features:

1.  A set of “rules”, external to the program itself, ex­pressed in ei­ther of these two forms:

          1a.  if circumstances then actions

          1b.  if circumstances then conclusions

2.  A set of “facts” representing the current state of knowledge of the sys­tem.

3.  A rule interpreter with the ability to use rules in more than one way. The three most common uses for rules are the following:

     3a.  To repeatedly recognize circumstances and perform ac­tions or assert conclusions until nothing further can be done. (This kind of logical inference is known as “forward chain­ing”).

     3b.  To verify conclusions by recursively testing circum­stances. (This is known as “backward chain­ing”).

     3c.  To explain actions or conclusions by reference to the ap­pli­ca­ble chain of rules.

CodeCheck satisfies conditions (1) and (2), in that it has an external set of rules and facts of the required form. (CodeCheck “facts” are the values of its user- and pre-de­fined variables.) It also has a rule interpreter which recog­nizes circumstances and per­forms actions. However, CodeCheck uses rules in only one way — forward chain­ing.

Much of the power of expert systems derives from their flexible use of ex­ter­nal bodies of facts and rules. These so-called “rule bases” encode the knowl­edge used by the expert system in a form that is (in the ideal case) under­­stand­able and maintain­able by non-pro­grammers. CodeCheck makes use of this sig­nifi­cant source of struc­tural power, but in a purely procedural way. It is thus a hybrid be­tween a procedural interpreter and a logical expert sys­tem.


2.3    Rule Syntax:.3  Rule Syntax;

 

The syntax of a CodeCheck rule is almost the same as the syntax of an if-state­ment in C:

1    if ( expression )

2       statement

The expression in the rule condition is called the “trigger” for the rule, be­cause it de­fines the event in which the rule is to be evaluated. The state­ment in the rule may be a com­pound statement sur­rounded by braces, just as in C. The only difference between a C if-statement and a CodeCheck rule is this: a rule can have no else statement. The reason for this is easy to see — the else state­ment, if it existed, would have to be evaluated whenever the trigger is not being trig­gered, an ill-defined event.

However, the statement in a rule may certainly contain if-statements, and these may have else statements. This syntax has the following format:

 

1    if ( trigger )

2       {

3       if ( expression )

4          statement1

5       else

6          statement2

7       }

There is no ill-defined event in this context, because the event causing the evalua­tion of the rule has been unambiguously defined by the trigger.

There are no local variables in CodeCheck — all vari­ables are global, no mat­ter where they are declared. Every user-defined CodeCheck variable must be de­clared before it is used.

The only kinds of control-flow statement permitted inside a CodeCheck rule are if, while, and switch state­ments. Break and continue are permitted.

The following are not permitted:

 

             for      do      goto    return


2.4    CodeCheck Operators:.4  CodeCheck Operators;

 

The C opera­tors that are valid in CodeCheck expressions are the following:

     ( )                 function call

     [ ]                 subscript selection

      ++                pre- and post-increment

      --                  pre- and post-decrement

     +                  unary and binary plus

     -                   unary and binary minus

     *                  multiply

     /                   divide

     %                 remainder

     <<                left shift

     >>                right shift

     =                  assign

     +=                add and assign

     -=                 subtract and assign

     *=                multiply and assign

     /=                 divide and assign

     %=               remainder and assign

     !                   logical negation

     ==                logical comparison (equality)

     <                  logical comparison (less)

     >                  logical comparison (greater)

     <=                logical comparison (=)

     >=                logical comparison (=)

     !=                 logical comparison (?)

     &&               logical conjunction

     ||                logical disjunction

      ~                 bitwise complement

     &                 bitwise and

     |                  bitwise or

     &                 address-of operator

The C operators that are NOT VALID in CodeCheck expressions are:

     .                   struct and union member selection

     ->                 pointer dereference

     *                  indirection operator

     sizeof size operator

     <<=              left shift and assign

     >>=              right shift and assign

     ^                  bitwise xor

     &=               bitwise AND and assign

     |=                bitwise OR and assign

     ^=                bitwise XOR and assign

     ? :                 conditional operator

      ,                  comma operator

     ::                  C++ scope operator

     .*                 C++ object member selector

     –>*               C++ object member pointer


2.5    CodeCheck Programs:.5  CodeCheck Programs;

 

A CodeCheck program is a collection of CodeCheck rules, optionally in­clud­ing decla­rations for user-defined variables. The C pre­processor is avail­able within CodeCheck pro­grams, and normal C comments can be placed anywhere. C++ single-line comments (delimited on the left by //) are also supported.

Here, in its entirety, is an example of a CodeCheck program that calculates the density of operators per line of C code. This rule set makes use of four prede­fined CodeCheck variables: fcn_begin and fcn_end, which flag the be­ginning and end of C functions, lin_operators, which counts the number of operators in each line of code, and fcn_total_lines, which counts the number of lines in each C function.

 

 1   float    ops,     /* number of operators    */

 2            density; /* operators per line     */

 3

 4   if ( fcn_begin )

 5      ops = 0.0;

 6

 7   if ( lin_end )

 8      ops += lin_operators;

 9

10   if ( fcn_end )

11      {

12      density = ops / fcn_total_lines;

13      printf( "Function %s:\n", fcn_name() );

14      printf( "   operator density = %g\n", density );

15      }

As CodeCheck scans a C source file, it interprets these rules in the follow­ing order. Every time a function definition is found, the rule on lines 4-5 is executed. Every time an end-of-line is found, the rule on lines 7-8 is executed. And lastly, every time the end of a function is found, the rule on lines 10-15 is executed. By this mechanism the variable ops accumulates the operator count until the end of the function, and is reset to zero at the start of the next func­tion.


2.6    Predefined and User-defined Variables:.6  Predefined and User-defined Variables;

 

There are well over 400 predefined CodeCheck variables which flag the oc­currence of stylistic fea­tures and potential portability or maintenance prob­lems. These variables de­scribe features that range from the lowest level of lex­ical anal­ysis all the way up to features of the project as a whole. A de­tailed de­scription of each predefined CodeCheck variable may be found in Chapter 6. In addition to the predefined variables, the user can declare and use both in­teger and floating-point variables within any rule set.

 

2.6.1  All CodeCheck Variables are Global

Unlike C automatic and static variables, no CodeCheck vari­able is de­fined lo­cally. All CodeCheck declara­tions are treated as though they were of storage class extern, i.e. global. At the begin­ning of every CodeCheck rule file there must be a declaration for every user-de­fined vari­able that is referred to in the file. Un­like C, you may not de­clare local vari­ables within compound state­ments in CodeCheck.

 

2.6.2  Only Simple Types are Allowed

The only base types allowed for user-defined variables in this version of Code­Check are int, float, and char. Structs, unions, arrays, pointers, and functions are not allowed. Strings (i.e. zero-terminated character arrays) are al­lowed only as the return values of CodeCheck functions, and as string literals (e.g. "this is a string literal" ). A CodeCheck dec­laration may in­clude an initializer, exactly as in C, but the initial­izer must be a constant, not an expres­sion. Vari­ables without explicit initializers are initialized to zero.

On 80x86 and 680x0 platforms, the size of a CodeCheck int is 32 bits, as is the size of a CodeCheck float. For other platforms consult the README file. The CodeCheck char type is signed.

Note: Currently, one-dimensional char arrays are allowed. When such kind of variable is declared, the dimension of the array must be specified. A pointer to char type is also allowed. Therefore a pointer of such kind can be used as index to a string.

 

2.6.3  CodeCheck Variables are Frequently Reset to Zero

It is very important to understand when CodeCheck predefined variables are re-reset to 0. Each predefined variable is set to 0 at the start of exe­cution, and then again at the end of the scan of every grammatical object to which it refers. Con­sider, for example, the variable dcl_union_init, which is given the value 1 when­ever a union initializer is found. This variable refers to declarations (as in­dicated by its prefix dcl_ ), and is therefore reset to 0 at the end of every decla­ration. Thus, its value is 0 until an ini­tial­­izer for a union is found, whereupon it is set to 1. It retains this value un­til the end of the declaration, at which time it is re­set to 0.

The act of re-initializing a predefined CodeCheck variable does not cause any rules to be triggered. The CodeCheck interpreter refers to its rules only when the value of a CodeCheck variable is changed as a result of an explicit event. In the case of prede­fined variables, this event is the one de­scribed in the definition of the variable (definitions for all predefined variables are given in Chapter 6). In the case of a user-defined variable, the event is any circumstance in which its value is changed as a re­sult of the interpretation of a rule.

 

2.6.4  CodeCheck has a Storage Class for Statistical Variables

 The special statistic storage class is defined in CodeCheck for vari­ables that are used for measurement purposes. This storage class is designed to sim­plify and optimize the calculation of sta­tis­tical values (e.g. means, me­di­ans, quar­tiles, his­tograms, etc.) for software metrics. No other storage classes are permitted in CodeCheck.  

A variable in the statistic storage class receives special treatment from Code­­Check. The major difference is that every value ever assigned to the statistic is remembered, so that statistical functions of these variables (e.g. mean, correla­tion) can be readily computed. Values of statistical variables are stored in the heap, and are freed with the CodeCheck reset() function.

Some CodeCheck predefined variables are of type statistic int. As a general rule, these are the CodeCheck variables that count features of func­tions and modules. For example, at the end of every function definition scanned by Code­Check, the predefined vari­able fcn_operators is set to the num­ber of stan­dard C operators found in the line of code before macro expan­sion. Variables of storage class sta­tis­tic have these properties:

1.  Every value assigned to a statistical variable is treated as a sepa­r­ate observation or case. CodeCheck stores every case of ev­ery sta­tistical variable that is used in a rule file.

2.  The “rvalue” of a statistical variable is its most-recently assigned value. (An rvalue of a variable is the value used when the vari­able appears on the right-hand side of an assignment.)

3.  CodeCheck statistical functions can be applied to statistical vari­ables, e.g.  mean(), median(), and histogram().

4.  A statistical variable can be reset (all of its cases erased) with the CodeCheck reset() function.

5.  The increment and decrement operators (++ and --) may not be used on statistical variables.

6.  User-defined statistical variables may be statistic float or statistic int. They cannot be any other type.


Chapter 3:  CodeCheck C/C++ Analysis Variables

 

 

 

3.1    Conversion Variables:.1  Conversion Variables;

All predefined CodeCheck variables that have the prefix cnv_ refer to charac­ter­istics of the implicit type conversions that frequently occur as executable oper­ators are evaluated. Every CodeCheck conversion variable is initial­ized to zero at the start of execution, and again at the end of the scan of the operands of every executable operator.

 

cnv_any_to_bitfield          Set to 1 when an expression requires an implicit con­version from any type to a bitfield.

cnv_any_to_ptr                 Set to 1 when an expression requires an implicit con­version from any non-pointer type to a pointer type.

cnv_bitfield_to_any          Set to 1 when an expression requires an implicit con­version from a bitfield to any type.

cnv_const_to_any              Set to 1 when an expression requires an implicit con­version from a constant type to any non-constant type.

cnv_float_to_int                Set to 1 when an expression requires an implicit con­version from a floating-point type to an integer type.

cnv_int_to_float                Set to 1 when an expression requires an implicit con­version from an integer type to a floating-point type.

cnv_ptr_to_any                 Set to 1 when an expression requires an implicit con­version from a pointer type to any non-pointer type.

cnv_ptr_to_ptr                  Set to 1 when an expression requires an implicit con­version from a pointer type to a different pointer type.

cnv_signed_to_any            Set to 1 when an expression requires an implicit con­version from a signed type to any unsigned type.

cnv_truncate                     Set to 1 when an expression requires an implicit con­version from a larger arithmetic type to a smaller arithmetic type.


3.2    Declaration Variables:.2  Declaration Variables;

 

All predefined CodeCheck variables that have the prefix dcl_ refer to charac­ter­istics of declarators. Every CodeCheck declaration variable is initial­ized to zero at the start of execution, and again at the end of the scan of every declarator. If the declara­tor has an initializer, then reinitialization occurs at the end of the scan of the initializer.

A declarator declares the name, type, and initial value of a single vari­able or func­tion (there can be more than one declarator in a declaration). For ex­am­ple, the follow­ing declaration has four declarators, of which two are func­tions and one has an initial­izer:

         long           eeny, meeny = 1, miny(), moe();

The end of a declarator is marked by a comma or semicolon. CodeCheck evalu­ates declarators recursively, so that variables that refer to declarators that con­tain de­clara­tors are correctly set.

 

dcl_3dots                          Set to 1 whenever an ellipsis (...) is found.