1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
#![cfg_attr(coverage_nightly, coverage(off))]
//! JavaScript/TypeScript language analysis.
use super::complexity::{find_brace_balanced_end, ComplexityVisitor};
use super::types::{FunctionInfo, LanguageAnalyzer};
use crate::services::complexity::ComplexityMetrics;
/// JavaScript/TypeScript analyzer
pub struct JavaScriptAnalyzer;
impl LanguageAnalyzer for JavaScriptAnalyzer {
fn extract_functions(&self, content: &str) -> Vec<FunctionInfo> {
let mut functions = Vec::new();
let lines: Vec<&str> = content.lines().collect();
// Track class context for method name qualification
let mut current_class: Option<String> = None;
let mut class_brace_depth = 0;
let mut global_brace_depth = 0;
for (line_num, line) in lines.iter().enumerate() {
let trimmed = line.trim();
// Track class declarations
if let Some(class_name) = self.extract_class_name(trimmed) {
current_class = Some(class_name);
class_brace_depth = global_brace_depth + 1;
}
// Track brace depth to know when we exit class
for ch in line.chars() {
match ch {
'{' => global_brace_depth += 1,
'}' => {
global_brace_depth -= 1;
// Exit class when we close its braces
if current_class.is_some() && global_brace_depth < class_brace_depth {
current_class = None;
}
}
_ => {}
}
}
// Detect class methods
if let Some(class_name) = ¤t_class {
if let Some(method_name) = self.extract_method_name(trimmed) {
let line_end = self.find_function_end(&lines, line_num);
let qualified_name = format!("{}::{}", class_name, method_name);
functions.push(FunctionInfo {
name: qualified_name,
line_start: line_num,
line_end,
});
continue;
}
}
// Detect regular function declarations
if self.is_function_declaration(trimmed) {
if let Some(name) = self.extract_function_name(trimmed) {
let line_end = self.find_function_end(&lines, line_num);
functions.push(FunctionInfo {
name,
line_start: line_num,
line_end,
});
}
}
}
functions
}
fn estimate_complexity(&self, content: &str, function: &FunctionInfo) -> ComplexityMetrics {
let lines: Vec<&str> = content.lines().collect();
let function_lines = &lines[function.line_start..=function.line_end];
let mut visitor = ComplexityVisitor::new();
visitor.analyze_lines(function_lines);
visitor.into_metrics()
}
}
impl JavaScriptAnalyzer {
/// Extract class name from class declaration
///
/// Detects: `class Name`, `export class Name`, `export default class Name`
fn extract_class_name(&self, line: &str) -> Option<String> {
let patterns = ["export default class ", "export class ", "class "];
for pattern in &patterns {
if let Some(pos) = line.find(pattern) {
let after = line.get(pos + pattern.len()..).unwrap_or_default();
// Extract until space or {
if let Some(end) = after.find(|c: char| c.is_whitespace() || c == '{') {
let name = after.get(..end).unwrap_or_default().trim();
if !name.is_empty() {
return Some(name.to_string());
}
}
}
}
None
}
/// Extract method name from class method declaration
///
/// Detects:
/// - Regular methods: `methodName(params) {`
/// - Async methods: `async methodName(params) {`
/// - Static methods: `static methodName(params) {`
/// - Constructors: `constructor(params) {`
/// - Getters/Setters: `get propertyName()`, `set propertyName(value)`
fn extract_method_name(&self, line: &str) -> Option<String> {
let trimmed = line.trim();
// Skip non-method lines
if trimmed.starts_with("//") || trimmed.starts_with("/*") || trimmed.starts_with('*') {
return None;
}
// Skip property declarations (e.g., `private name: string;`)
if !trimmed.contains('(') {
return None;
}
// Handle: static methodName(
if let Some(after) = trimmed.strip_prefix("static ") {
// Skip "static "
return self
.extract_simple_method_name(after)
.map(|n| format!("static {}", n));
}
// Handle: async methodName(
if let Some(after) = trimmed.strip_prefix("async ") {
// Skip "async "
return self.extract_simple_method_name(after);
}
// Handle: get propertyName() or set propertyName(value)
if let Some(after) = trimmed.strip_prefix("get ") {
return self.extract_simple_method_name(after);
}
if let Some(after) = trimmed.strip_prefix("set ") {
return self.extract_simple_method_name(after);
}
// Handle: constructor(
if trimmed.starts_with("constructor(") || trimmed.starts_with("constructor (") {
return Some("constructor".to_string());
}
// Handle: methodName( or methodName (
self.extract_simple_method_name(trimmed)
}
/// Extract simple method name from pattern: `methodName(params)`
fn extract_simple_method_name(&self, text: &str) -> Option<String> {
if let Some(paren_pos) = text.find('(') {
let before_paren = &text.get(..paren_pos).unwrap_or_default().trim();
// Extract last word before '('
if let Some(last_word_start) = before_paren.rfind(|c: char| c.is_whitespace()) {
let name = before_paren
.get(last_word_start..)
.unwrap_or_default()
.trim();
if !name.is_empty()
&& name
.chars()
.next()
.is_some_and(|c| c.is_alphabetic() || c == '_')
{
return Some(name.to_string());
}
} else if !before_paren.is_empty()
&& before_paren
.chars()
.next()
.is_some_and(|c| c.is_alphabetic() || c == '_')
{
return Some(before_paren.to_string());
}
}
None
}
fn is_function_declaration(&self, line: &str) -> bool {
line.starts_with("function ")
|| line.starts_with("async function ")
|| line.starts_with("export function ")
|| line.starts_with("export async function ")
|| line.starts_with("export default function ")
|| line.contains("= function")
|| line.contains("= async function")
|| (line.contains("const ") && line.contains(" = ("))
|| (line.contains("let ") && line.contains(" = ("))
|| (line.contains("var ") && line.contains(" = ("))
|| (line.contains("export const ") && line.contains(" = ("))
|| line.contains(" => {")
}
fn extract_function_name(&self, line: &str) -> Option<String> {
// Handle: function name(
if let Some(pos) = line.find("function ") {
let after = line.get(pos + 9..).unwrap_or_default();
if let Some(paren_pos) = after.find('(') {
let name = after.get(..paren_pos).unwrap_or_default().trim();
if !name.is_empty() {
return Some(name.to_string());
}
}
}
// Handle: const/let/var name =
for keyword in &["const ", "let ", "var "] {
if let Some(pos) = line.find(keyword) {
let after = line.get(pos + keyword.len()..).unwrap_or_default();
if let Some(eq_pos) = after.find(" = ") {
let name = after.get(..eq_pos).unwrap_or_default().trim();
return Some(name.to_string());
}
}
}
// For anonymous functions, use generic name
Some("anonymous_fn".to_string())
}
fn find_function_end(&self, lines: &[&str], start: usize) -> usize {
find_brace_balanced_end(lines, start, false)
}
}
#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
use super::*;
/// RED TEST (PMAT-BUG-001): TypeScript/JavaScript class methods must be extracted
///
/// **BUG**: JavaScriptAnalyzer uses regex/heuristic parsing that ONLY detects:
/// - `function name()` declarations
/// - Arrow functions `const x = () => {}`
/// - Variable assignments to functions
///
/// But it does NOT detect:
/// - Class methods (e.g., `add(a, b) { ... }` inside a class)
/// - Constructors (e.g., `constructor() { ... }`)
/// - Static methods (e.g., `static create() { ... }`)
///
/// **ROOT CAUSE**: CLI uses `JavaScriptAnalyzer` (heuristics) instead of
/// `EnhancedTypeScriptVisitor` (full AST analysis).
///
/// **EXPECTED**: After fix, this test must PASS.
/// **ACTUAL**: Currently FAILS because class methods return empty `[]`.
///
/// **FIX STRATEGY**:
/// 1. Modify `JavaScriptAnalyzer::extract_functions()` to detect class methods
/// 2. Add regex patterns for: `methodName(params)`, `constructor(params)`, `static methodName(params)`
/// 3. Track class context using brace counting
/// 4. Qualify method names with class name (e.g., `Calculator::add`)
///
/// **Quality Gate**: This test must pass before v2.162.0 release.
#[test]
fn red_test_typescript_class_methods_must_be_extracted() {
let analyzer = JavaScriptAnalyzer;
let content = r#"
export class Calculator {
add(a: number, b: number): number {
return a + b;
}
divide(a: number, b: number): number {
if (b === 0) {
throw new Error("Division by zero");
}
return a / b;
}
constructor(private name: string) {}
}
"#;
let functions = analyzer.extract_functions(content);
// RED: This assertion WILL FAIL until the fix is implemented
assert!(
functions.len() >= 3,
"PMAT-BUG-001: JavaScriptAnalyzer must extract class methods. \
Expected >=3 (add, divide, constructor), found {}. \
Functions: {:?}",
functions.len(),
functions.iter().map(|f| &f.name).collect::<Vec<_>>()
);
// Verify specific method names are detected
let method_names: Vec<&str> = functions.iter().map(|f| f.name.as_str()).collect();
assert!(
method_names.iter().any(|n| n.contains("add")),
"Must detect 'add' method"
);
assert!(
method_names.iter().any(|n| n.contains("divide")),
"Must detect 'divide' method"
);
assert!(
method_names.iter().any(|n| n.contains("constructor")),
"Must detect 'constructor' method"
);
}
/// RED TEST (PMAT-BUG-001): JavaScript class methods must be extracted
///
/// Same bug affects JavaScript ES6 classes. This test validates plain JavaScript
/// class syntax without TypeScript types.
///
/// **Quality Gate**: Must pass before v2.162.0 release.
#[test]
fn red_test_javascript_class_methods_must_be_extracted() {
let analyzer = JavaScriptAnalyzer;
let content = r#"
class Server {
constructor(port) {
this.port = port;
}
start() {
console.log(`Starting on port ${this.port}`);
}
stop() {
console.log('Stopping server');
}
static create(port) {
return new Server(port);
}
}
"#;
let functions = analyzer.extract_functions(content);
// RED: This assertion WILL FAIL until the fix is implemented
assert!(
functions.len() >= 4,
"PMAT-BUG-001: JavaScriptAnalyzer must extract class methods. \
Expected >=4 (constructor, start, stop, static create), found {}. \
Functions: {:?}",
functions.len(),
functions.iter().map(|f| &f.name).collect::<Vec<_>>()
);
// Verify specific method names
let method_names: Vec<&str> = functions.iter().map(|f| f.name.as_str()).collect();
assert!(
method_names.iter().any(|n| n.contains("constructor")),
"Must detect 'constructor'"
);
assert!(
method_names.iter().any(|n| n.contains("start")),
"Must detect 'start' method"
);
assert!(
method_names.iter().any(|n| n.contains("stop")),
"Must detect 'stop' method"
);
assert!(
method_names.iter().any(|n| n.contains("create")),
"Must detect static 'create' method"
);
}
}
include!("javascript_property_tests.rs");