tywrap 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +319 -0
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +263 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/config/index.d.ts +41 -0
  8. package/dist/config/index.d.ts.map +1 -0
  9. package/dist/config/index.js +234 -0
  10. package/dist/config/index.js.map +1 -0
  11. package/dist/core/analyzer.d.ts +63 -0
  12. package/dist/core/analyzer.d.ts.map +1 -0
  13. package/dist/core/analyzer.js +676 -0
  14. package/dist/core/analyzer.js.map +1 -0
  15. package/dist/core/discovery.d.ts +85 -0
  16. package/dist/core/discovery.d.ts.map +1 -0
  17. package/dist/core/discovery.js +344 -0
  18. package/dist/core/discovery.js.map +1 -0
  19. package/dist/core/generator.d.ts +37 -0
  20. package/dist/core/generator.d.ts.map +1 -0
  21. package/dist/core/generator.js +368 -0
  22. package/dist/core/generator.js.map +1 -0
  23. package/dist/core/mapper.d.ts +40 -0
  24. package/dist/core/mapper.d.ts.map +1 -0
  25. package/dist/core/mapper.js +401 -0
  26. package/dist/core/mapper.js.map +1 -0
  27. package/dist/core/validation.d.ts +79 -0
  28. package/dist/core/validation.d.ts.map +1 -0
  29. package/dist/core/validation.js +486 -0
  30. package/dist/core/validation.js.map +1 -0
  31. package/dist/index.d.ts +26 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +29 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/runtime/base.d.ts +12 -0
  36. package/dist/runtime/base.d.ts.map +1 -0
  37. package/dist/runtime/base.js +6 -0
  38. package/dist/runtime/base.js.map +1 -0
  39. package/dist/runtime/errors.d.ts +17 -0
  40. package/dist/runtime/errors.d.ts.map +1 -0
  41. package/dist/runtime/errors.js +21 -0
  42. package/dist/runtime/errors.js.map +1 -0
  43. package/dist/runtime/http.d.ts +22 -0
  44. package/dist/runtime/http.d.ts.map +1 -0
  45. package/dist/runtime/http.js +79 -0
  46. package/dist/runtime/http.js.map +1 -0
  47. package/dist/runtime/index.d.ts +8 -0
  48. package/dist/runtime/index.d.ts.map +1 -0
  49. package/dist/runtime/index.js +17 -0
  50. package/dist/runtime/index.js.map +1 -0
  51. package/dist/runtime/node.d.ts +48 -0
  52. package/dist/runtime/node.d.ts.map +1 -0
  53. package/dist/runtime/node.js +328 -0
  54. package/dist/runtime/node.js.map +1 -0
  55. package/dist/runtime/optimized-node.d.ts +131 -0
  56. package/dist/runtime/optimized-node.d.ts.map +1 -0
  57. package/dist/runtime/optimized-node.js +622 -0
  58. package/dist/runtime/optimized-node.js.map +1 -0
  59. package/dist/runtime/protocol.d.ts +3 -0
  60. package/dist/runtime/protocol.d.ts.map +1 -0
  61. package/dist/runtime/protocol.js +3 -0
  62. package/dist/runtime/protocol.js.map +1 -0
  63. package/dist/runtime/pyodide.d.ts +27 -0
  64. package/dist/runtime/pyodide.d.ts.map +1 -0
  65. package/dist/runtime/pyodide.js +191 -0
  66. package/dist/runtime/pyodide.js.map +1 -0
  67. package/dist/tools/python_suite.js +173 -0
  68. package/dist/tools/python_suite.js.map +1 -0
  69. package/dist/types/index.d.ts +299 -0
  70. package/dist/types/index.d.ts.map +1 -0
  71. package/dist/types/index.js +5 -0
  72. package/dist/types/index.js.map +1 -0
  73. package/dist/tywrap.d.ts +29 -0
  74. package/dist/tywrap.d.ts.map +1 -0
  75. package/dist/tywrap.js +589 -0
  76. package/dist/tywrap.js.map +1 -0
  77. package/dist/utils/bundle-optimizer.d.ts +182 -0
  78. package/dist/utils/bundle-optimizer.d.ts.map +1 -0
  79. package/dist/utils/bundle-optimizer.js +680 -0
  80. package/dist/utils/bundle-optimizer.js.map +1 -0
  81. package/dist/utils/cache.d.ts +149 -0
  82. package/dist/utils/cache.d.ts.map +1 -0
  83. package/dist/utils/cache.js +492 -0
  84. package/dist/utils/cache.js.map +1 -0
  85. package/dist/utils/codec.d.ts +94 -0
  86. package/dist/utils/codec.d.ts.map +1 -0
  87. package/dist/utils/codec.js +150 -0
  88. package/dist/utils/codec.js.map +1 -0
  89. package/dist/utils/logger.d.ts +42 -0
  90. package/dist/utils/logger.d.ts.map +1 -0
  91. package/dist/utils/logger.js +140 -0
  92. package/dist/utils/logger.js.map +1 -0
  93. package/dist/utils/memory-profiler.d.ts +123 -0
  94. package/dist/utils/memory-profiler.d.ts.map +1 -0
  95. package/dist/utils/memory-profiler.js +426 -0
  96. package/dist/utils/memory-profiler.js.map +1 -0
  97. package/dist/utils/parallel-processor.d.ts +146 -0
  98. package/dist/utils/parallel-processor.d.ts.map +1 -0
  99. package/dist/utils/parallel-processor.js +636 -0
  100. package/dist/utils/parallel-processor.js.map +1 -0
  101. package/dist/utils/python.d.ts +8 -0
  102. package/dist/utils/python.d.ts.map +1 -0
  103. package/dist/utils/python.js +56 -0
  104. package/dist/utils/python.js.map +1 -0
  105. package/dist/utils/runtime.d.ts +153 -0
  106. package/dist/utils/runtime.d.ts.map +1 -0
  107. package/dist/utils/runtime.js +519 -0
  108. package/dist/utils/runtime.js.map +1 -0
  109. package/package.json +136 -0
  110. package/runtime/python_bridge.py +476 -0
  111. package/src/cli.ts +331 -0
  112. package/src/config/index.ts +289 -0
  113. package/src/core/analyzer.ts +788 -0
  114. package/src/core/discovery.ts +415 -0
  115. package/src/core/generator.ts +447 -0
  116. package/src/core/mapper.ts +504 -0
  117. package/src/core/validation.ts +693 -0
  118. package/src/index.ts +83 -0
  119. package/src/runtime/base.ts +32 -0
  120. package/src/runtime/errors.ts +19 -0
  121. package/src/runtime/http.ts +132 -0
  122. package/src/runtime/index.ts +24 -0
  123. package/src/runtime/node.ts +431 -0
  124. package/src/runtime/optimized-node.ts +838 -0
  125. package/src/runtime/protocol.ts +2 -0
  126. package/src/runtime/pyodide.ts +228 -0
  127. package/src/types/global.d.ts +60 -0
  128. package/src/types/index.ts +410 -0
  129. package/src/tywrap.ts +669 -0
  130. package/src/utils/bundle-optimizer.ts +876 -0
  131. package/src/utils/cache.ts +634 -0
  132. package/src/utils/codec.ts +275 -0
  133. package/src/utils/logger.ts +201 -0
  134. package/src/utils/memory-profiler.ts +582 -0
  135. package/src/utils/parallel-processor.ts +879 -0
  136. package/src/utils/python.ts +79 -0
  137. package/src/utils/runtime.ts +616 -0
@@ -0,0 +1,693 @@
1
+ /**
2
+ * Error Handling & Validation Framework
3
+ *
4
+ * Comprehensive error handling, syntax validation, and analysis reporting system
5
+ */
6
+
7
+ import type {
8
+ AnalysisError,
9
+ AnalysisWarning,
10
+ // AnalysisStatistics,
11
+ PythonFunction,
12
+ PythonClass,
13
+ PythonType,
14
+ } from '../types/index.js';
15
+
16
+ export interface ValidationConfig {
17
+ strictTypeChecking: boolean;
18
+ allowMissingTypeHints: boolean;
19
+ maxComplexityScore: number;
20
+ deprecatedPatterns: string[];
21
+ requiredDocstrings: boolean;
22
+ }
23
+
24
+ export interface ValidationReport {
25
+ errors: AnalysisError[];
26
+ warnings: AnalysisWarning[];
27
+ statistics: ValidationStatistics;
28
+ recommendations: ValidationRecommendation[];
29
+ }
30
+
31
+ export interface ValidationStatistics {
32
+ totalIssues: number;
33
+ errorCount: number;
34
+ warningCount: number;
35
+ typeHintCoverage: number;
36
+ docstringCoverage: number;
37
+ complexityScore: number;
38
+ qualityScore: number; // 0-100
39
+ }
40
+
41
+ export interface ValidationRecommendation {
42
+ type: 'performance' | 'maintainability' | 'type-safety' | 'documentation';
43
+ severity: 'low' | 'medium' | 'high' | 'critical';
44
+ message: string;
45
+ suggestion: string;
46
+ file?: string;
47
+ line?: number;
48
+ impact: string;
49
+ }
50
+
51
+ export class ValidationEngine {
52
+ private config: ValidationConfig;
53
+
54
+ constructor(config: Partial<ValidationConfig> = {}) {
55
+ this.config = {
56
+ strictTypeChecking: config.strictTypeChecking ?? true,
57
+ allowMissingTypeHints: config.allowMissingTypeHints ?? false,
58
+ maxComplexityScore: 10,
59
+ deprecatedPatterns: [],
60
+ requiredDocstrings: false,
61
+ ...config,
62
+ };
63
+ }
64
+
65
+ /**
66
+ * Validate Python functions for type safety and best practices
67
+ */
68
+ validateFunction(func: PythonFunction, filePath?: string): ValidationReport {
69
+ const errors: AnalysisError[] = [];
70
+ const warnings: AnalysisWarning[] = [];
71
+ const recommendations: ValidationRecommendation[] = [];
72
+
73
+ // Check type hints
74
+ this.validateTypeHints(func, errors, warnings);
75
+
76
+ // Check docstring
77
+ this.validateDocstring(func, warnings, filePath);
78
+
79
+ // Check parameter patterns
80
+ this.validateParameters(func, warnings, filePath);
81
+
82
+ // Check for deprecated patterns
83
+ this.validateDeprecatedPatterns(func, warnings, filePath);
84
+
85
+ // Check complexity
86
+ this.validateComplexity(func, warnings, filePath);
87
+
88
+ // Generate recommendations
89
+ this.generateFunctionRecommendations(func, recommendations, filePath);
90
+
91
+ const statistics = this.calculateFunctionStatistics(func, errors, warnings);
92
+
93
+ return {
94
+ errors,
95
+ warnings,
96
+ statistics,
97
+ recommendations,
98
+ };
99
+ }
100
+
101
+ /**
102
+ * Validate Python classes for structure and best practices
103
+ */
104
+ validateClass(cls: PythonClass, filePath?: string): ValidationReport {
105
+ const errors: AnalysisError[] = [];
106
+ const warnings: AnalysisWarning[] = [];
107
+ const recommendations: ValidationRecommendation[] = [];
108
+
109
+ // Validate each method
110
+ for (const method of cls.methods) {
111
+ const methodReport = this.validateFunction(method, filePath);
112
+ errors.push(...methodReport.errors);
113
+ warnings.push(...methodReport.warnings);
114
+ recommendations.push(...methodReport.recommendations);
115
+ }
116
+
117
+ // Validate class-specific patterns
118
+ this.validateClassStructure(cls, warnings, filePath);
119
+ this.validateInheritance(cls, warnings, filePath);
120
+
121
+ const statistics = this.calculateClassStatistics(cls, errors, warnings);
122
+
123
+ return {
124
+ errors,
125
+ warnings,
126
+ statistics,
127
+ recommendations,
128
+ };
129
+ }
130
+
131
+ /**
132
+ * Validate type annotations for correctness
133
+ */
134
+ validateTypeAnnotation(type: PythonType, context: string = ''): AnalysisError[] {
135
+ const errors: AnalysisError[] = [];
136
+
137
+ try {
138
+ this.validateTypeStructure(type, errors, context);
139
+ } catch (error) {
140
+ errors.push({
141
+ type: 'type',
142
+ message: `Type validation failed: ${error}`,
143
+ });
144
+ }
145
+
146
+ return errors;
147
+ }
148
+
149
+ /**
150
+ * Generate comprehensive analysis report
151
+ */
152
+ generateReport(
153
+ functions: PythonFunction[],
154
+ classes: PythonClass[],
155
+ filePath?: string
156
+ ): ValidationReport {
157
+ const errors: AnalysisError[] = [];
158
+ const warnings: AnalysisWarning[] = [];
159
+ const recommendations: ValidationRecommendation[] = [];
160
+
161
+ // Validate all functions
162
+ for (const func of functions) {
163
+ const funcReport = this.validateFunction(func, filePath);
164
+ errors.push(...funcReport.errors);
165
+ warnings.push(...funcReport.warnings);
166
+ recommendations.push(...funcReport.recommendations);
167
+ }
168
+
169
+ // Validate all classes
170
+ for (const cls of classes) {
171
+ const classReport = this.validateClass(cls, filePath);
172
+ errors.push(...classReport.errors);
173
+ warnings.push(...classReport.warnings);
174
+ recommendations.push(...classReport.recommendations);
175
+ }
176
+
177
+ // Generate module-level recommendations
178
+ this.generateModuleRecommendations(functions, classes, recommendations, filePath);
179
+
180
+ const statistics = this.calculateModuleStatistics(functions, classes, errors, warnings);
181
+
182
+ return {
183
+ errors,
184
+ warnings,
185
+ statistics,
186
+ recommendations,
187
+ };
188
+ }
189
+
190
+ /**
191
+ * Private validation methods
192
+ */
193
+ private validateTypeHints(
194
+ func: PythonFunction,
195
+ errors: AnalysisError[],
196
+ warnings: AnalysisWarning[]
197
+ ): void {
198
+ // Check return type (skip __init__ methods as they conventionally don't need return type annotations)
199
+ if (this.isEmptyType(func.returnType) && func.name !== '__init__') {
200
+ if (this.config.allowMissingTypeHints) {
201
+ warnings.push({
202
+ type: 'missing-type',
203
+ message: `Function '${func.name}' is missing return type annotation`,
204
+ });
205
+ } else if (this.config.strictTypeChecking) {
206
+ // In strict mode without allowMissingTypeHints, we warn first then error
207
+ warnings.push({
208
+ type: 'missing-type',
209
+ message: `Function '${func.name}' is missing return type annotation`,
210
+ });
211
+ errors.push({
212
+ type: 'type',
213
+ message: `Function '${func.name}' requires return type annotation`,
214
+ });
215
+ }
216
+ }
217
+
218
+ // Check parameter types (skip 'self' and 'cls' parameters)
219
+ for (const param of func.parameters) {
220
+ if (this.isEmptyType(param.type) && param.name !== 'self' && param.name !== 'cls') {
221
+ if (this.config.allowMissingTypeHints) {
222
+ warnings.push({
223
+ type: 'missing-type',
224
+ message: `Parameter '${param.name}' in function '${func.name}' is missing type annotation`,
225
+ });
226
+ } else if (this.config.strictTypeChecking) {
227
+ // In strict mode without allowMissingTypeHints, we warn first then error
228
+ warnings.push({
229
+ type: 'missing-type',
230
+ message: `Parameter '${param.name}' in function '${func.name}' is missing type annotation`,
231
+ });
232
+ errors.push({
233
+ type: 'type',
234
+ message: `Parameter '${param.name}' in function '${func.name}' requires type annotation`,
235
+ });
236
+ }
237
+ }
238
+
239
+ // Validate type structure only in strict mode (skip 'self' and 'cls' parameters)
240
+ if (
241
+ this.config.strictTypeChecking &&
242
+ !this.config.allowMissingTypeHints &&
243
+ param.name !== 'self' &&
244
+ param.name !== 'cls'
245
+ ) {
246
+ const typeErrors = this.validateTypeAnnotation(param.type, `parameter '${param.name}'`);
247
+ errors.push(...typeErrors);
248
+ }
249
+ }
250
+
251
+ // Validate return type structure only in strict mode
252
+ if (this.config.strictTypeChecking && !this.config.allowMissingTypeHints) {
253
+ const returnTypeErrors = this.validateTypeAnnotation(func.returnType, 'return type');
254
+ errors.push(...returnTypeErrors);
255
+ }
256
+ }
257
+
258
+ private validateDocstring(
259
+ func: PythonFunction,
260
+ warnings: AnalysisWarning[],
261
+ filePath?: string
262
+ ): void {
263
+ if (this.config.requiredDocstrings && !func.docstring) {
264
+ warnings.push({
265
+ type: 'missing-type',
266
+ message: `Function '${func.name}' is missing docstring`,
267
+ file: filePath,
268
+ });
269
+ }
270
+
271
+ // Check docstring quality
272
+ if (func.docstring && func.docstring.length < 10) {
273
+ warnings.push({
274
+ type: 'missing-type',
275
+ message: `Function '${func.name}' has very short docstring`,
276
+ file: filePath,
277
+ });
278
+ }
279
+ }
280
+
281
+ private validateParameters(
282
+ func: PythonFunction,
283
+ warnings: AnalysisWarning[],
284
+ filePath?: string
285
+ ): void {
286
+ // Check for too many parameters
287
+ if (func.parameters.length > 8) {
288
+ warnings.push({
289
+ type: 'performance',
290
+ message: `Function '${func.name}' has too many parameters (${func.parameters.length})`,
291
+ file: filePath,
292
+ });
293
+ }
294
+
295
+ // Check parameter naming
296
+ for (const param of func.parameters) {
297
+ if (param.name.length < 2 && !['x', 'y', 'z', 'i', 'j', 'k'].includes(param.name)) {
298
+ warnings.push({
299
+ type: 'missing-type',
300
+ message: `Parameter '${param.name}' in function '${func.name}' should have a more descriptive name`,
301
+ file: filePath,
302
+ });
303
+ }
304
+ }
305
+ }
306
+
307
+ private validateDeprecatedPatterns(
308
+ func: PythonFunction,
309
+ warnings: AnalysisWarning[],
310
+ filePath?: string
311
+ ): void {
312
+ for (const pattern of this.config.deprecatedPatterns) {
313
+ if (func.name.includes(pattern)) {
314
+ warnings.push({
315
+ type: 'deprecated',
316
+ message: `Function '${func.name}' uses deprecated pattern '${pattern}'`,
317
+ file: filePath,
318
+ });
319
+ }
320
+ }
321
+ }
322
+
323
+ private validateComplexity(
324
+ func: PythonFunction,
325
+ warnings: AnalysisWarning[],
326
+ filePath?: string
327
+ ): void {
328
+ // Simple complexity estimation based on parameters and async/generator flags
329
+ let complexity = func.parameters.length * 0.5;
330
+ if (func.isAsync) {
331
+ complexity += 1;
332
+ }
333
+ if (func.isGenerator) {
334
+ complexity += 1;
335
+ }
336
+ if (func.decorators.length > 0) {
337
+ complexity += func.decorators.length * 0.5;
338
+ }
339
+
340
+ if (complexity > this.config.maxComplexityScore) {
341
+ warnings.push({
342
+ type: 'performance',
343
+ message: `Function '${func.name}' has high complexity (${complexity.toFixed(1)})`,
344
+ file: filePath,
345
+ });
346
+ }
347
+ }
348
+
349
+ private validateClassStructure(
350
+ cls: PythonClass,
351
+ warnings: AnalysisWarning[],
352
+ filePath?: string
353
+ ): void {
354
+ // Check for empty classes
355
+ if (cls.methods.length === 0 && cls.properties.length === 0) {
356
+ warnings.push({
357
+ type: 'missing-type',
358
+ message: `Class '${cls.name}' appears to be empty`,
359
+ file: filePath,
360
+ });
361
+ }
362
+
363
+ // Check for missing __init__ method
364
+ const hasInit = cls.methods.some(method => method.name === '__init__');
365
+ if (!hasInit && cls.properties.length > 0) {
366
+ warnings.push({
367
+ type: 'missing-type',
368
+ message: `Class '${cls.name}' has properties but no __init__ method`,
369
+ file: filePath,
370
+ });
371
+ }
372
+ }
373
+
374
+ private validateInheritance(
375
+ cls: PythonClass,
376
+ warnings: AnalysisWarning[],
377
+ filePath?: string
378
+ ): void {
379
+ // Check for deep inheritance chains
380
+ if (cls.bases.length > 3) {
381
+ warnings.push({
382
+ type: 'compatibility',
383
+ message: `Class '${cls.name}' inherits from many classes (${cls.bases.length})`,
384
+ file: filePath,
385
+ });
386
+ }
387
+
388
+ // Check for diamond inheritance pattern
389
+ if (cls.bases.length > 1) {
390
+ warnings.push({
391
+ type: 'compatibility',
392
+ message: `Class '${cls.name}' uses multiple inheritance, consider composition`,
393
+ file: filePath,
394
+ });
395
+ }
396
+ }
397
+
398
+ private validateTypeStructure(type: PythonType, errors: AnalysisError[], context: string): void {
399
+ switch (type.kind) {
400
+ case 'union':
401
+ if (type.types.length < 2) {
402
+ errors.push({
403
+ type: 'type',
404
+ message: `Union type in ${context} should have at least 2 types`,
405
+ });
406
+ }
407
+ // Recursively validate union member types
408
+ for (const unionType of type.types) {
409
+ this.validateTypeStructure(unionType, errors, context);
410
+ }
411
+ break;
412
+
413
+ case 'collection':
414
+ if (type.itemTypes.length === 0 && ['list', 'dict', 'set'].includes(type.name)) {
415
+ errors.push({
416
+ type: 'type',
417
+ message: `Collection type '${type.name}' in ${context} should specify item types`,
418
+ });
419
+ }
420
+ // Recursively validate item types
421
+ for (const itemType of type.itemTypes) {
422
+ this.validateTypeStructure(itemType, errors, context);
423
+ }
424
+ break;
425
+
426
+ case 'optional':
427
+ this.validateTypeStructure(type.type, errors, context);
428
+ break;
429
+
430
+ case 'generic':
431
+ // Validate generic arguments
432
+ for (const arg of type.typeArgs) {
433
+ this.validateTypeStructure(arg, errors, context);
434
+ }
435
+ break;
436
+
437
+ case 'custom':
438
+ // Could add checks for known custom types
439
+ break;
440
+
441
+ case 'primitive':
442
+ // Basic types are always valid
443
+ break;
444
+ }
445
+ }
446
+
447
+ private isEmptyType(type: PythonType): boolean {
448
+ return type.kind === 'primitive' && type.name === 'None';
449
+ }
450
+
451
+ private generateFunctionRecommendations(
452
+ func: PythonFunction,
453
+ recommendations: ValidationRecommendation[],
454
+ filePath?: string
455
+ ): void {
456
+ // Recommend async for I/O operations
457
+ if (
458
+ (!func.isAsync && func.name.includes('read')) ||
459
+ func.name.includes('write') ||
460
+ func.name.includes('fetch')
461
+ ) {
462
+ recommendations.push({
463
+ type: 'performance',
464
+ severity: 'medium',
465
+ message: `Consider making '${func.name}' async for I/O operations`,
466
+ suggestion: `Add 'async def' instead of 'def' and use await for I/O operations`,
467
+ file: filePath,
468
+ impact: 'Improved performance for I/O-bound operations',
469
+ });
470
+ }
471
+
472
+ // Recommend type hints if missing
473
+ if (func.parameters.some(p => this.isEmptyType(p.type)) || this.isEmptyType(func.returnType)) {
474
+ recommendations.push({
475
+ type: 'type-safety',
476
+ severity: 'high',
477
+ message: `Add type hints to '${func.name}' for better IDE support`,
478
+ suggestion: 'Add type annotations to parameters and return type',
479
+ file: filePath,
480
+ impact: 'Better IDE support, type checking, and documentation',
481
+ });
482
+ }
483
+
484
+ // Recommend docstrings
485
+ if (!func.docstring) {
486
+ recommendations.push({
487
+ type: 'documentation',
488
+ severity: 'medium',
489
+ message: `Add docstring to '${func.name}'`,
490
+ suggestion: 'Add a docstring explaining the function purpose, parameters, and return value',
491
+ file: filePath,
492
+ impact: 'Better code documentation and IDE support',
493
+ });
494
+ }
495
+ }
496
+
497
+ private generateModuleRecommendations(
498
+ functions: PythonFunction[],
499
+ classes: PythonClass[],
500
+ recommendations: ValidationRecommendation[],
501
+ filePath?: string
502
+ ): void {
503
+ const totalFunctions =
504
+ functions.length + classes.reduce((acc, cls) => acc + cls.methods.length, 0);
505
+
506
+ // Recommend breaking up large modules
507
+ if (totalFunctions > 50) {
508
+ recommendations.push({
509
+ type: 'maintainability',
510
+ severity: 'medium',
511
+ message: 'Module has many functions, consider breaking it up',
512
+ suggestion: 'Split module into smaller, focused modules',
513
+ file: filePath,
514
+ impact: 'Improved maintainability and code organization',
515
+ });
516
+ }
517
+
518
+ // Check type hint coverage
519
+ const functionsWithTypes = functions.filter(
520
+ f => !this.isEmptyType(f.returnType) || f.parameters.some(p => !this.isEmptyType(p.type))
521
+ );
522
+
523
+ const typeHintCoverage =
524
+ totalFunctions > 0 ? (functionsWithTypes.length / totalFunctions) * 100 : 100;
525
+
526
+ if (typeHintCoverage < 50) {
527
+ recommendations.push({
528
+ type: 'type-safety',
529
+ severity: 'high',
530
+ message: `Low type hint coverage (${typeHintCoverage.toFixed(1)}%)`,
531
+ suggestion: 'Add type annotations to improve type safety',
532
+ file: filePath,
533
+ impact: 'Better type checking and IDE support',
534
+ });
535
+ }
536
+ }
537
+
538
+ private calculateFunctionStatistics(
539
+ func: PythonFunction,
540
+ errors: AnalysisError[],
541
+ warnings: AnalysisWarning[]
542
+ ): ValidationStatistics {
543
+ const hasTypeHints =
544
+ !this.isEmptyType(func.returnType) || func.parameters.some(p => !this.isEmptyType(p.type));
545
+
546
+ return {
547
+ totalIssues: errors.length + warnings.length,
548
+ errorCount: errors.length,
549
+ warningCount: warnings.length,
550
+ typeHintCoverage: hasTypeHints ? 100 : 0,
551
+ docstringCoverage: func.docstring ? 100 : 0,
552
+ complexityScore: this.calculateComplexity(func),
553
+ qualityScore: this.calculateQualityScore(func, errors, warnings),
554
+ };
555
+ }
556
+
557
+ private calculateClassStatistics(
558
+ cls: PythonClass,
559
+ errors: AnalysisError[],
560
+ warnings: AnalysisWarning[]
561
+ ): ValidationStatistics {
562
+ const methodsWithTypes = cls.methods.filter(
563
+ m => !this.isEmptyType(m.returnType) || m.parameters.some(p => !this.isEmptyType(p.type))
564
+ ).length;
565
+
566
+ const methodsWithDocstrings = cls.methods.filter(m => m.docstring).length;
567
+
568
+ const typeHintCoverage =
569
+ cls.methods.length > 0 ? (methodsWithTypes / cls.methods.length) * 100 : 100;
570
+ const docstringCoverage =
571
+ cls.methods.length > 0 ? (methodsWithDocstrings / cls.methods.length) * 100 : 100;
572
+
573
+ return {
574
+ totalIssues: errors.length + warnings.length,
575
+ errorCount: errors.length,
576
+ warningCount: warnings.length,
577
+ typeHintCoverage,
578
+ docstringCoverage,
579
+ complexityScore: Math.max(...cls.methods.map(m => this.calculateComplexity(m)), 0),
580
+ qualityScore: this.calculateClassQualityScore(cls, errors, warnings),
581
+ };
582
+ }
583
+
584
+ private calculateModuleStatistics(
585
+ functions: PythonFunction[],
586
+ classes: PythonClass[],
587
+ errors: AnalysisError[],
588
+ warnings: AnalysisWarning[]
589
+ ): ValidationStatistics {
590
+ const allMethods = classes.flatMap(cls => cls.methods);
591
+ const allFunctions = [...functions, ...allMethods];
592
+
593
+ const functionsWithTypes = allFunctions.filter(
594
+ f => !this.isEmptyType(f.returnType) || f.parameters.some(p => !this.isEmptyType(p.type))
595
+ ).length;
596
+
597
+ const functionsWithDocstrings = allFunctions.filter(f => f.docstring).length;
598
+
599
+ const typeHintCoverage =
600
+ allFunctions.length > 0 ? (functionsWithTypes / allFunctions.length) * 100 : 100;
601
+ const docstringCoverage =
602
+ allFunctions.length > 0 ? (functionsWithDocstrings / allFunctions.length) * 100 : 100;
603
+
604
+ return {
605
+ totalIssues: errors.length + warnings.length,
606
+ errorCount: errors.length,
607
+ warningCount: warnings.length,
608
+ typeHintCoverage,
609
+ docstringCoverage,
610
+ complexityScore: Math.max(...allFunctions.map(f => this.calculateComplexity(f)), 0),
611
+ qualityScore: this.calculateModuleQualityScore(allFunctions, errors, warnings),
612
+ };
613
+ }
614
+
615
+ private calculateComplexity(func: PythonFunction): number {
616
+ let complexity = 1; // Base complexity
617
+ complexity += func.parameters.length * 0.5;
618
+ complexity += func.isAsync ? 1 : 0;
619
+ complexity += func.isGenerator ? 1 : 0;
620
+ complexity += func.decorators.length * 0.5;
621
+ return Math.round(complexity * 10) / 10;
622
+ }
623
+
624
+ private calculateQualityScore(
625
+ func: PythonFunction,
626
+ errors: AnalysisError[],
627
+ warnings: AnalysisWarning[]
628
+ ): number {
629
+ let score = 100;
630
+
631
+ // Deduct points for errors and warnings
632
+ score -= errors.length * 20;
633
+ score -= warnings.length * 10;
634
+
635
+ // Add points for good practices
636
+ if (!this.isEmptyType(func.returnType)) {
637
+ score += 10;
638
+ }
639
+ if (func.parameters.every(p => !this.isEmptyType(p.type))) {
640
+ score += 10;
641
+ }
642
+ if (func.docstring) {
643
+ score += 10;
644
+ }
645
+
646
+ return Math.max(0, Math.min(100, score));
647
+ }
648
+
649
+ private calculateClassQualityScore(
650
+ cls: PythonClass,
651
+ errors: AnalysisError[],
652
+ warnings: AnalysisWarning[]
653
+ ): number {
654
+ let score = 100;
655
+
656
+ // Deduct points for errors and warnings
657
+ score -= errors.length * 15;
658
+ score -= warnings.length * 8;
659
+
660
+ // Add points for good practices
661
+ if (cls.docstring) {
662
+ score += 10;
663
+ }
664
+ if (cls.methods.some(m => m.name === '__init__')) {
665
+ score += 10;
666
+ }
667
+ if (cls.methods.length > 0) {
668
+ score += 5;
669
+ }
670
+
671
+ return Math.max(0, Math.min(100, score));
672
+ }
673
+
674
+ private calculateModuleQualityScore(
675
+ functions: PythonFunction[],
676
+ errors: AnalysisError[],
677
+ warnings: AnalysisWarning[]
678
+ ): number {
679
+ if (functions.length === 0) {
680
+ return 100;
681
+ }
682
+
683
+ const functionScores = functions.map(f =>
684
+ this.calculateQualityScore(
685
+ f,
686
+ errors.filter(e => e.message?.includes(f.name)),
687
+ warnings.filter(w => w.message?.includes(f.name))
688
+ )
689
+ );
690
+
691
+ return functionScores.reduce((sum, score) => sum + score, 0) / functionScores.length;
692
+ }
693
+ }