or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-analysis.mddata-models.mdextensions-system.mdindex.mdlanguage-support.mdutility-functions.md

extensions-system.mddocs/

0

# Extensions System

1

2

Extension framework for custom analysis metrics and output formats through the lizard_ext package. The system provides both built-in extensions for common analysis needs and an extensible architecture for custom extensions.

3

4

## Capabilities

5

6

### Extension Loading

7

8

Functions for loading and managing extensions during analysis.

9

10

```python { .api }

11

def get_extensions(extension_names):

12

"""

13

Loads and expands extension modules for analysis.

14

15

Args:

16

extension_names (list): List of extension names to load (e.g., ['nd', 'ns', 'wordcount'])

17

18

Returns:

19

list: List of extension objects ready for analysis

20

21

Example:

22

# Load nesting depth and nested structures extensions

23

extensions = get_extensions(['nd', 'ns'])

24

results = lizard.analyze_files(['app.py'], exts=extensions)

25

"""

26

```

27

28

### Output Formatters

29

30

Built-in formatters for generating analysis reports in various formats.

31

32

```python { .api }

33

def print_xml(results, options, _, total_factory):

34

"""

35

Formats and prints XML output in cppncss-compatible format.

36

37

Args:

38

results: Iterator of analysis results

39

options: Configuration options object

40

_: Unused parameter (for interface compatibility)

41

total_factory: Factory function for creating total results

42

43

Returns:

44

int: Exit code (0 for success)

45

"""

46

47

def print_csv(results, options, _, total_factory):

48

"""

49

Formats and prints CSV output with function metrics.

50

51

Args:

52

results: Iterator of analysis results

53

options: Configuration options object

54

_: Unused parameter

55

total_factory: Factory function for creating total results

56

57

Returns:

58

int: Exit code (0 for success)

59

"""

60

61

def print_checkstyle(results, options, _, total_factory, file=None):

62

"""

63

Formats and prints Checkstyle XML output for CI integration.

64

65

Args:

66

results: Iterator of analysis results

67

options: Configuration options object

68

_: Unused parameter

69

total_factory: Factory function for creating total results

70

file: Output file object (optional, defaults to stdout)

71

72

Returns:

73

int: Exit code (0 for success)

74

"""

75

76

def html_output(result, options, *_):

77

"""

78

Generates HTML reports using Jinja2 templates.

79

80

Args:

81

result: Analysis results object

82

options: Configuration options

83

84

Returns:

85

str: HTML report content

86

"""

87

88

def csv_output(result, options):

89

"""

90

Generates CSV format output with function metrics.

91

92

Args:

93

result: Analysis results object

94

options: Configuration options

95

96

Returns:

97

str: CSV formatted output

98

"""

99

100

def xml_output(all_result, verbose):

101

"""

102

Generates cppncss-compatible XML output.

103

104

Args:

105

all_result: Aggregated analysis results

106

verbose (bool): Include detailed function information

107

108

Returns:

109

str: XML formatted output

110

"""

111

112

def checkstyle_output(all_result, verbose):

113

"""

114

Generates Checkstyle XML format output.

115

116

Args:

117

all_result: Aggregated analysis results

118

verbose (bool): Include detailed information

119

120

Returns:

121

str: Checkstyle XML formatted output

122

"""

123

```

124

125

### File Utilities

126

127

Smart file handling utilities with encoding detection.

128

129

```python { .api }

130

def auto_open(*args, **kwargs):

131

"""

132

Smart file opening with UTF-8 BOM detection and encoding fallback.

133

134

Args:

135

*args: Arguments passed to open()

136

**kwargs: Keyword arguments passed to open()

137

138

Returns:

139

file object: Opened file with appropriate encoding

140

141

Example:

142

with auto_open('data.txt', 'r') as f:

143

content = f.read()

144

"""

145

146

def auto_read(filename):

147

"""

148

Smart file reading with fallback encoding handling.

149

150

Args:

151

filename (str): Path to file to read

152

153

Returns:

154

str: File content with detected encoding

155

156

Example:

157

content = auto_read('source_file.py')

158

print(f"File length: {len(content)} characters")

159

"""

160

```

161

162

### Analysis Extensions

163

164

Built-in extensions for specialized code analysis metrics.

165

166

#### Nesting Depth Extension

167

168

```python { .api }

169

class LizardExtension:

170

"""

171

Nesting Depth (ND) extension for analyzing maximum nesting depth.

172

173

Command-line: -N, --ND

174

Threshold: DEFAULT_ND_THRESHOLD = 7

175

176

Function Info Added:

177

max_nesting_depth: Maximum nesting depth in function

178

"""

179

```

180

181

#### Nested Structures Extension

182

183

```python { .api }

184

class LizardExtension:

185

"""

186

Nested Structures (NS) extension for counting nested control structures.

187

188

Command-line: --NS

189

Threshold: DEFAULT_NS_THRESHOLD = 3

190

191

Function Info Added:

192

max_nested_structures: Count of nested control structures

193

"""

194

```

195

196

#### Word Count Extension

197

198

```python { .api }

199

class LizardExtension:

200

"""

201

Word Count extension for generating tag clouds from code.

202

203

Command-line: -Ewordcount

204

205

Features:

206

- Counts word occurrences across codebase

207

- Generates HTML tag cloud visualization

208

- Filters common programming keywords

209

- Cross-file analysis and aggregation

210

"""

211

```

212

213

#### Duplicate Detection Extension

214

215

```python { .api }

216

class LizardExtension:

217

"""

218

Duplicate code detection extension.

219

220

Command-line: -Eduplicate

221

222

Features:

223

- Detects copy-paste code blocks

224

- Configurable similarity thresholds

225

- Hash-based duplicate identification

226

"""

227

```

228

229

### Extension Base Classes

230

231

Base classes for creating custom extensions.

232

233

```python { .api }

234

class ExtensionBase:

235

"""

236

Base class for all lizard extensions.

237

238

Methods to override:

239

__call__(self, tokens, reader): Process tokens during analysis

240

set_args(parser): Add command-line arguments

241

cross_file_process(fileinfos): Process results across multiple files

242

"""

243

```

244

245

### Available Extensions

246

247

Complete list of built-in extensions with their capabilities:

248

249

```python { .api }

250

# Core Analysis Extensions

251

class LizardExtension: # lizardnd.py

252

"""Nesting depth analysis (max_nesting_depth metric)"""

253

254

class LizardExtension: # lizardns.py

255

"""Nested structures counting (max_nested_structures metric)"""

256

257

class LizardExtension: # lizardmccabe.py

258

"""McCabe complexity metrics"""

259

260

class LizardExtension: # lizardmodified.py

261

"""Modified complexity calculations"""

262

263

# Code Quality Extensions

264

class LizardExtension: # lizardduplicate.py

265

"""Duplicate code detection and reporting"""

266

267

class LizardExtension: # lizardduplicatedparamlist.py

268

"""Duplicate parameter list detection"""

269

270

class LizardExtension: # lizardboolcount.py

271

"""Boolean complexity counting"""

272

273

class LizardExtension: # lizardcomplextags.py

274

"""Complex tag analysis"""

275

276

# Statement and Flow Extensions

277

class LizardExtension: # lizardexitcount.py

278

"""Exit/return statement counting (exit_count metric)"""

279

280

class LizardExtension: # lizardgotocount.py

281

"""Goto statement counting"""

282

283

class LizardExtension: # lizardstatementcount.py

284

"""Statement counting and analysis"""

285

286

# Language-Specific Extensions

287

class LizardExtension: # lizardcpre.py

288

"""C preprocessor directive filtering"""

289

290

class LizardExtension: # lizardignoreassert.py

291

"""Assert statement handling and filtering"""

292

293

class LizardExtension: # lizardnonstrict.py

294

"""Non-strict parsing mode"""

295

296

# Analysis and Reporting Extensions

297

class LizardExtension: # lizardwordcount.py

298

"""Word frequency analysis and tag cloud generation"""

299

300

class LizardExtension: # lizardio.py

301

"""I/O operation analysis"""

302

303

class LizardExtension: # lizarddependencycount.py

304

"""Dependency counting and analysis"""

305

306

class LizardExtension: # lizardoutside.py

307

"""External scope analysis"""

308

309

class LizardExtension: # lizarddumpcomments.py

310

"""Comment extraction and dumping"""

311

```

312

313

## Usage Examples

314

315

### Basic Extension Usage

316

317

```python

318

import lizard

319

320

# Use nesting depth extension

321

extensions = lizard.get_extensions(['nd'])

322

results = lizard.analyze(['src/'], exts=extensions)

323

324

for file_info in results:

325

for func in file_info.function_list:

326

if hasattr(func, 'max_nesting_depth'):

327

print(f"{func.name}: ND={func.max_nesting_depth}")

328

```

329

330

### Multiple Extensions

331

332

```python

333

import lizard

334

335

# Combine multiple extensions

336

extensions = lizard.get_extensions(['nd', 'ns', 'exitcount'])

337

results = lizard.analyze(['src/'], exts=extensions)

338

339

for file_info in results:

340

for func in file_info.function_list:

341

metrics = []

342

if hasattr(func, 'max_nesting_depth'):

343

metrics.append(f"ND={func.max_nesting_depth}")

344

if hasattr(func, 'max_nested_structures'):

345

metrics.append(f"NS={func.max_nested_structures}")

346

if hasattr(func, 'exit_count'):

347

metrics.append(f"Exits={func.exit_count}")

348

349

print(f"{func.name}: {', '.join(metrics)}")

350

```

351

352

### Command-Line Extension Usage

353

354

```python

355

import lizard

356

357

# Equivalent of: lizard -Ewordcount -Eduplicate -N src/

358

lizard.main(['-Ewordcount', '-Eduplicate', '-N', 'src/'])

359

360

# Multiple output formats with extensions

361

lizard.main(['-Ewordcount', '--xml', '-N', 'src/'])

362

```

363

364

### Custom Output Processing

365

366

```python

367

from lizard_ext import html_output, csv_output

368

import lizard

369

370

# Generate analysis results

371

extensions = lizard.get_extensions(['nd', 'ns'])

372

results = list(lizard.analyze(['src/'], exts=extensions))

373

374

# Create custom options object

375

class Options:

376

def __init__(self):

377

self.verbose = True

378

self.fields = ['nloc', 'ccn', 'max_nesting_depth']

379

380

options = Options()

381

382

# Generate HTML report

383

html_report = html_output(results, options)

384

with open('analysis_report.html', 'w') as f:

385

f.write(html_report)

386

387

# Generate CSV data

388

csv_data = csv_output(results, options)

389

with open('analysis_data.csv', 'w') as f:

390

f.write(csv_data)

391

```

392

393

### File Encoding Utilities

394

395

```python

396

from lizard_ext import auto_open, auto_read

397

398

# Smart file reading with encoding detection

399

try:

400

content = auto_read('source_file_with_unicode.py')

401

print(f"Successfully read {len(content)} characters")

402

except Exception as e:

403

print(f"Failed to read file: {e}")

404

405

# Smart file opening

406

with auto_open('output.txt', 'w', encoding='utf-8') as f:

407

f.write("Analysis results with unicode: 你好 world")

408

```