### Install Lizard from source Source: https://github.com/terryyin/lizard/blob/master/README.rst Install Lizard from the source code, specifying an installation directory. This method ensures all functionalities are available. ```bash [sudo] python setup.py install --prefix=/path/to/installation/directory/ ``` -------------------------------- ### GitHub Actions for Code Complexity Checks Source: https://context7.com/terryyin/lizard/llms.txt Set up a GitHub Actions workflow to check code complexity. This example installs Lizard, runs the analysis with complexity and length thresholds, and fails the action if the checks are not met. ```yaml - name: Check code complexity run: | pip install lizard lizard -C 15 -L 100 -w src/ || exit 1 ``` -------------------------------- ### Install Lizard using pip Source: https://github.com/terryyin/lizard/blob/master/README.rst Install Lizard globally using pip for full functionality. Ensure you have Python 3.8 or higher. ```bash [sudo] pip install lizard ``` -------------------------------- ### Example Complexity Calculation Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Illustrates how cyclomatic complexity is calculated, including base complexity and additions for control flow and logical operators. ```python def example(x, y): if x > 0 and y > 0 or x < -10: # +1 (if) +1 (and) +1 (or) for i in range(10): # +1 (for) pass # Total CCN: 1 (base) + 3 (if, and, or) + 1 (for) = 5 ``` -------------------------------- ### C-like Language Reader Example Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Reader configuration for C-like languages, defining control flow keywords, logical operators, case keywords, and ternary operators using symbols. ```python class CStyleReader(CodeReader, CCppCommentsMixin): _control_flow_keywords = {'if', 'for', 'while', 'catch'} _logical_operators = {'&&', '||'} _case_keywords = {'case'} _ternary_operators = {'?'} ``` -------------------------------- ### Create State Machine for MyLanguage Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Define the state machine for the new language, including methods for different states like global and function name parsing. This example shows how to push a new function context and set its name. ```python class MyLanguageStates(CodeStateMachine): def _state_global(self, token): if token == 'func': self.context.push_new_function('anonymous') self._state = self._function_name def _function_name(self, token): self.context.current_function.name = token self._state = self._state_global ``` -------------------------------- ### Script Language Reader Example Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Reader configuration for script languages, using word-based operators for control flow and logical operations. Case keywords and ternary operators are empty sets. ```python class ScriptStyleReader(CodeReader): _control_flow_keywords = {'if', 'elif', 'for', 'while', 'except'} _logical_operators = {'and', 'or'} _case_keywords = set() _ternary_operators = set() ``` -------------------------------- ### ST Language Keywords (Case-Insensitive) Source: https://github.com/terryyin/lizard/blob/master/ongoing/condition-categories-reference.md Example of control flow and logical operators in ST (Structured Text), demonstrating case-insensitivity by including both upper and lower case versions. ```st _control_flow_keywords = {'if', 'elsif', 'IF', 'ELSIF', ...} ``` ```st _logical_operators = {'and', 'or', 'AND', 'OR'} ``` -------------------------------- ### Case-Insensitive Language Reader Example Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Reader configuration for case-insensitive languages, specifying keywords and operators in both upper and lower case. Includes both symbol and word-based operators. ```python class CaseInsensitiveReader(CodeReader): _control_flow_keywords = {'IF', 'if', 'FOR', 'for'} _logical_operators = {'.AND.', '.and.', '.OR.', '.or.'} _case_keywords = {'CASE', 'case'} _ternary_operators = set() ``` -------------------------------- ### Mixed Style Language Reader Example Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Reader configuration for mixed-style languages that support both word-based and symbol-based logical operators. Includes common control flow keywords and symbol-based ternary operators. ```python class MixedReader(CodeReader): _control_flow_keywords = {'if', 'for', 'while'} _logical_operators = {'and', 'or', '&&', '||'} # Both forms _case_keywords = set() _ternary_operators = {'?'} ``` -------------------------------- ### TagCloud Get Line Height Method Source: https://github.com/terryyin/lizard/blob/master/codecloud.html Calculates the line height based on the current font size. Uses 'M' character width as a reference. ```javascript TagCloud.prototype.getLineHeight = function (fontSize) { return this.ctx.measureText('M').width * 1.2; } ``` -------------------------------- ### GDScript Control Flow Keywords Source: https://github.com/terryyin/lizard/blob/master/ongoing/condition-categories-reference.md Example of control flow keywords in GDScript, which follows Python-like syntax and includes 'elif'. ```gdscript _control_flow_keywords = {'if', 'elif', 'for', 'while', 'catch', 'do'} ``` -------------------------------- ### Get filenames from an input file Source: https://github.com/terryyin/lizard/blob/master/README.rst Provide a list of filenames to analyze by specifying an input file using the -f option. This is useful for analyzing a predefined set of files. ```bash lizard -f input_files.txt ``` -------------------------------- ### Lizard Whitelist Configuration Source: https://github.com/terryyin/lizard/blob/master/README.rst Example content for a `whitelizard.txt` file used to ignore specific functions or files from Lizard analysis. Place this file in the current directory or specify its path using the -W option. ```text #whitelizard.txt #The file name can only be whitelizard.txt and put it in the current folder. #You may have commented lines begin with #. function_name1, function_name2 # list function names in multiple lines or split with comma. file/path/name:function1, function2 # you can also specify the filename ``` -------------------------------- ### Remove Logical Operators Example Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Demonstrates how to selectively remove specific categories of tokens, such as logical operators in non-strict mode, using set operations. ```python # Remove only logical operators (non-strict mode) reader.conditions -= reader.logical_operators ``` -------------------------------- ### LanguageReader Override Example Source: https://github.com/terryyin/lizard/blob/master/ongoing/code-structure-reference.md Illustrates how a specific language reader can override the default condition categories defined in the base CodeReader class. ```python class LanguageReader(CodeReader): _control_flow_keywords = {'if', 'for', 'while'} _logical_operators = {'&&', '||'} _case_keywords = {'case'} _ternary_operators = {'?'} ``` -------------------------------- ### TagCloud Get Coverage Method Source: https://github.com/terryyin/lizard/blob/master/codecloud.html Calculates the percentage of the canvas that is covered by rendered pixels. It iterates through all pixel data to count non-transparent pixels. ```javascript TagCloud.prototype.getCoverage = function () { var pix = this.ctx.getImageData( 0, 0, this.canvasWidth, this.canvasHeight).data; var pixCount = 0; for (var i = 0, n = pix.length; i < n; i += 4) { if (pix[i+3]) pixCount++; } return pixCount * 100 / this.canvasWidth / this.canvasHeight; }; ``` -------------------------------- ### Nested Control Structures Example Source: https://github.com/terryyin/lizard/blob/master/theory.rst This C++ code demonstrates deep nesting of control structures (while, for, for, if). Lizard's Nested Control Structures metric counts the depth of these nests, which can indicate overly complex code. ```cpp int foo() { while (expr1) { for (; expr2;) { for (; expr3;) { if (expr4) return 42; } } } return -42; } ``` -------------------------------- ### Define Multi-word Keywords Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Include complete multi-word keywords as single entries to ensure they are correctly identified. For example, 'else if' in R. ```python _control_flow_keywords = {'if', 'else if', 'for'} # 'else if' is one keyword in R ``` -------------------------------- ### TagCloud Get Random Color Method Source: https://github.com/terryyin/lizard/blob/master/codecloud.html Returns a random color from a predefined list of CSS color names. ```javascript TagCloud.prototype._getRandomColor = function (){ var colors = ["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal"]; return colors[Math.floor(colors.length * Math.random())]; }; ``` -------------------------------- ### Analyze Function Metrics with Lizard Source: https://context7.com/terryyin/lizard/llms.txt Analyze a JavaScript file to get detailed metrics for each function. Access properties like name, complexity, and line numbers. ```python import lizard file_info = lizard.analyze_file.analyze_source_code("sample.js", """ function processOrder(order, user, discount, shipping, tax) { if (!order) return null; if (order.items.length === 0) return null; let total = 0; for (const item of order.items) { if (item.available) { total += item.price * item.quantity; } } return total * (1 - discount) + shipping + tax; } """) func = file_info.function_list[0] print(func.name) # 'processOrder' print(func.long_name) # 'processOrder( order , user , discount , shipping , tax )' print(func.cyclomatic_complexity) # 5 print(func.nloc) # 10 print(func.token_count) # ~55 print(func.parameter_count) # 5 print(func.parameters) # ['order', 'user', 'discount', 'shipping', 'tax'] print(func.length) # end_line - start_line + 1 print(func.start_line) # 2 print(func.end_line) # 12 print(func.location) # ' processOrder@2-12@sample.js' print(func.unqualified_name) # 'processOrder' (no namespace prefix) ``` -------------------------------- ### R Language Logical Operators Source: https://github.com/terryyin/lizard/blob/master/ongoing/condition-categories-reference.md Example of logical operators in R, including both short-circuit (&&, ||) and element-wise (&, |) operators, all of which count towards complexity. ```r _logical_operators = {'&&', '||', '&', '|'} ``` -------------------------------- ### TagCloud Get Non-Overlapping Place Method Source: https://github.com/terryyin/lizard/blob/master/codecloud.html Finds a suitable placement for a tag with a given font size. It measures text width and height, then attempts to find an empty spot using a spiral offset pattern. Returns placement details or null if no spot is found. ```javascript TagCloud.prototype._getNonOverlappingPlaceWithBestSize = function (fontSize, tag) { this.ctx.font = "" + fontSize + "pt " + "Arial"; var lineHeight=this.getLineHeight(fontSize); var tagWidth = this.ctx.measureText(tag).width; var base = new BasePlacement( (this.canvasWidth - tagWidth) * Math.random(), (this.canvasHeight - lineHeight) * Math.random(), lineHeight ); var placement; /* jshint ignore:start */ while (placement = base.nextPlaceToTry()) { if (this._isPlaceEmpty(placement, tagWidth, lineHeight)) break; } /* jshint ignore:end */ return placement; }; ``` -------------------------------- ### Generate HTML output with Lizard Source: https://context7.com/terryyin/lizard/llms.txt Use the -H or --html flag to generate an interactive HTML report. This requires the 'jinja2' Python package to be installed. The format can also be inferred from the .html extension. ```bash pip install jinja2 ``` ```bash lizard -H mySource/ > report.html ``` ```bash lizard mySource/ -o report.html ``` -------------------------------- ### Erlang Ternary Operator Usage Source: https://github.com/terryyin/lizard/blob/master/ongoing/condition-categories-reference.md Example for Erlang where '?' is used for macro expansion, which still contributes to complexity despite not being a traditional ternary operator. ```erlang _ternary_operators = {'?'} ``` -------------------------------- ### Extension Pattern: Remove Logical Operators Source: https://github.com/terryyin/lizard/blob/master/ongoing/code-structure-reference.md An example of an extension that modifies the condition set by removing logical operators, thereby excluding them from the CCN calculation. ```python class LizardExtension(object): def __call__(self, tokens, reader): # Remove logical operators from conditions reader.conditions -= reader.logical_operators return tokens ``` -------------------------------- ### Set Warning Threshold for NLOC Source: https://github.com/terryyin/lizard/blob/master/README.rst Configure Lizard to report warnings for functions exceeding a specified Number of Logical Lines of Code (NLOC). This example sets the threshold to 25. ```bash lizard -T nloc=25 ``` -------------------------------- ### Analyze a source file using Lizard Python API Source: https://context7.com/terryyin/lizard/llms.txt The primary entry point for programmatic use. Call 'lizard.analyze_file(filename)' to get a FileInformation object. This object contains details about the file and its functions. ```python import lizard # Analyze a file on disk file_info = lizard.analyze_file("src/main.cpp") print(file_info.filename) # 'src/main.cpp' print(file_info.nloc) # Total non-comment lines of code print(file_info.CCN) # Sum of CCN across all functions for func in file_info.function_list: print(f"{func.name}: CCN={func.cyclomatic_complexity}, " f"NLOC={func.nloc}, params={func.parameter_count}, " f"tokens={func.token_count}, length={func.length}, " f"start={func.start_line}, end={func.end_line}") # Example output: # main: CCN=3, NLOC=12, params=2, tokens=45, length=15, start=10, end=24 ``` -------------------------------- ### Assertion Example in C++ Source: https://github.com/terryyin/lizard/blob/master/theory.rst This C++ code shows a typical assertion with a message. Lizard's IgnoreAssert extension can be used to exclude the complexity of such assertions from the total CCN calculation, focusing on the inherent complexity of the function's logic. ```cpp assert(expression && "More description..."); ``` -------------------------------- ### Create MyLanguageReader Class Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Define a new language reader by inheriting from CodeReader and optionally CCppCommentsMixin. Specify file extensions and language names. Configure control flow keywords, logical operators, case keywords, and ternary operators. Initialize parallel states. ```python from .code_reader import CodeReader, CodeStateMachine from .clike import CCppCommentsMixin # If language has C-style comments class MyLanguageReader(CodeReader, CCppCommentsMixin): ext = ['mylang'] # File extensions language_names = ['mylanguage', 'mylang'] # Command line names # Separated condition categories _control_flow_keywords = {'if', 'for', 'while', 'catch'} _logical_operators = {'&&', '||'} _case_keywords = {'case'} _ternary_operators = {'?'} def __init__(self, context): super(MyLanguageReader, self).__init__(context) self.parallel_states = [MyLanguageStates(context)] ``` -------------------------------- ### Configure Whitelist File for Warnings Source: https://context7.com/terryyin/lizard/llms.txt Create a `whitelizard.txt` file or use the `-W` flag to permanently suppress warnings for specific functions or file+function pairs. The file path must match Lizard's output exactly. ```text # whitelizard.txt # Suppress by function name alone legacy_init, old_parser # Suppress by file path + function name (path must match Lizard's output path exactly) src/legacy/tokenizer.cpp:tokenize_input, build_ast ``` -------------------------------- ### Sample CSV output with header Source: https://context7.com/terryyin/lizard/llms.txt This sample shows the CSV output format with a verbose header row, detailing columns like NLOC, CCN, and function location. ```csv # NLOC,CCN,token,PARAM,length,location,file,function,long_name,start,end # 10,2,29,2,12,"start_new_player@26-37@./html_game.c","./html_game.c","start_new_player","start_new_player( int id , char * name )",26,37 ``` -------------------------------- ### Output warnings in Visual Studio format Source: https://github.com/terryyin/lizard/blob/master/README.rst Display only warnings, formatted for Visual Studio. This is helpful for developers using VS IDE. ```bash lizard --warning-msvs ``` -------------------------------- ### Specify output file for analysis results Source: https://github.com/terryyin/lizard/blob/master/README.rst Save the analysis results to an HTML file named 'output.html'. The output format is inferred from the file extension. ```bash lizard -o output.html ``` -------------------------------- ### TagCloud Render Method Source: https://github.com/terryyin/lizard/blob/master/codecloud.html Renders the tags onto the canvas. Sets text baseline and iterates through tags to place them. Requires an array of tags. ```javascript TagCloud.prototype.render = function (tags) { this.ctx.textBaseline = "top"; tags.forEach(function (tag) { this.placeTag(tag[0]); }, this); }; ``` -------------------------------- ### Pattern Matching Keywords Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md For languages with pattern matching, define keywords like 'match' and 'when' and use an empty set for traditional 'case' keywords. ```python _control_flow_keywords = {'match', 'when'} # Rust, Scala _case_keywords = set() # Not using traditional case ``` -------------------------------- ### Automatic .gitignore Filtering Source: https://context7.com/terryyin/lizard/llms.txt Lizard automatically uses `.gitignore` files to exclude matched files if they exist at the analyzed path. Requires the `pathspec` Python package to be installed. ```bash lizard mySource/ # Files matching .gitignore patterns in mySource/ are automatically skipped ``` -------------------------------- ### Extension Pattern: Special Case Handling Source: https://github.com/terryyin/lizard/blob/master/ongoing/code-structure-reference.md Demonstrates an extension that implements special handling for consecutive 'case' keywords, subtracting complexity for subsequent cases to avoid overcounting. ```python class LizardExtension(ExtensionBase): def _state_global(self, token): if token == "case": # Detect case keywords self._state = self._in_case def _after_a_case(self, token): if token == "case": # Consecutive case self.context.add_condition(-1) # Subtract complexity ``` -------------------------------- ### Python-style Condition Complexity Source: https://github.com/terryyin/lizard/blob/master/ongoing/condition-categories-reference.md Demonstrates Cyclomatic Complexity calculation in Python, including if, and, for, and except clauses. ```python def func(x, y): if x > 0 and y > 0: # +1 (if) +1 (and) for i in range(10): # +1 (for) try: process() except Exception: # +1 (except) pass # Total CCN: 1 (base) + 1 + 1 + 1 + 1 = 5 ``` -------------------------------- ### C-style Condition Complexity Source: https://github.com/terryyin/lizard/blob/master/ongoing/condition-categories-reference.md Illustrates Cyclomatic Complexity calculation in C, including if, &&, switch, case, and ternary operators. ```c int func(int x, int y) { if (x > 0 && y > 0) { // +1 (if) +1 (&&) switch(x) { // +0 (switch itself) case 1: // +1 case 2: // +1 break; } } return x > 0 ? 1 : -1; // +1 (?) } // Total CCN: 1 (base) + 1 + 1 + 1 + 1 + 1 = 6 ``` -------------------------------- ### Initialize Duplicate Code Detection Extension Source: https://context7.com/terryyin/lizard/llms.txt Instantiate the LizardDuplicate extension and add it to the list of extensions for file analysis. This enables the detection of copy-pasted code. ```python import lizard from lizard_ext.lizardduplicate import LizardExtension as DuplicateExtension dup_ext = DuplicateExtension() extensions = lizard.get_extensions([]) + [dup_ext] ``` -------------------------------- ### Load Lizard Extensions for Custom Analysis Source: https://context7.com/terryyin/lizard/llms.txt Load extensions, such as nesting-depth analysis, to build a custom processor pipeline. Use this with the FileAnalyzer for extended metrics. ```python import lizard # Build an extension pipeline including nesting-depth analysis extensions = lizard.get_extensions(["nd"]) # loads lizard_ext.lizardnd file_analyzer = lizard.FileAnalyzer(extensions) file_info = file_analyzer("src/complex.cpp") for func in file_info.function_list: print(f"{func.name}: CCN={func.cyclomatic_complexity}, " f"MaxNestingDepth={func.max_nesting_depth}") ``` -------------------------------- ### Draw Function for Canvas Initialization Source: https://github.com/terryyin/lizard/blob/master/codecloud.html Initializes the canvas element and the TagCloud instance. Handles high-DPI scaling by doubling canvas dimensions if necessary. Renders a sample tag cloud. ```javascript function draw() { var canvas = document.getElementById("canvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); // scale 2x if(window.devicePixelRatio == 2) { canvas.setAttribute('width', canvas.width * 2); canvas.setAttribute('height', canvas.height * 2); } var tagCloud = new TagCloud(canvas.width, canvas.height, ctx); tagCloud.render([ ["bar", 2], ["0", 1], ["1", 1], ["2", 1], ["3", 1], ["foo", 1], ["switch", 1], ]); } } ``` -------------------------------- ### Output warnings in clang/gcc format Source: https://github.com/terryyin/lizard/blob/master/README.rst Display only warnings, formatted according to clang/gcc standards. This option is useful for integrating with build systems. ```bash lizard -w ``` -------------------------------- ### Basic Recursive Directory Analysis Source: https://context7.com/terryyin/lizard/llms.txt Run Lizard on all recognized source files under a path, reporting per-function metrics and functions exceeding the default CCN threshold. ```bash # Analyze current directory lizard # Analyze a specific source tree lizard mySource/ # Expected output: # ============================================================== # NLOC CCN token param function@line@file # -------------------------------------------------------------- # 10 2 29 2 start_new_player@26@./html_game.c # 6 1 3 0 set_shutdown_flag@449@./httpd.c # -------------------------------------------------------------- # 2 file analyzed. # ============================================================== # LOC Avg.NLOC AvgCCN Avg.token function_cnt file # -------------------------------------------------------------- # 191 15 3 51 12 ./html_game.c # ====================================== # !!!! Warnings (CCN > 15) !!!! # ====================================== # 66 19 247 1 accept_request@64@./httpd.c ``` -------------------------------- ### Minimal C code causing Lizard crash Source: https://github.com/terryyin/lizard/blob/master/prompt-history.md This C code example, when analyzed by Lizard with the -w flag, triggers a crash due to the deeply nested conditional statements. Save this code as 'test.c' to reproduce the issue. ```c #include void func() { int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o; if (a) { // Do nothing. } else if (b) { // Do nothing. } else if (c) { // Do nothing. } else if (d) { // Do nothing. } else if (e) { // Do nothing. } else if (f) { // Do nothing. } else if (g) { // Do nothing. } else if (h) { // Do nothing. } else if (i) { // Do nothing. } else if (j) { // Do nothing. } else if (k) { // Do nothing. } else if (l) { // Do nothing. } else if (m) { // Do nothing. } else if (n) { // Do nothing. } else if (o) { // Do nothing. } else { // Do nothing. } } ``` -------------------------------- ### Generate Tag Cloud with Word Count Extension Source: https://context7.com/terryyin/lizard/llms.txt Utilize the `-EWordCount` extension to count identifier frequencies and generate an HTML5 tag-cloud visualization. This command opens `codecloud.html` in the default browser. ```bash lizard -EWordCount src/ ``` -------------------------------- ### TagCloud Is Place Empty Method Source: https://github.com/terryyin/lizard/blob/master/codecloud.html Checks if a proposed placement area on the canvas is empty. It verifies boundaries and checks pixel data for transparency. Also includes an elliptical boundary check. ```javascript TagCloud.prototype._isPlaceEmpty = function (placement, width, height) { if (placement.x < 0 || placement.y < 0 || placement.x + width > this.canvasWidth || placement.y + height > this.canvasHeight) return false; var pix = this.ctx.getImageData( placement.x, placement.y, width, height).data; for (var i = 0, n = pix.length; i < n; i += 4) if (pix[i+3]) return false; return [[placement.x, placement.y], [placement.x + width, placement.y], [placement.x, placement.y + height], [placement.x + width, placement.y + height]].every( function(pos) { var a = this.canvasWidth / 2; var b = this.canvasHeight / 2; var X = pos[0] - a; var Y = pos[1] - b; return (X * X / a / a + Y * Y / b / b < 1); }, this); }; ``` -------------------------------- ### Visual Studio Warning Format with --warning-msvs Source: https://context7.com/terryyin/lizard/llms.txt Emit warnings in MSVS format for use in Visual Studio build output. The format includes file, line number, warning type, function name, and signature. ```bash lizard --warning-msvs mySource/ # Output: # ./src/httpd.c(64): warning: accept_request (accept_request( struct request_info * info )) has ... ``` -------------------------------- ### lizard.analyze(paths, exclude_pattern, threads, exts, lans) Source: https://context7.com/terryyin/lizard/llms.txt Provides an iterator-based API for batch analysis of multiple files or directories with full option support. ```APIDOC ### `lizard.analyze(paths, exclude_pattern, threads, exts, lans)` — Batch analyze paths Iterator-based API for analyzing multiple files or directories with full option support. ```python import lizard # Analyze all Python and Java files in src/, excluding tests results = lizard.analyze( paths=["src/"], exclude_pattern=["./src/tests/*"], threads=4, lans=["python", "java"] ) for file_info in results: if file_info is None: continue print(f"\n--- {file_info.filename} ---") print(f" NLOC: {file_info.nloc}") print(f" Avg CCN: {file_info.average_cyclomatic_complexity:.2f}") for func in file_info.function_list: if func.cyclomatic_complexity > 10: print(f" [WARNING] {func.name} CCN={func.cyclomatic_complexity} " f"at line {func.start_line}") ``` ``` -------------------------------- ### Case Keywords for Switch/Case and Pattern Matching Source: https://github.com/terryyin/lizard/blob/master/ongoing/condition-categories-reference.md Sets of keywords used for switch/case branch labels and pattern matching in different languages. Some languages use empty sets if they rely on other constructs like match arms. ```python _case_keywords = {'case'} ``` ```rust _case_keywords = set() ``` ```scala _case_keywords = {'case'} ``` -------------------------------- ### Implement Token Generation Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Extend the default token generation by adding language-specific patterns. This method is static and should be overridden to include custom regular expressions for tokenization. ```python @staticmethod def generate_tokens(source_code, addition='', token_class=None): # Add language-specific patterns addition = addition + r"|pattern1|pattern2" return CodeReader.generate_tokens(source_code, addition, token_class) ``` -------------------------------- ### Run Lizard excluding specific folders Source: https://github.com/terryyin/lizard/blob/master/README.rst Analyze code in 'mySource/' while excluding the './tests/' directory and its contents using the -x option. ```bash lizard mySource/ -x "./tests/*" ``` -------------------------------- ### Sample Cppncss XML output fragment Source: https://context7.com/terryyin/lizard/llms.txt This is a sample fragment of the XML output generated by Lizard, showing function metrics like NCSS and CCN. ```xml 182 ``` -------------------------------- ### Analyze File Aggregate Metrics with Lizard Source: https://context7.com/terryyin/lizard/llms.txt Analyze a C++ file to obtain aggregate metrics for the entire file. This includes total lines of code, token count, and average complexity. ```python import lizard file_info = lizard.analyze_file("src/engine.cpp") print(file_info.nloc) # Total NLOC print(file_info.token_count) # Total token count print(file_info.CCN) # Sum of all function CCNs print(file_info.average_nloc) # Average NLOC per function print(file_info.average_cyclomatic_complexity) # Average CCN per function print(file_info.average_token_count) # Average tokens per function print(len(file_info.function_list)) # Number of functions found ``` -------------------------------- ### Analyze Files with Lizard Source: https://context7.com/terryyin/lizard/llms.txt Use `analyze_files` to process source files and `get_all_source_files` to collect them. Exhaust the iterator to ensure analysis is complete. ```python import lizard results = lizard.analyze_files( lizard.get_all_source_files(["src/"], [], None), threads=1, exts=extensions ) list(results) # exhaust the iterator ``` -------------------------------- ### Rust Language Condition Keywords Source: https://github.com/terryyin/lizard/blob/master/ongoing/code-structure-reference.md Lists the keywords for control flow, logical operators, case statements (using match arms), and ternary operators relevant to Rust's complexity analysis. ```rust _control_flow_keywords = {'if', 'for', 'while', 'catch', 'match', 'where'} _logical_operators = {'&&', '||'} _case_keywords = set() # Rust uses match arms, not case _ternary_operators = {'?'} # Error propagation operator ``` -------------------------------- ### Extension Pattern: Track All Complexity Keywords Source: https://github.com/terryyin/lizard/blob/master/ongoing/code-structure-reference.md An extension that records all tokens contributing to complexity, along with their line numbers, into a 'complex_tags' list within the context. ```python class LizardExtension(object): def __call__(self, tokens, reader): conditions = reader.conditions # Use combined set for token in tokens: if token in conditions: # Record [token, line_number] context.current_function.complex_tags.append([token, line]) yield token ``` -------------------------------- ### HTML Output Source: https://context7.com/terryyin/lizard/llms.txt Generates an interactive HTML report with sortable and searchable DataTables, requiring the Jinja2 library. ```APIDOC ### HTML output (`-H` / `--html`) Generates an interactive HTML report with sortable/searchable DataTables (requires `jinja2`). ```bash pip install jinja2 lizard -H mySource/ > report.html lizard mySource/ -o report.html # format inferred from .html extension ``` ``` -------------------------------- ### Generate XML output with Lizard Source: https://context7.com/terryyin/lizard/llms.txt Use the -X or --xml flag to generate Cppncss-compatible XML reports. The output format can also be inferred from the .xml file extension. ```bash lizard -X mySource/ > report.xml ``` ```bash lizard mySource/ -o report.xml ``` -------------------------------- ### XML Output Source: https://context7.com/terryyin/lizard/llms.txt Generates Cppncss-compatible XML output, suitable for integration with tools like Jenkins. ```APIDOC ## XML Output Produces cppncss-compatible XML, suitable for Jenkins with the cppncss plugin. ```bash lizard -X mySource/ > report.xml lizard mySource/ -o report.xml # format inferred from .xml extension ``` ```xml 182 ``` ``` -------------------------------- ### Checkstyle XML Output Source: https://context7.com/terryyin/lizard/llms.txt Generates Checkstyle-compatible XML, useful for integration with the Jenkins Checkstyle plugin. ```APIDOC ### Checkstyle XML output (`--checkstyle`) Generates Checkstyle-compatible XML for Jenkins Checkstyle plugin or other tools. ```bash lizard --checkstyle mySource/ > report.checkstyle.xml lizard mySource/ -o report.checkstyle.xml # inferred from .checkstyle.xml extension ``` ``` -------------------------------- ### Warnings-Only Output with -w Source: https://context7.com/terryyin/lizard/llms.txt Emit only warning lines in clang/gcc diagnostic format, useful for editor integrations. Includes NLOC, CCN, token count, parameter count, length, and ND (nesting depth). ```bash lizard -w mySource/ # Output: # ./src/httpd.c:64: warning: accept_request has 66 NLOC, 19 CCN, 247 token, 1 PARAM, 70 length, 4 ND ``` -------------------------------- ### Test Simple Function in MyLang Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Tests the parsing of a basic function in a custom language (MyLang). Ensures correct function name and cyclomatic complexity are identified. ```python import unittest from lizard import analyze_file def get_mylang_function_list(source_code): return analyze_file.analyze_source_code("test.mylang", source_code).function_list class TestMyLanguage(unittest.TestCase): def test_simple_function(self): code = ''' func simple() { return 1 } ''' result = get_mylang_function_list(code) self.assertEqual(1, len(result)) self.assertEqual("simple", result[0].name) self.assertEqual(1, result[0].cyclomatic_complexity) ``` -------------------------------- ### TagCloud Place Tag Method Source: https://github.com/terryyin/lizard/blob/master/codecloud.html Places a single tag on the canvas. It repeatedly tries to find a non-overlapping position with decreasing font size until successful. Assigns a random color to the tag. ```javascript TagCloud.prototype.placeTag = function (tag) { var placement; while (!(placement = this._getNonOverlappingPlaceWithBestSize( this.fontSize, tag))) this.fontSize *= 0.9; this.ctx.fillStyle = this._getRandomColor(); this.ctx.fillText(tag, placement.x, placement.y); }; ``` -------------------------------- ### Access Specific Token Categories Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Shows how to access and check for tokens within specific categories like 'control_flow_keywords' or 'case_keywords' for custom analysis. ```python # Access specific categories if token in reader.control_flow_keywords: ... if token in reader.case_keywords: ... ``` -------------------------------- ### Read File List from File with -f Source: https://context7.com/terryyin/lizard/llms.txt Specify a file containing a list of files to analyze, one per line. This is an alternative to providing paths directly on the command line. ```bash lizard -f file_list.txt ``` -------------------------------- ### Define Empty Keyword Sets Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Use empty sets for language constructs not present in the target language, such as 'case' keywords or ternary operators, to maintain consistency. ```python _case_keywords = set() # Python uses if/elif, not case _ternary_operators = set() # Python uses 'x if c else y', not ? ``` -------------------------------- ### BasePlacement Class Definition Source: https://github.com/terryyin/lizard/blob/master/codecloud.html Defines the BasePlacement class for managing placement attempts. It uses spiral offsets to determine the next position to try. ```javascript function BasePlacement(x, y, h) { var baseX = x, baseY = y, scale = h, tryNumber = 0; this.nextPlaceToTry = function() { if (tryNumber < this._spiralOffsets.length) return { x : baseX + this._spiralOffsets[tryNumber][0] * scale, y : baseY + this._spiralOffsets[tryNumber++][1] * scale }; }; } ``` -------------------------------- ### Generate Checkstyle XML output with Lizard Source: https://context7.com/terryyin/lizard/llms.txt Use the --checkstyle flag to generate Checkstyle-compatible XML, suitable for Jenkins Checkstyle plugin. The format can also be inferred from the .checkstyle.xml extension. ```bash lizard --checkstyle mySource/ > report.checkstyle.xml ``` ```bash lizard mySource/ -o report.checkstyle.xml ``` -------------------------------- ### Measure Nesting Depth with Lizard Extension Source: https://context7.com/terryyin/lizard/llms.txt Use the `-END` extension to measure the maximum nesting depth of control structures in functions. The output includes an 'ND' column. Requires importing `lizardnd`. ```bash lizard -END -N 5 src/ ``` ```python import lizard from lizard_ext import lizardnd # patches FileInfoBuilder automatically extensions = lizard.get_extensions(["nd"]) file_info = lizard.FileAnalyzer(extensions)("src/parser.c") for func in file_info.function_list: print(f"{func.name}: ND={func.max_nesting_depth}") # parse_expression: ND=6 ``` -------------------------------- ### Analyze a Folder Recursively with Lizard Source: https://github.com/terryyin/lizard/blob/master/README.rst Use this command to analyze all files within a specified folder recursively. The output provides detailed metrics for each function and a summary for each file. ```bash lizard mahjong_game/src ``` -------------------------------- ### R Language Condition Keywords Source: https://github.com/terryyin/lizard/blob/master/ongoing/code-structure-reference.md Details the keywords for control flow, logical operators (including element-wise), case statements, and ternary operators applicable to R code complexity. ```r _control_flow_keywords = {'if', 'else if', 'for', 'while', 'repeat', 'switch', 'tryCatch', 'try', 'ifelse'} _logical_operators = {'&&', '||', '&', '|'} # Both short-circuit and element-wise _case_keywords = set() _ternary_operators = set() ``` -------------------------------- ### Multi-threaded Analysis with -t Source: https://context7.com/terryyin/lizard/llms.txt Utilize multiple worker threads to accelerate analysis on large codebases. Specify the number of threads to use. ```bash lizard -t 4 mySource/ ``` -------------------------------- ### Reproduce Lizard Crash with -w flag Source: https://github.com/terryyin/lizard/blob/master/prompt-history.md This command reproduces the crash in Lizard when analyzing a C file with the -w flag. Ensure the C file is saved as 'test.c' in the current directory. ```bash lizard -w test.c ``` -------------------------------- ### Run Lizard using .gitignore Source: https://github.com/terryyin/lizard/blob/master/README.rst Analyze code in 'mySource/' and automatically exclude files listed in the .gitignore file. This is useful for analyzing only tracked files. ```bash lizard mySource/ ``` -------------------------------- ### Generate Code Tag Cloud with Lizard Source: https://github.com/terryyin/lizard/blob/master/README.rst Generate a tag cloud representing identifier frequency in your code. This command ignores comments. Replace `` with the relevant path. ```bash lizard -EWordCount ``` -------------------------------- ### CCN Threshold with -C or -T Source: https://context7.com/terryyin/lizard/llms.txt Set a custom cyclomatic complexity warning threshold. The default is 15. ```bash # Warn on any function with CCN > 10 lizard -C 10 mySource/ # Equivalent using -T (Threshold) lizard -T cyclomatic_complexity=10 mySource/ ``` -------------------------------- ### Run Lizard in verbose mode Source: https://github.com/terryyin/lizard/blob/master/README.rst Execute Lizard in verbose mode to display long function names in the output. This can provide more detailed information. ```bash lizard -V ``` -------------------------------- ### Exclude Paths with -x Source: https://context7.com/terryyin/lizard/llms.txt Glob-based file exclusion using `*` and `?`. Supports multiple exclusion patterns. ```bash # Exclude everything under tests/ lizard mySource/ -x"./tests/*" # Exclude generated files lizard mySource/ -x"*_generated.cpp" -x"./build/*" ``` -------------------------------- ### Exclude C Preprocessor #else Branches Source: https://context7.com/terryyin/lizard/llms.txt Employ the `-Ecpre` flag to ignore code within `#else` branches when computing metrics. ```bash lizard -Ecpre src/ ``` -------------------------------- ### Set Warning Threshold for Cyclomatic Complexity Source: https://github.com/terryyin/lizard/blob/master/README.rst Set a threshold for cyclomatic complexity. Functions exceeding this limit will trigger a warning. This is equivalent to using the -C option. ```bash lizard -Tcyclomatic_complexity=10 ``` -------------------------------- ### Jenkins Integration with cppncss XML Output Source: https://context7.com/terryyin/lizard/llms.txt Generate Lizard report in XML format using `-X` and `-o lizard_report.xml`. This XML can then be consumed by Jenkins plugins like 'SLOCCount/cppncss'. ```bash # In Jenkinsfile or shell step lizard -X src/ -o lizard_report.xml # Then use the Jenkins "SLOCCount/cppncss" plugin to consume lizard_report.xml ``` -------------------------------- ### lizard.analyze_file.analyze_source_code(filename, code) Source: https://context7.com/terryyin/lizard/llms.txt Analyzes a raw source code string, using the provided filename to determine the language. ```APIDOC ### `lizard.analyze_file.analyze_source_code(filename, code)` — Analyze source code string Analyze a raw code string, providing a filename only to identify the language reader. ```python import lizard code = """ def calculate(x, y): if x > 0: return x + y elif y > 0: return y return 0 """ file_info = lizard.analyze_file.analyze_source_code("example.py", code) for func in file_info.function_list: print(f"Function: {func.name}") print(f" CCN: {func.cyclomatic_complexity}") # 3 print(f" NLOC: {func.nloc}") # 6 print(f" Parameters: {func.parameter_count}") # 2 print(f" Tokens: {func.token_count}") print(f" Long name: {func.long_name}") # 'calculate( x , y )' ``` ``` -------------------------------- ### Set parameter count limit for warnings Source: https://github.com/terryyin/lizard/blob/master/README.rst Set a limit for the number of parameters a function can have. Functions exceeding this limit will generate a warning. ```bash lizard -a 5 ``` -------------------------------- ### Ignore a specific number of warnings Source: https://github.com/terryyin/lizard/blob/master/README.rst Configure Lizard to exit normally if the number of warnings is less than or equal to 5. Otherwise, it will generate an error. ```bash lizard -i 5 ``` -------------------------------- ### Combining Condition Categories for CCN Calculation Source: https://github.com/terryyin/lizard/blob/master/ongoing/condition-categories-reference.md Python code demonstrating how the four condition categories are combined into a single set for cyclomatic complexity calculation. ```python self.conditions = ( self._control_flow_keywords | self._logical_operators | self._case_keywords | self._ternary_operators ) ``` -------------------------------- ### lizard.analyze_file(filename) Source: https://context7.com/terryyin/lizard/llms.txt Analyzes a single source file and returns a FileInformation object containing code metrics. ```APIDOC ## Python Library API ### `lizard.analyze_file(filename)` — Analyze a source file The primary entry point for programmatic use. Returns a `FileInformation` object. ```python import lizard # Analyze a file on disk file_info = lizard.analyze_file("src/main.cpp") print(file_info.filename) # 'src/main.cpp' print(file_info.nloc) # Total non-comment lines of code print(file_info.CCN) # Sum of CCN across all functions for func in file_info.function_list: print(f"{func.name}: CCN={func.cyclomatic_complexity}, " f"NLOC={func.nloc}, params={func.parameter_count}, " f"tokens={func.token_count}, length={func.length}, " f"start={func.start_line}, end={func.end_line}") # Example output: # main: CCN=3, NLOC=12, params=2, tokens=45, length=15, start=10, end=24 ``` ``` -------------------------------- ### Detect Code Duplicates with Lizard Source: https://github.com/terryyin/lizard/blob/master/README.rst Use this command to identify duplicate code sections within your project. Replace `` with the actual file or directory path. ```bash lizard -Eduplicate ``` -------------------------------- ### Set Warning Threshold for Parameter Count Source: https://github.com/terryyin/lizard/blob/master/README.rst Set a threshold for the number of parameters a function can have. Functions exceeding this limit will trigger a warning. This is equivalent to using the -a option. ```bash lizard -Tparameter_count=10 ``` -------------------------------- ### Fortran Language Condition Keywords (Case-insensitive) Source: https://github.com/terryyin/lizard/blob/master/ongoing/code-structure-reference.md Defines control flow, logical operators (including case-insensitive forms), and case keywords for Fortran, noting its case-insensitive nature. ```fortran _control_flow_keywords = {'IF', 'DO', 'if', 'do'} _logical_operators = {'.AND.', '.OR.', '.and.', '.or.'} _case_keywords = {'CASE', 'case'} _ternary_operators = set() ``` -------------------------------- ### Ignoring Warning Count with -i Source: https://context7.com/terryyin/lizard/llms.txt Allow up to N warnings before returning a non-zero exit code. Use `-i -1` to always exit cleanly, which is useful for legacy codebases in Makefiles. ```bash # Exit normally if there are 5 or fewer warnings lizard -i 5 mySource/ # Always exit 0 regardless of warnings lizard -i -1 mySource/ ``` -------------------------------- ### Analyze Source Code String with Lizard Source: https://github.com/terryyin/lizard/blob/master/README.rst Analyze code directly from a string using the Lizard Python module. A filename must be provided to help Lizard determine the language. ```python i = lizard.analyze_file.analyze_source_code("AllTests.cpp", "int foo(){}") ``` -------------------------------- ### BasePlacement Spiral Offsets Property Source: https://github.com/terryyin/lizard/blob/master/codecloud.html Static property of BasePlacement that holds the pre-calculated spiral offsets. ```javascript BasePlacement.prototype._spiralOffsets = generateSpiralOffsets(); ``` -------------------------------- ### Makefile Integration for Complexity Checks Source: https://context7.com/terryyin/lizard/llms.txt Integrate Lizard into a Makefile to enforce complexity limits. The command returns a non-zero exit code if any function exceeds the specified Cyclomatic Complexity (CCN) or length. Use `-i -1` to always pass for reporting purposes. ```makefile check-complexity: lizard -C 15 -i 0 src/ # Returns exit code 1 if any function exceeds CCN 15 # Use -i -1 to always pass (for reporting only) ``` -------------------------------- ### Generate Warnings Only Output Source: https://github.com/terryyin/lizard/blob/master/README.rst This command runs Lizard and filters the output to show only warnings, formatted in a way compatible with clang/gcc compilers. ```bash lizard -w mahjong_game ``` -------------------------------- ### Analyze File with Lizard Python Module Source: https://github.com/terryyin/lizard/blob/master/README.rst Analyze a C++ file using the Lizard Python module. This snippet shows how to import Lizard, analyze a file, and inspect the returned object's attributes, including function details. ```python import lizard i = lizard.analyze_file("../cpputest/tests/AllTests.cpp") print i.__dict__ print i.function_list[0].__dict__ ``` -------------------------------- ### R Vectorized Operations Source: https://github.com/terryyin/lizard/blob/master/ongoing/language-implementation-guide.md Handle languages like R that have both short-circuit and element-wise logical operators by including all relevant operators. ```python _logical_operators = {'&&', '||', '&', '|'} # Both types count ``` -------------------------------- ### TagCloud Class Definition Source: https://github.com/terryyin/lizard/blob/master/codecloud.html Defines the TagCloud class for rendering tag clouds. Initializes canvas dimensions, font size, and shape. Requires a canvas context. ```javascript function TagCloud(w, h, context) { "use strict"; this.ctx = context; this.canvasWidth = w; this.canvasHeight = h; this.fontSize = this.canvasHeight / 3; this.shape = "rectangle"; } ``` -------------------------------- ### Set maximum function length warning threshold Source: https://github.com/terryyin/lizard/blob/master/README.rst Set a warning threshold of 500 for maximum function length. Functions longer than this will generate a warning. ```bash lizard -L 500 ```