code-gauge 3.1.0 → 4.0.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.
- package/README.md +16 -15
- package/dist/crossFileDuplication.cjs +1 -1
- package/dist/crossFileDuplication.cjs.map +1 -1
- package/dist/crossFileDuplication.js +1 -1
- package/dist/crossFileDuplication.js.map +1 -1
- package/dist/diffCommand.cjs +1 -1
- package/dist/diffCommand.cjs.map +1 -1
- package/dist/diffCommand.js +1 -1
- package/dist/diffCommand.js.map +1 -1
- package/dist/duplication.cjs +1 -1
- package/dist/duplication.cjs.map +1 -1
- package/dist/duplication.d.ts +14 -28
- package/dist/duplication.js +1 -1
- package/dist/duplication.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.js +1 -1
- package/dist/languages.cjs +1 -1
- package/dist/languages.cjs.map +1 -1
- package/dist/languages.d.ts +5 -0
- package/dist/languages.js +1 -1
- package/dist/languages.js.map +1 -1
- package/dist/metrics.cjs +1 -1
- package/dist/metrics.cjs.map +1 -1
- package/dist/metrics.d.ts +14 -12
- package/dist/metrics.js +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/nativeMetrics.cjs +3 -1
- package/dist/nativeMetrics.cjs.map +1 -1
- package/dist/nativeMetrics.d.ts +24 -9
- package/dist/nativeMetrics.js +3 -1
- package/dist/nativeMetrics.js.map +1 -1
- package/dist/scan.cjs +1 -1
- package/dist/scan.cjs.map +1 -1
- package/dist/scan.js +1 -1
- package/dist/scan.js.map +1 -1
- package/dist/types.d.ts +5 -13
- package/native/Cargo.lock +523 -0
- package/native/Cargo.toml +45 -0
- package/native/build.rs +3 -0
- package/native/src/complexity.rs +627 -0
- package/native/src/dep_degree.rs +253 -0
- package/native/src/duplication.rs +2007 -0
- package/native/src/functions.rs +345 -0
- package/native/src/languages.rs +647 -0
- package/native/src/lib.rs +101 -0
- package/native/src/measure.rs +590 -0
- package/native/src/ncss.rs +263 -0
- package/native/src/types.rs +135 -0
- package/native/src/util.rs +139 -0
- package/package.json +16 -19
- package/scripts/buildNative.mjs +25 -0
- package/scripts/installNative.mjs +96 -0
- package/dist/depDegree.cjs +0 -2
- package/dist/depDegree.cjs.map +0 -1
- package/dist/depDegree.d.ts +0 -12
- package/dist/depDegree.js +0 -2
- package/dist/depDegree.js.map +0 -1
- package/dist/ncss.cjs +0 -2
- package/dist/ncss.cjs.map +0 -1
- package/dist/ncss.d.ts +0 -17
- package/dist/ncss.js +0 -2
- package/dist/ncss.js.map +0 -1
package/dist/metrics.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metrics.cjs","names":["createLanguageRegistry","measureWithNativeBackend","countNcss","measureDuplication","collectCrossFileDuplicateCandidates","Parser","defaultDuplicationOptions","measureDepDegree","getNcssSets","ncssContribution","commentNodeTypes","hashText"],"sources":["../src/metrics.ts"],"sourcesContent":["import Parser from 'tree-sitter';\nimport { measureDepDegree } from './depDegree.js';\nimport {\n collectCrossFileDuplicateCandidates,\n defaultDuplicationOptions,\n hashText,\n measureDuplication,\n type CrossFileDuplicateCandidate,\n type CrossFileDuplicationFileData,\n} from './duplication.js';\nimport { createLanguageRegistry } from './languages.js';\nimport { commentNodeTypes, countNcss, getNcssSets, invalidateNcssSetsCache, ncssContribution } from './ncss.js';\nimport { measureWithNativeBackend, type NativeHalsteadCounts, type NativeMetricsPayload } from './nativeMetrics.js';\nimport type {\n CodeMetrics,\n FunctionMetrics,\n HalsteadMetrics,\n LanguageDefinition,\n LanguageName,\n MeasureOptions,\n} from './types.js';\n\nconst booleanOperators = new Set(['&&', '||', 'and', 'or']);\nconst operatorTexts = new Set([\n '+',\n '-',\n '*',\n '/',\n '%',\n '**',\n '=',\n '+=',\n '-=',\n '*=',\n '/=',\n '%=',\n '==',\n '!=',\n '===',\n '!==',\n '<',\n '<=',\n '>',\n '>=',\n '!',\n '~',\n '&',\n '|',\n '^',\n '++',\n '--',\n '<<',\n '>>',\n '>>>',\n '=>',\n '**=',\n '<<=',\n '>>=',\n '>>>=',\n '&=',\n '|=',\n '^=',\n '&&=',\n '||=',\n '??=',\n '??',\n '?.',\n '?',\n '//',\n '//=',\n '@',\n '@=',\n ':=',\n '<-',\n '<=>',\n '=~',\n '..',\n '...',\n '..=',\n '&&',\n '||',\n '!~',\n '&^',\n '&^=',\n '&.',\n // Member access/qualification are classical Halstead operators (floats and range/spread tokens\n // are distinct leaves, so `.` cannot collide with them). `->` also captures Python/Rust\n // return-type arrows, consistent with the counted `=>`.\n '.',\n '->',\n '::',\n '->*',\n '.*',\n 'sizeof',\n 'alignof',\n 'defined?',\n 'as',\n // C++ alternative operator tokens parse as anonymous leaves like their symbolic forms.\n 'bitand',\n 'bitor',\n 'xor',\n 'compl',\n 'and_eq',\n 'or_eq',\n 'xor_eq',\n 'not_eq',\n 'and',\n 'or',\n 'not',\n 'in',\n 'is',\n 'instanceof',\n 'typeof',\n 'new',\n 'delete',\n 'return',\n 'throw',\n 'raise',\n 'yield',\n 'await',\n 'co_await',\n 'co_yield',\n 'co_return',\n 'break',\n 'continue',\n]);\n\nconst operandNodeTypes = new Set([\n 'identifier',\n 'property_identifier',\n 'field_identifier',\n 'type_identifier',\n 'constant',\n 'instance_variable',\n 'class_variable',\n 'global_variable',\n 'simple_symbol',\n 'self',\n 'this',\n 'super',\n // C/C++/Rust built-in types are leaves of their own node type, unlike Go's `type_identifier`.\n 'primitive_type',\n 'boolean_type',\n 'void_type',\n 'auto',\n 'number',\n 'integer',\n 'float',\n 'integer_literal',\n 'float_literal',\n 'int_literal',\n 'rune_literal',\n 'imaginary_literal',\n 'number_literal',\n 'decimal_integer_literal',\n 'hex_integer_literal',\n 'octal_integer_literal',\n 'binary_integer_literal',\n 'decimal_floating_point_literal',\n 'hex_floating_point_literal',\n 'string',\n 'string_literal',\n // Go raw strings are leaves with no content child, unlike Rust/C++ `raw_string_literal`s.\n 'raw_string_literal',\n 'string_fragment',\n 'multiline_string_fragment',\n 'string_content',\n 'raw_string_content',\n 'template_string',\n 'character_literal',\n 'char_literal',\n 'character',\n 'true',\n 'false',\n 'null',\n 'null_literal',\n 'undefined',\n 'nil',\n 'none',\n]);\n\n/**\n * Non-leaf literals counted as one Halstead operand without descending: Go interpreted strings\n * have no content leaf at all, and regex literals would otherwise count their `/` delimiters as\n * division operators. Interpolated regex contents are deliberately swallowed by the atom.\n */\n// C++ user-defined literals (`42_km`) are atomic too, keeping their suffix in the operand identity,\n// and multi-token built-in types (Java `int`, C `unsigned long`) wrap anonymous keyword leaves so\n// they count as one operand.\nconst atomicOperandNodeTypes = new Set([\n 'interpreted_string_literal',\n 'regex',\n 'user_defined_literal',\n 'integral_type',\n 'floating_point_type',\n 'sized_type_specifier',\n 'placeholder_type_specifier',\n]);\n\ninterface ComplexityResult {\n cognitiveComplexity: number;\n nestingDepth: number;\n}\n\ninterface CommentSpan {\n line: number;\n startColumn: number;\n endColumn: number;\n}\n\nexport class TreeMeasurer {\n private readonly registry = createLanguageRegistry();\n\n registerLanguage(language: LanguageDefinition): void {\n // Re-registering may carry mutated node-type arrays; drop derived caches so they rebuild.\n invalidateComplexityNodeSetsCache(language);\n invalidateNcssSetsCache(language);\n this.registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n this.registry.set(alias, language);\n }\n }\n\n getSupportedLanguages(): LanguageName[] {\n return [...new Set([...this.registry.values()].map((language) => language.name))];\n }\n\n measure(code: string, options: MeasureOptions): CodeMetrics {\n const language = this.registry.get(options.language);\n if (!language) {\n throw new Error(`Unsupported language: ${options.language}`);\n }\n\n // The native backend implements only the default duplication settings, so custom settings\n // measure through the TypeScript backend instead of silently ignoring them.\n const nativePayload = usesDefaultDuplicationOptions(options)\n ? measureWithNativeBackend(code, language, options.includeSyntaxTree ?? false)\n : undefined;\n if (nativePayload) {\n return assembleNativeMetrics(nativePayload, options.includeSyntaxTree ?? false);\n }\n\n const root = parseRoot(code, language);\n const functions = collectNodes(root, new Set(language.functionNodeTypes)).filter(\n (node) => !isLambdaBodyBlock(node) && isImplementedFunction(node)\n );\n const functionMetrics = collectFunctionMetrics(root, functions, language, code);\n const globalComplexity = measureComplexity(root, language);\n const { lines, codeLineNumbers } = classifyLines(code, root);\n\n return {\n language: language.name,\n bytes: Buffer.byteLength(code),\n lines,\n functions: functionMetrics,\n cognitiveComplexity: globalComplexity.cognitiveComplexity,\n maxCognitiveComplexity: maxCognitiveComplexity(functionMetrics),\n nestingDepth: globalComplexity.nestingDepth,\n ncssCount: countNcss(root, language),\n duplication: measureDuplication(root, codeLineNumbers, options.duplication),\n halstead: measureHalstead(root, code),\n syntaxTree: options.includeSyntaxTree ? root.toString() : undefined,\n };\n }\n\n /** Collects one file's duplicate candidates for cross-file clone detection. */\n collectDuplicationCandidates(code: string, options: MeasureOptions): CrossFileDuplicateCandidate[] {\n return this.collectCrossFileDuplicationFileData(code, options).candidates;\n }\n\n /**\n * Normalized token hash sequences of every function, index-parallel to the functions array of\n * measure(): identifiers are anonymized by first occurrence within the function, literals by\n * kind, and keywords/operators kept verbatim, so the regression gate can re-match renamed or\n * moved functions across two revisions by token-LCS similarity. Always measured by the\n * TypeScript backend.\n */\n collectFunctionTokenSequences(code: string, options: MeasureOptions): Int32Array[] {\n const { language, root } = this.parse(code, options);\n const functions = collectNodes(root, new Set(language.functionNodeTypes)).filter(\n (node) => !isLambdaBodyBlock(node) && isImplementedFunction(node)\n );\n return functions.map((node) => tokenizeFunction(node));\n }\n\n /**\n * Collects one file's duplicate candidates, normalized tokens, and statement structure for\n * cross-file clone detection with measureCrossFileDuplication. Always measured by the\n * TypeScript backend.\n */\n collectCrossFileDuplicationFileData(code: string, options: MeasureOptions): CrossFileDuplicationFileData {\n const { root } = this.parse(code, options);\n return {\n ...collectCrossFileDuplicateCandidates(root, options.duplication),\n // Lets cross-file line coverage count only code lines, like within-file coverage.\n codeLineNumbers: classifyLines(code, root).codeLineNumbers,\n };\n }\n\n private parse(code: string, options: MeasureOptions): { language: LanguageDefinition; root: Parser.SyntaxNode } {\n const language = this.registry.get(options.language);\n if (!language) {\n throw new Error(`Unsupported language: ${options.language}`);\n }\n return { language, root: parseRoot(code, language) };\n }\n}\n\nfunction parseRoot(code: string, language: LanguageDefinition): Parser.SyntaxNode {\n const parser = new Parser();\n parser.setLanguage(language.parserLanguage);\n return parser.parse(code, undefined, { bufferSize: code.length + 1 }).rootNode;\n}\n\nfunction usesDefaultDuplicationOptions(options: MeasureOptions): boolean {\n const duplication = options.duplication;\n return (\n (duplication?.minTokens ?? defaultDuplicationOptions.minTokens) === defaultDuplicationOptions.minTokens &&\n (duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens) === defaultDuplicationOptions.maxGapTokens &&\n (duplication?.minSimilarityPercent ?? defaultDuplicationOptions.minSimilarityPercent) ===\n defaultDuplicationOptions.minSimilarityPercent\n );\n}\n\nexport const defaultMeasurer = new TreeMeasurer();\n\nexport function measureCode(code: string, options: MeasureOptions): CodeMetrics {\n return defaultMeasurer.measure(code, options);\n}\n\n/** Standalone helper mirroring measureCode for the default measurer. */\nexport function collectDuplicationCandidates(code: string, options: MeasureOptions): CrossFileDuplicateCandidate[] {\n return defaultMeasurer.collectDuplicationCandidates(code, options);\n}\n\n/** Standalone helper mirroring measureCode for the default measurer. */\nexport function collectFunctionTokenSequences(code: string, options: MeasureOptions): Int32Array[] {\n return defaultMeasurer.collectFunctionTokenSequences(code, options);\n}\n\n/** Standalone helper mirroring measureCode for the default measurer. */\nexport function collectCrossFileDuplicationFileData(\n code: string,\n options: MeasureOptions\n): CrossFileDuplicationFileData {\n return defaultMeasurer.collectCrossFileDuplicationFileData(code, options);\n}\n\n/**\n * Completes a native measurement into CodeMetrics. The object is rebuilt field by field (rather\n * than spread from the parsed JSON) so the result has exactly the shape the TypeScript backend\n * produces, including explicitly-undefined optional keys.\n */\nfunction assembleNativeMetrics(payload: NativeMetricsPayload, includeSyntaxTree: boolean): CodeMetrics {\n return {\n language: payload.language,\n bytes: payload.bytes,\n lines: payload.lines,\n functions: payload.functions.map((fn) => ({\n name: fn.name,\n nodeType: fn.nodeType,\n startLine: fn.startLine,\n startColumn: fn.startColumn,\n endLine: fn.endLine,\n cognitiveComplexity: fn.cognitiveComplexity,\n nestingDepth: fn.nestingDepth,\n ncss: fn.ncss,\n parameterCount: fn.parameterCount,\n halstead: deriveHalsteadMetrics(fn.halsteadCounts),\n depDegree: fn.depDegree,\n })),\n cognitiveComplexity: payload.cognitiveComplexity,\n maxCognitiveComplexity: payload.maxCognitiveComplexity,\n nestingDepth: payload.nestingDepth,\n ncssCount: payload.ncssCount,\n duplication: payload.duplication,\n halstead: deriveHalsteadMetrics(payload.halsteadCounts),\n syntaxTree: includeSyntaxTree ? payload.syntaxTree : undefined,\n };\n}\n\nfunction collectFunctionMetrics(\n root: Parser.SyntaxNode,\n functions: Parser.SyntaxNode[],\n language: LanguageDefinition,\n code: string\n): FunctionMetrics[] {\n const bodyMetricsByNodeId = measureFunctionBodyMetrics(root, language);\n const { functionNodes } = getComplexityNodeSets(language);\n return functions.map((node) => {\n const bodyMetrics = bodyMetricsByNodeId.get(node.id);\n if (!bodyMetrics) {\n throw new Error(`missing body metrics for function node at line ${node.startPosition.row + 1}`);\n }\n return {\n name: findFunctionName(node),\n nodeType: node.type,\n startLine: node.startPosition.row + 1,\n startColumn: node.startPosition.column,\n endLine: node.endPosition.row + 1,\n cognitiveComplexity: bodyMetrics.cognitiveComplexity,\n nestingDepth: bodyMetrics.nestingDepth,\n ncss: bodyMetrics.ncss,\n parameterCount: countParameters(node),\n halstead: measureHalstead(node, code),\n depDegree: measureDepDegree(node, (nested) => isFunctionBoundary(nested, functionNodes)),\n };\n });\n}\n\n/** Counts declared parameters of a function/method, ignoring punctuation and comments. */\nfunction countParameters(node: Parser.SyntaxNode): number {\n // An unparenthesized arrow-function parameter (`x => x + 1`) is a bare `parameter` field.\n if (node.childForFieldName('parameter')) {\n return 1;\n }\n\n const parametersNode = findParametersNode(node);\n if (!parametersNode) {\n return 0;\n }\n\n // A Java bare lambda parameter (`x -> x + 1`) puts a lone identifier in the `parameters` field.\n if (parametersNode.type === 'identifier') {\n return 1;\n }\n\n // Ruby block-locals after `;` (`{ |x; memo| ... }`) occupy `locals` fields and receive no arguments.\n const blockLocalIds = new Set(findChildrenByFieldName(parametersNode, 'locals').map((child) => child.id));\n // Rust's `self` and Java's explicit receiver (`void f(X this)`) are not declared parameters, and\n // C/C++ `f(void)` declares none. A Ruby block parameter (`&blk`) binds the block, which call\n // sites pass outside the argument list, so it counts toward no arity.\n let count = 0;\n for (const child of parametersNode.namedChildren) {\n if (\n child.type === 'comment' ||\n child.type === 'self_parameter' ||\n child.type === 'receiver_parameter' ||\n child.type === 'block_parameter' ||\n // Python's PEP 570/3102 markers (`/`, `*`) separate parameter kinds but bind nothing.\n child.type === 'positional_separator' ||\n child.type === 'keyword_separator' ||\n blockLocalIds.has(child.id) ||\n isVoidParameter(child)\n ) {\n continue;\n }\n // Go declares several names per declaration (`a, b int`); each name is a parameter.\n count += child.type === 'parameter_declaration' ? Math.max(1, findChildrenByFieldName(child, 'name').length) : 1;\n }\n // C++ C-style varargs (`int f(int a, ...)`) leave `...` as an anonymous token, unlike C's named\n // `variadic_parameter`.\n const anonymousVariadicCount = parametersNode.children.filter(\n (child) => !child.isNamed && child.text === '...'\n ).length;\n return count + anonymousVariadicCount;\n}\n\n/** C/C++ `int f(void)` has a `parameter_declaration` whose type is a bare `void` with no declarator. */\nfunction isVoidParameter(node: Parser.SyntaxNode): boolean {\n return (\n node.type === 'parameter_declaration' &&\n node.childForFieldName('declarator') === null &&\n node.childForFieldName('type')?.text === 'void'\n );\n}\n\nfunction findParametersNode(node: Parser.SyntaxNode): Parser.SyntaxNode | undefined {\n const direct = node.childForFieldName('parameters');\n if (direct) {\n return direct;\n }\n\n // A Java compact constructor implicitly takes the record's components, declared on the\n // `record_declaration` two levels up (via `class_body`).\n if (node.type === 'compact_constructor_declaration') {\n return node.parent?.parent?.childForFieldName('parameters') ?? undefined;\n }\n\n // C/C++ parameters hang off the (possibly pointer/reference-wrapped) declarator, not the\n // definition itself.\n let declarator: Parser.SyntaxNode | null | undefined = node.childForFieldName('declarator');\n while (declarator) {\n const parameters = declarator.childForFieldName('parameters');\n if (parameters) {\n return parameters;\n }\n declarator = nextDeclarator(declarator);\n }\n\n return node.namedChildren.find((child) => child.type === 'formal_parameters' || child.type === 'parameter_list');\n}\n\n/**\n * C++ `function_definition` also covers pure-virtual/`= default`/`= delete` members; those have no\n * `body` and are signatures, not implementations, matching how TypeScript method signatures are\n * excluded. Java `method_declaration` is NOT here: PMD reports abstract/interface methods as\n * methods (NCSS 1), so bodyless Java methods stay in the function list.\n */\nconst bodyRequiredFunctionTypes = new Set([\n 'function_definition',\n 'constructor_declaration',\n 'compact_constructor_declaration',\n // Rust trait method signatures (`fn required(&self);`) never carry a body.\n 'function_signature_item',\n]);\n\nfunction isImplementedFunction(node: Parser.SyntaxNode): boolean {\n if (!bodyRequiredFunctionTypes.has(node.type) || node.childForFieldName('body') !== null) {\n return true;\n }\n\n // C++ constructor/destructor function-try-blocks carry their `try_statement` outside the\n // `body` field; they are implementations, unlike `= 0`/`= default`/`= delete` members.\n return node.namedChildren.some((child) => child.type === 'try_statement');\n}\n\n/**\n * A Ruby stabby lambda (`->(x) { ... }`) wraps its body in a `block`/`do_block`, which is itself a\n * function node type; the wrapper is part of the lambda, not a separate function, so it must not\n * count as one or act as a nested-function boundary.\n */\nfunction isLambdaBodyBlock(node: Parser.SyntaxNode): boolean {\n return (node.type === 'block' || node.type === 'do_block') && node.parent?.type === 'lambda';\n}\n\nfunction isFunctionBoundary(node: Parser.SyntaxNode, functionNodeTypes: Set<string>): boolean {\n return functionNodeTypes.has(node.type) && !isLambdaBodyBlock(node);\n}\n\n// Sonar cognitive complexity charges a switch/match once as a whole, not per case label. Only\n// named nodes are consulted, so anonymous keyword tokens never match.\nconst switchLikeNodeTypes = new Set([\n 'switch_statement',\n 'switch_expression',\n 'expression_switch_statement',\n 'type_switch_statement',\n 'select_statement',\n 'match_expression',\n 'match_statement',\n 'case',\n 'case_match',\n]);\n\n// Per-case decision nodes add no cognitive point because the switch itself carries the cost.\nconst caseClauseNodeTypes = new Set([\n 'case_clause',\n 'switch_case',\n 'switch_block_statement_group',\n 'switch_rule',\n 'case_statement',\n 'expression_case',\n 'type_case',\n 'communication_case',\n 'match_arm',\n 'when',\n 'in_clause',\n]);\n\nconst ifLikeNodeTypes = new Set(['if_statement', 'if_expression', 'if', 'unless']);\n\ninterface ComplexityNodeSets {\n functionNodes: Set<string>;\n decisionNodes: Set<string>;\n nestingNodes: Set<string>;\n}\n\n// Cached per language: measureComplexity runs once per function plus once per file, so per-call\n// Set construction would add a measurable constant factor on large files.\nconst complexityNodeSetsCache = new WeakMap<LanguageDefinition, ComplexityNodeSets>();\n\n/** Drops the cached sets so a re-registered (possibly mutated) definition rebuilds them. */\nfunction invalidateComplexityNodeSetsCache(language: LanguageDefinition): void {\n complexityNodeSetsCache.delete(language);\n}\n\nfunction getComplexityNodeSets(language: LanguageDefinition): ComplexityNodeSets {\n let sets = complexityNodeSetsCache.get(language);\n if (!sets) {\n sets = {\n functionNodes: new Set(language.functionNodeTypes),\n decisionNodes: new Set(language.decisionNodeTypes),\n nestingNodes: new Set(language.nestingNodeTypes),\n };\n complexityNodeSetsCache.set(language, sets);\n }\n return sets;\n}\n\ninterface FunctionBodyMetrics {\n cognitiveComplexity: number;\n nestingDepth: number;\n ncss: number;\n}\n\n/** Accumulator for one function body during measureFunctionBodyMetrics' post-order pass. */\ninterface FunctionBodyFrame {\n cognitiveComplexity: number;\n /** Count of `1 + nesting` cognitive increments, for re-basing on hoist into the parent frame. */\n nestingSensitiveCount: number;\n nestingDepth: number;\n ncss: number;\n hasOwnNcssContribution: boolean;\n /** Cognitive nesting (structural nesting + function/class bonuses) carried into this body. */\n entryCognitiveNesting: number;\n /** Structural nesting carried into this body (bonuses excluded), for nesting depth. */\n entryStructuralNesting: number;\n}\n\nfunction createFrame(entryCognitiveNesting: number, entryStructuralNesting: number): FunctionBodyFrame {\n return {\n cognitiveComplexity: 0,\n nestingSensitiveCount: 0,\n nestingDepth: 0,\n ncss: 0,\n hasOwnNcssContribution: false,\n entryCognitiveNesting,\n entryStructuralNesting,\n };\n}\n\n/**\n * Per-function complexity and NCSS for every function boundary, in one post-order pass so each\n * node is visited once instead of once per enclosing function (issue #35). A function's metrics\n * are its own-body contributions plus, per directly nested function, that function's\n * already-computed totals: NCSS hoists as-is; cognitive complexity re-bases the nested function's\n * nesting-sensitive increments (each worth `1 + nesting`) by the nesting offset at the embedding\n * site, while flat increments (else branches, boolean-operator sequences, chain continuations,\n * jumps, guards) hoist unchanged; nesting depth describes the own body only, so it does not hoist.\n */\nfunction measureFunctionBodyMetrics(\n root: Parser.SyntaxNode,\n language: LanguageDefinition\n): Map<number, FunctionBodyMetrics> {\n const { functionNodes, decisionNodes, nestingNodes } = getComplexityNodeSets(language);\n const { countable, containers } = getNcssSets(language);\n const results = new Map<number, FunctionBodyMetrics>();\n // frames[0] is a sentinel for top-level code; its accumulation is discarded.\n const frames: FunctionBodyFrame[] = [createFrame(0, 0)];\n\n function visit(\n current: Parser.SyntaxNode,\n currentNesting: number,\n functionNestingBonus: number,\n insideFunction: boolean,\n insideNestedRegion: boolean,\n insideChargedClassBody: boolean\n ): void {\n // A class body nested in a function (anonymous/local classes) raises the cognitive nesting\n // level once for everything inside it — PMD charges the class body, not the methods it holds\n // (verified: an anonymous-class instance initializer's `if` costs 1 + 1 nesting), so methods\n // directly inside a charged class body skip the function-boundary bonus.\n const isChargedClassBody = current.type === 'class_body' && insideFunction;\n if (isChargedClassBody) {\n insideNestedRegion = true;\n functionNestingBonus += 1;\n }\n const opensFrame = isFunctionBoundary(current, functionNodes);\n if (opensFrame) {\n if (insideFunction && !insideChargedClassBody) {\n functionNestingBonus += 1;\n }\n insideFunction = true;\n }\n // The node's own increments target the frame it is embedded in, not the one it opens; a\n // frame-opening or charged-class-body node contributes nothing to that frame's own body\n // (nesting), matching the per-function traversal this pass replaces.\n const frame = frames.at(-1) as FunctionBodyFrame;\n const relativeNesting = currentNesting + functionNestingBonus - frame.entryCognitiveNesting;\n const countsForOwnBody = !insideNestedRegion && !opensFrame;\n\n // Anonymous keyword tokens can share a type with named nodes (Ruby's `if` node contains an\n // `if` keyword token), so only named nodes count as decisions.\n const isDecision = current.isNamed && decisionNodes.has(current.type) && !isDefaultSwitchBranch(current);\n const isCaseClause = current.isNamed && caseClauseNodeTypes.has(current.type);\n // Ruby's `case ... else` arm is an `else` node; like every other language's default branch it\n // nests its contents inside the switch (it cannot go in the Ruby nesting set because\n // `if`/`begin` else branches would then double-nest under their already-nesting parent).\n const isNesting =\n current.isNamed &&\n (nestingNodes.has(current.type) ||\n (current.type === 'else' && (current.parent?.type === 'case' || current.parent?.type === 'case_match')));\n // `elsif`/`elif`/`else if` continue a flat chain: they add a decision without a nesting\n // surcharge, and their bodies stay at the chain's nesting level (Sonar cognitive-complexity\n // semantics); genuinely nested conditionals inside those bodies still deepen.\n const isContinuation = isDecision && isFlatChainContinuation(current);\n\n if (isDecision && !isCaseClause) {\n if (isContinuation) {\n frame.cognitiveComplexity += 1;\n } else {\n frame.cognitiveComplexity += 1 + relativeNesting;\n frame.nestingSensitiveCount += 1;\n }\n }\n if (current.isNamed && switchLikeNodeTypes.has(current.type)) {\n frame.cognitiveComplexity += 1 + relativeNesting;\n frame.nestingSensitiveCount += 1;\n }\n // A plain `else` branch adds one flat cognitive point; `else if` chains are charged on the\n // nested if instead.\n frame.cognitiveComplexity += countPlainElseBranches(current);\n // Sonar charges flow-breaking jumps: goto and labeled break/continue add one flat point.\n if (isFlowBreakingJump(current)) {\n frame.cognitiveComplexity += 1;\n }\n\n // A sequence of identical boolean operators reads as one condition, so only the operator\n // starting a sequence adds a cognitive point (Sonar spec).\n if (isBooleanOperator(current) && startsBooleanOperatorSequence(current)) {\n frame.cognitiveComplexity += 1;\n }\n\n // Pattern guards (Java `when`, Ruby `in y if ...`, Python `case n if ...`, Rust `n if ... =>`)\n // add one independent execution path without nesting.\n if (isPatternGuard(current)) {\n frame.cognitiveComplexity += 1;\n }\n\n const childNesting = isNesting && !isContinuation ? currentNesting + 1 : currentNesting;\n if (countsForOwnBody) {\n frame.nestingDepth = Math.max(frame.nestingDepth, childNesting - frame.entryStructuralNesting);\n }\n\n if (opensFrame) {\n frames.push(createFrame(childNesting + functionNestingBonus, childNesting));\n }\n // The node's NCSS contribution belongs to the innermost frame whose subtree holds it — the\n // frame the node opens, if any (per-function NCSS includes the declaration node itself).\n const ownNcss = ncssContribution(current, countable, containers);\n const ncssFrame = frames.at(-1) as FunctionBodyFrame;\n ncssFrame.ncss += ownNcss;\n if (opensFrame && ownNcss > 0) {\n ncssFrame.hasOwnNcssContribution = true;\n }\n\n for (const child of current.children) {\n visit(\n child,\n childNesting,\n functionNestingBonus,\n insideFunction,\n opensFrame ? false : insideNestedRegion,\n isChargedClassBody\n );\n }\n\n if (opensFrame) {\n const closed = frames.pop() as FunctionBodyFrame;\n results.set(current.id, {\n cognitiveComplexity: closed.cognitiveComplexity,\n nestingDepth: closed.nestingDepth,\n // A function node without a countable declaration of its own (arrow functions, lambdas,\n // blocks) still counts 1 for the declaration itself.\n ncss: closed.ncss + (closed.hasOwnNcssContribution ? 0 : 1),\n });\n const parent = frames.at(-1) as FunctionBodyFrame;\n parent.cognitiveComplexity +=\n closed.cognitiveComplexity +\n closed.nestingSensitiveCount * (closed.entryCognitiveNesting - parent.entryCognitiveNesting);\n parent.nestingSensitiveCount += closed.nestingSensitiveCount;\n parent.ncss += closed.ncss;\n }\n }\n\n visit(root, 0, 0, false, false, false);\n return results;\n}\n\n/**\n * File-level complexity over the whole tree. Cognitive complexity charges nested function/lambda\n * content one nesting level deeper per function boundary crossed (Sonar spec); nesting depth\n * counts every node once.\n */\nfunction measureComplexity(node: Parser.SyntaxNode, language: LanguageDefinition): ComplexityResult {\n let cognitiveComplexity = 0;\n let nestingDepth = 0;\n const { functionNodes, decisionNodes, nestingNodes } = getComplexityNodeSets(language);\n\n function visit(\n current: Parser.SyntaxNode,\n currentNesting: number,\n functionNestingBonus: number,\n insideFunction: boolean,\n insideChargedClassBody: boolean\n ): void {\n // A class body nested in a function (anonymous/local classes) raises the cognitive nesting\n // level once for everything inside it — PMD charges the class body, not the methods it holds,\n // so methods directly inside a charged class body skip the function-boundary bonus.\n const isChargedClassBody = current.type === 'class_body' && insideFunction;\n if (isChargedClassBody) {\n functionNestingBonus += 1;\n }\n if (isFunctionBoundary(current, functionNodes)) {\n if (insideFunction && !insideChargedClassBody) {\n functionNestingBonus += 1;\n }\n insideFunction = true;\n }\n const cognitiveNesting = currentNesting + functionNestingBonus;\n\n // Anonymous keyword tokens can share a type with named nodes (Ruby's `if` node contains an\n // `if` keyword token), so only named nodes count as decisions.\n const isDecision = current.isNamed && decisionNodes.has(current.type) && !isDefaultSwitchBranch(current);\n const isCaseClause = current.isNamed && caseClauseNodeTypes.has(current.type);\n // Ruby's `case ... else` arm is an `else` node; like every other language's default branch it\n // nests its contents inside the switch (it cannot go in the Ruby nesting set because\n // `if`/`begin` else branches would then double-nest under their already-nesting parent).\n const isNesting =\n current.isNamed &&\n (nestingNodes.has(current.type) ||\n (current.type === 'else' && (current.parent?.type === 'case' || current.parent?.type === 'case_match')));\n // `elsif`/`elif`/`else if` continue a flat chain: they add a decision without a nesting\n // surcharge, and their bodies stay at the chain's nesting level (Sonar cognitive-complexity\n // semantics); genuinely nested conditionals inside those bodies still deepen.\n const isContinuation = isDecision && isFlatChainContinuation(current);\n\n if (isDecision && !isCaseClause) {\n cognitiveComplexity += isContinuation ? 1 : 1 + cognitiveNesting;\n }\n if (current.isNamed && switchLikeNodeTypes.has(current.type)) {\n cognitiveComplexity += 1 + cognitiveNesting;\n }\n // A plain `else` branch adds one flat cognitive point; `else if` chains are charged on the\n // nested if instead.\n cognitiveComplexity += countPlainElseBranches(current);\n // Sonar charges flow-breaking jumps: goto and labeled break/continue add one flat point.\n if (isFlowBreakingJump(current)) {\n cognitiveComplexity += 1;\n }\n\n // A sequence of identical boolean operators reads as one condition, so only the operator\n // starting a sequence adds a cognitive point (Sonar spec).\n if (isBooleanOperator(current) && startsBooleanOperatorSequence(current)) {\n cognitiveComplexity += 1;\n }\n\n // Pattern guards (Java `when`, Ruby `in y if ...`, Python `case n if ...`, Rust `n if ... =>`)\n // add one independent execution path without nesting.\n if (isPatternGuard(current)) {\n cognitiveComplexity += 1;\n }\n\n const childNesting = isNesting && !isContinuation ? currentNesting + 1 : currentNesting;\n nestingDepth = Math.max(nestingDepth, childNesting);\n\n for (const child of current.children) {\n visit(child, childNesting, functionNestingBonus, insideFunction, isChargedClassBody);\n }\n }\n\n for (const child of node.children) {\n visit(child, 0, 0, false, false);\n }\n\n return { cognitiveComplexity, nestingDepth };\n}\n\n/**\n * Plain else branches attached to `current`: an `else_clause`/Ruby `else` whose branch is not an\n * `else if` continuation, or a bare Java/Go `alternative:` statement without a clause wrapper.\n */\nfunction countPlainElseBranches(current: Parser.SyntaxNode): number {\n if (!current.isNamed) {\n return 0;\n }\n if (current.type === 'else') {\n // A Ruby `case ... else` is the default arm of a switch, which already counts as a whole\n // (sonar-ruby models it as a match case, not an else branch); `if`/`unless`/`begin` else\n // branches count one point each.\n return current.parent?.type === 'case' || current.parent?.type === 'case_match' ? 0 : 1;\n }\n if (current.type === 'else_clause') {\n return current.namedChildren.some((child) => ifLikeNodeTypes.has(child.type)) ? 0 : 1;\n }\n if (current.type !== 'if_statement' && current.type !== 'if_expression') {\n return 0;\n }\n let count = 0;\n for (let index = 0; index < current.childCount; index += 1) {\n const child = current.child(index);\n if (\n child &&\n current.fieldNameForChild(index) === 'alternative' &&\n child.type !== 'else_clause' &&\n child.type !== 'elif_clause' &&\n !ifLikeNodeTypes.has(child.type)\n ) {\n count += 1;\n }\n }\n return count;\n}\n\n/** goto, and break/continue that jump to a label (their only named child is the label). */\nfunction isFlowBreakingJump(node: Parser.SyntaxNode): boolean {\n if (!node.isNamed) {\n return false;\n }\n if (node.type === 'goto_statement') {\n return true;\n }\n // Rust jumps are expressions; `break value` carries a named expression child, so only an\n // explicit `label` child marks a labeled jump.\n if (node.type === 'break_expression' || node.type === 'continue_expression') {\n return node.namedChildren.some((child) => child.type === 'label' || child.type === 'loop_label');\n }\n // Comments are named children too (`break /* done */;`), so only non-comment children mark a\n // label.\n return (\n (node.type === 'break_statement' || node.type === 'continue_statement') &&\n node.namedChildren.some((child) => !commentNodeTypes.has(child.type))\n );\n}\n\n// Wrappers that are transparent when locating the enclosing boolean operation: PMD/Sonar keep a\n// sequence continuous across parentheses (`a && (b && c)` costs one point).\nconst parenthesizedNodeTypes = new Set(['parenthesized_expression', 'parenthesized_statements']);\n\n/**\n * Whether this boolean operator token starts a new sequence, i.e. its binary node is the root of a\n * run of same-operator binaries (possibly through parentheses). Only the root operator counts one\n * cognitive point: `a && b && c` and `a && (b && c)` cost one, `a && b || c` costs two, matching\n * the Sonar specification and PMD 7.26.0.\n */\nfunction startsBooleanOperatorSequence(token: Parser.SyntaxNode): boolean {\n const binary = token.parent;\n if (!binary) {\n return true;\n }\n let ancestor = binary.parent;\n while (ancestor && parenthesizedNodeTypes.has(ancestor.type)) {\n ancestor = ancestor.parent;\n }\n if (!ancestor || ancestor.type !== binary.type) {\n return true;\n }\n return normalizeBooleanOperator(findBooleanOperatorText(ancestor)) !== normalizeBooleanOperator(token.text);\n}\n\n/** C++ `and`/`or` are alternative spellings of `&&`/`||`, so mixing them keeps one sequence. */\nfunction normalizeBooleanOperator(text: string | undefined): string | undefined {\n if (text === 'and') {\n return '&&';\n }\n if (text === 'or') {\n return '||';\n }\n return text;\n}\n\nfunction findBooleanOperatorText(binaryNode: Parser.SyntaxNode): string | undefined {\n const operator = binaryNode.childForFieldName('operator');\n if (operator) {\n return operator.text;\n }\n return binaryNode.children.find((child) => !child.isNamed && booleanOperators.has(child.text))?.text;\n}\n\n/** Java `guard`, Ruby `if_guard`, Python `if_clause`, and Rust guards inside `match_pattern`. */\nfunction isPatternGuard(node: Parser.SyntaxNode): boolean {\n if (!node.isNamed) {\n return false;\n }\n if (node.type === 'guard' || node.type === 'if_guard' || node.type === 'unless_guard' || node.type === 'if_clause') {\n return true;\n }\n return node.type === 'match_pattern' && node.children.some((child) => !child.isNamed && child.type === 'if');\n}\n\n/** Ruby `elsif`, Python `elif`, and `else if` (an if node in an else/alternative position). */\nfunction isFlatChainContinuation(node: Parser.SyntaxNode): boolean {\n if (node.type === 'elsif' || node.type === 'elif_clause') {\n return true;\n }\n if (node.type !== 'if_statement' && node.type !== 'if_expression' && node.type !== 'if') {\n return false;\n }\n const parent = node.parent;\n if (!parent) {\n return false;\n }\n // JS/C/C++/Rust wrap `else if` in an else clause; Java/Go put it directly in `alternative`.\n return parent.type === 'else_clause' || parent.childForFieldName('alternative')?.id === node.id;\n}\n\n/**\n * C/C++ `default:` shares the `case_statement` node type with `case` (only `case` has a `value`\n * field), and Java's default group/rule carries an expressionless `switch_label`; a default branch\n * adds no decision, though its contents still nest inside the switch like any other arm.\n */\nfunction isDefaultSwitchBranch(node: Parser.SyntaxNode): boolean {\n if (node.type === 'case_statement') {\n return node.childForFieldName('value') === null;\n }\n\n if (node.type === 'switch_block_statement_group' || node.type === 'switch_rule') {\n const label = node.namedChildren.find((child) => child.type === 'switch_label');\n return label !== undefined && label.namedChildCount === 0;\n }\n\n // Python `case _:` / `case y:` and Rust `_ =>` fallback arms are unconditional like `default`\n // (a bare Python name is always a capture); a guard is charged separately as a flat decision,\n // so the arm itself still adds nothing. Rust bare identifiers are NOT suppressed: they can name\n // constants or unit variants, which the grammar cannot distinguish from captures.\n if (node.type === 'case_clause' || node.type === 'match_arm') {\n const pattern = node.namedChildren.find((child) => child.type === 'case_pattern' || child.type === 'match_pattern');\n if (!pattern) {\n return false;\n }\n if (pattern.child(0)?.type === '_' && (pattern.childCount === 1 || pattern.child(1)?.type === 'if')) {\n return true;\n }\n const soleChild = pattern.namedChildCount === 1 ? pattern.namedChild(0) : undefined;\n return (\n node.type === 'case_clause' &&\n soleChild?.type === 'dotted_name' &&\n soleChild.namedChildCount === 1 &&\n soleChild.namedChild(0)?.type === 'identifier'\n );\n }\n\n // Ruby `in y` binds unconditionally (bare lowercase names are variable captures; constants and\n // literals are tests).\n if (node.type === 'in_clause') {\n return node.namedChild(0)?.type === 'identifier';\n }\n\n return false;\n}\n\n/** Parents under which `&&`/`||`/`and`/`or` tokens are actual boolean operators. */\nconst booleanOperatorParentTypes = new Set(['binary_expression', 'binary', 'boolean_operator']);\n\n/**\n * The parent guard is required because the same tokens appear in non-boolean syntax: C++ rvalue\n * references (`int&&`), ref-qualifiers, `operator&&`, and Rust's empty closure parameter list\n * (`|| 5`) must not count as decisions.\n */\nfunction isBooleanOperator(node: Parser.SyntaxNode): boolean {\n if (node.isNamed || !booleanOperators.has(node.text)) {\n return false;\n }\n\n const parent = node.parent;\n return parent !== null && booleanOperatorParentTypes.has(parent.type);\n}\n\nfunction collectNodes(root: Parser.SyntaxNode, nodeTypes: Set<string>): Parser.SyntaxNode[] {\n const nodes: Parser.SyntaxNode[] = [];\n\n function visit(node: Parser.SyntaxNode): void {\n if (nodeTypes.has(node.type)) {\n nodes.push(node);\n }\n\n for (const child of node.namedChildren) {\n visit(child);\n }\n }\n\n visit(root);\n return nodes;\n}\n\n/**\n * 1-based numbers of lines that are neither blank nor comment-only, matching measureLines'\n * classification so duplication line coverage and its code-line denominator agree.\n */\nfunction classifyLines(\n code: string,\n root: Parser.SyntaxNode\n): { lines: CodeMetrics['lines']; codeLineNumbers: Set<number> } {\n const sourceLines = code.length === 0 ? [] : code.split(/\\r\\n|\\n|\\r/);\n // Spans are bucketed by line so classification stays linear; scanning every span per line made\n // this pass quadratic on comment-heavy files.\n const commentSpansByLine = new Map<number, CommentSpan[]>();\n for (const span of collectCommentSpans(root)) {\n const spans = commentSpansByLine.get(span.line) ?? [];\n spans.push(span);\n commentSpansByLine.set(span.line, spans);\n }\n let blank = 0;\n let comment = 0;\n const codeLineNumbers = new Set<number>();\n\n for (const [index, line] of sourceLines.entries()) {\n if (line.trim() === '') {\n blank += 1;\n continue;\n }\n if (isCommentOnlyLine(line, commentSpansByLine.get(index) ?? [])) {\n comment += 1;\n } else {\n codeLineNumbers.add(index + 1);\n }\n }\n\n return {\n lines: {\n total: sourceLines.length,\n code: codeLineNumbers.size,\n comment,\n blank,\n },\n codeLineNumbers,\n };\n}\n\nfunction collectCommentSpans(root: Parser.SyntaxNode): CommentSpan[] {\n const spans: CommentSpan[] = [];\n\n function visit(node: Parser.SyntaxNode): void {\n if (node.type === 'comment' || node.type === 'line_comment' || node.type === 'block_comment') {\n for (let row = node.startPosition.row; row <= node.endPosition.row; row += 1) {\n spans.push({\n line: row,\n startColumn: row === node.startPosition.row ? node.startPosition.column : 0,\n endColumn: row === node.endPosition.row ? node.endPosition.column : Number.POSITIVE_INFINITY,\n });\n }\n }\n\n for (const child of node.namedChildren) {\n visit(child);\n }\n }\n\n visit(root);\n return spans;\n}\n\nfunction isCommentOnlyLine(line: string, relevantSpans: CommentSpan[]): boolean {\n if (relevantSpans.length === 0) {\n return false;\n }\n\n // A line may hold several comments (`/* one */ /* two */`), so every non-whitespace column must\n // be covered by the UNION of spans, not by a single span.\n for (let column = 0; column < line.length; column += 1) {\n if (/\\s/u.test(line[column] ?? ' ')) {\n continue;\n }\n if (!relevantSpans.some((span) => span.startColumn <= column && column < span.endColumn)) {\n return false;\n }\n }\n return true;\n}\n\nfunction measureHalstead(root: Parser.SyntaxNode, code: string): HalsteadMetrics {\n const operators = new Map<string, number>();\n const operands = new Map<string, number>();\n\n function visit(node: Parser.SyntaxNode): void {\n if (node.type === 'comment' || node.type === 'line_comment' || node.type === 'block_comment') {\n return;\n }\n\n if (atomicOperandNodeTypes.has(node.type)) {\n incrementCount(operands, code.slice(node.startIndex, node.endIndex));\n return;\n }\n\n // Operators are counted from leaf tokens only: keyword-named nodes (Ruby `return`, Python\n // `await`, ...) always contain a same-text anonymous keyword leaf, so counting the named node\n // as well would double-count.\n if (node.childCount === 0) {\n const text = code.slice(node.startIndex, node.endIndex);\n // Operands win over text matches so identifiers spelled like word operators (`cache.delete(...)`,\n // a Go parameter named `in`) stay operands; genuine keyword operators are anonymous leaves whose\n // types are never operand types. A blanket `isNamed` guard would break JS's named `optional_chain`.\n if (operandNodeTypes.has(node.type)) {\n incrementCount(operands, text);\n } else if ((operatorTexts.has(text) || operatorTexts.has(node.type)) && isCountableContextualToken(node, text)) {\n incrementCount(operators, text || node.type);\n }\n return;\n }\n\n for (const child of node.children) {\n visit(child);\n }\n }\n\n visit(root);\n\n return deriveHalsteadMetrics({\n distinctOperators: operators.size,\n distinctOperands: operands.size,\n totalOperators: sum(operators.values()),\n totalOperands: sum(operands.values()),\n });\n}\n\n/** Derives the full Halstead metrics from the four base counts (shared with the native backend). */\nfunction deriveHalsteadMetrics(counts: NativeHalsteadCounts): HalsteadMetrics {\n const { distinctOperators, distinctOperands, totalOperators, totalOperands } = counts;\n const vocabulary = distinctOperators + distinctOperands;\n const length = totalOperators + totalOperands;\n const volume = vocabulary === 0 ? 0 : length * Math.log2(vocabulary);\n const difficulty = distinctOperands === 0 ? 0 : (distinctOperators / 2) * (totalOperands / distinctOperands);\n const effort = difficulty * volume;\n\n return {\n distinctOperators,\n distinctOperands,\n totalOperators,\n totalOperands,\n vocabulary,\n length,\n volume,\n effort,\n };\n}\n\n/** Name-carrying leaf types anonymized by tokenizeFunction so consistent renames still match. */\nconst identifierLeafNodeTypes = new Set([\n 'identifier',\n 'property_identifier',\n 'field_identifier',\n 'type_identifier',\n 'constant',\n 'instance_variable',\n 'class_variable',\n 'global_variable',\n]);\n\n/** See TreeMeasurer.collectFunctionTokenSequences. */\nfunction tokenizeFunction(functionNode: Parser.SyntaxNode): Int32Array {\n const symbols: number[] = [];\n collectTokenSymbols(functionNode, symbols, new Map());\n return Int32Array.from(symbols);\n}\n\nfunction collectTokenSymbols(node: Parser.SyntaxNode, symbols: number[], idIndexByName: Map<string, number>): void {\n if (node.type === 'comment' || node.type === 'line_comment' || node.type === 'block_comment') {\n return;\n }\n if (atomicOperandNodeTypes.has(node.type)) {\n symbols.push(hashText(node.type));\n return;\n }\n if (node.childCount > 0) {\n for (const child of node.children) {\n collectTokenSymbols(child, symbols, idIndexByName);\n }\n return;\n }\n if (identifierLeafNodeTypes.has(node.type)) {\n let index = idIndexByName.get(node.text);\n if (index === undefined) {\n index = idIndexByName.size;\n idIndexByName.set(node.text, index);\n }\n symbols.push(hashText(`id${index}`));\n return;\n }\n // Remaining operand leaves are literals, normalized by kind; everything else (keywords,\n // operators, punctuation) is kept verbatim.\n symbols.push(hashText(operandNodeTypes.has(node.type) ? node.type : node.text));\n}\n\nfunction findFunctionName(node: Parser.SyntaxNode): string | undefined {\n const wrappedName = findWrappedComponentName(node);\n if (wrappedName) {\n return wrappedName;\n }\n\n const nameNode = node.childForFieldName('name');\n if (nameNode) {\n return nameNode.text;\n }\n\n // C/C++ definitions name the function inside the (possibly pointer-wrapped) declarator chain.\n const declaratorName = findDeclaratorName(node);\n if (declaratorName) {\n return declaratorName;\n }\n\n const parent = node.parent;\n if (!parent) {\n return undefined;\n }\n\n // A Rust closure bound to a simple `let` identifier (`let add = |x| ...;`) takes that identifier\n // as its name, mirroring how JS arrow functions assigned to a variable are named, so calls to the\n // binding resolve as intra-file edges.\n if (node.type === 'closure_expression' && parent.type === 'let_declaration') {\n const patternNode = parent.childForFieldName('pattern');\n return patternNode?.type === 'identifier' ? patternNode.text : undefined;\n }\n\n // A C++ lambda assigned to a variable (`auto f = [](int x) { ... };`) takes the variable name,\n // like Rust `let` closures above, so calls to the binding resolve as intra-file edges.\n if (node.type === 'lambda_expression' && parent.type === 'init_declarator') {\n return unwrapDeclaratorName(parent.childForFieldName('declarator'));\n }\n\n // A Go func literal bound via `add := func...` or `var add = func...` takes the identifier at\n // the same list position; unpaired or non-identifier targets stay unnamed.\n if (node.type === 'func_literal' && parent.type === 'expression_list') {\n return findGoFuncLiteralName(node, parent);\n }\n\n // Ruby lambdas assigned to a name (`choose = ->(x) {...}` / `ADD = lambda { ... }`) take that\n // name; Ruby assignments use the `left` field, and `lambda { }` blocks hang off a `call`.\n if (node.type === 'lambda' && parent.type === 'assignment') {\n return findRubyAssignmentName(parent);\n }\n if ((node.type === 'block' || node.type === 'do_block') && isRubyLambdaCall(parent)) {\n return parent.parent?.type === 'assignment' ? findRubyAssignmentName(parent.parent) : undefined;\n }\n\n const parentName = parent.childForFieldName('name');\n return parentName?.text;\n}\n\nfunction findDeclaratorName(node: Parser.SyntaxNode): string | undefined {\n return unwrapDeclaratorName(node.childForFieldName('declarator'));\n}\n\n/**\n * Unwraps a C/C++ declarator chain to the declared name, handling parenthesized declarators\n * (function pointers), qualified names, destructors, and operator overloads explicitly; a\n * rightmost-identifier fallback would pick up parameter names from nested `function_declarator`s.\n */\nfunction unwrapDeclaratorName(declarator: Parser.SyntaxNode | null): string | undefined {\n let current: Parser.SyntaxNode | null | undefined = declarator;\n while (current) {\n switch (current.type) {\n case 'identifier':\n case 'field_identifier':\n case 'type_identifier':\n case 'destructor_name':\n case 'operator_name': {\n return current.text;\n }\n // A C++ conversion operator (`operator int()`) is its own declarator node whose text spans\n // the parameter list and qualifiers; only `operator <type>` is the name.\n case 'operator_cast': {\n return `operator ${current.childForFieldName('type')?.text ?? ''}`.trimEnd();\n }\n // Template specializations (`id<int>`) and qualified names both carry a `name` field.\n case 'template_function':\n case 'qualified_identifier': {\n current = current.childForFieldName('name');\n break;\n }\n default: {\n current = nextDeclarator(current);\n }\n }\n }\n return undefined;\n}\n\n/**\n * Steps into the inner declarator; `reference_declarator` and `parenthesized_declarator` do not\n * expose a `declarator` field in tree-sitter-cpp, so their sole named child is the inner node.\n */\nfunction nextDeclarator(node: Parser.SyntaxNode): Parser.SyntaxNode | undefined {\n const direct = node.childForFieldName('declarator');\n if (direct) {\n return direct;\n }\n if (node.type === 'reference_declarator' || node.type === 'parenthesized_declarator') {\n return node.namedChild(0) ?? undefined;\n }\n return undefined;\n}\n\nfunction findRubyAssignmentName(assignment: Parser.SyntaxNode): string | undefined {\n const leftNode = assignment.childForFieldName('left');\n return leftNode?.type === 'identifier' || leftNode?.type === 'constant' ? leftNode.text : undefined;\n}\n\nfunction isRubyLambdaCall(node: Parser.SyntaxNode): boolean {\n if (node.type !== 'call' || node.childForFieldName('receiver')) {\n return false;\n }\n const methodNode = node.childForFieldName('method');\n return methodNode?.type === 'identifier' && (methodNode.text === 'lambda' || methodNode.text === 'proc');\n}\n\nfunction findGoFuncLiteralName(node: Parser.SyntaxNode, expressionList: Parser.SyntaxNode): string | undefined {\n const holder = expressionList.parent;\n // Comments interleave with expressions in the list but have no matching binding target, so\n // positions are aligned over non-comment children on both sides.\n const values = expressionList.namedChildren.filter((child) => child.type !== 'comment');\n const valueIndex = values.findIndex((child) => child.id === node.id);\n if (!holder || valueIndex === -1) {\n return undefined;\n }\n\n if (holder.type === 'short_var_declaration') {\n const targets = holder.childForFieldName('left')?.namedChildren.filter((child) => child.type !== 'comment');\n return asGoBindingName(targets?.[valueIndex]);\n }\n\n if (holder.type === 'var_spec') {\n const target = findChildrenByFieldName(holder, 'name')[valueIndex];\n return asGoBindingName(target);\n }\n\n return undefined;\n}\n\n/** Go's blank identifier `_` discards the value and creates no callable binding. */\nfunction asGoBindingName(target: Parser.SyntaxNode | undefined): string | undefined {\n return target?.type === 'identifier' && target.text !== '_' ? target.text : undefined;\n}\n\nfunction findWrappedComponentName(node: Parser.SyntaxNode): string | undefined {\n let current: Parser.SyntaxNode | undefined = node;\n while (current) {\n const argumentsNode: Parser.SyntaxNode | null = current.parent;\n const callNode: Parser.SyntaxNode | null | undefined = argumentsNode?.parent;\n if (argumentsNode?.type !== 'arguments' || callNode?.type !== 'call_expression') {\n return undefined;\n }\n\n if (!isReactComponentWrapperCall(callNode)) {\n return undefined;\n }\n\n const declaratorNode = callNode.parent;\n if (declaratorNode?.type === 'variable_declarator') {\n return declaratorNode.childForFieldName('name')?.text;\n }\n\n current = callNode;\n }\n\n return undefined;\n}\n\nfunction isReactComponentWrapperCall(node: Parser.SyntaxNode): boolean {\n const calleeNode = node.childForFieldName('function') ?? node.namedChild(0);\n return (\n calleeNode?.text === 'memo' ||\n calleeNode?.text === 'React.memo' ||\n calleeNode?.text === 'forwardRef' ||\n calleeNode?.text === 'React.forwardRef'\n );\n}\n\n/** Ternary/conditional and Rust try parents make `?` an operator; TS optional markers do not. */\nconst questionOperatorParentTypes = new Set([\n 'ternary_expression',\n 'conditional_expression',\n 'conditional',\n 'try_expression',\n // TypeScript conditional types (`T extends U ? X : Y`) select like a ternary.\n 'conditional_type',\n]);\n\nfunction isCountableContextualToken(node: Parser.SyntaxNode, text: string): boolean {\n if (text === '@') {\n // Python matrix multiplication only; decorator/annotation `@` marks are not operators.\n const parentType = node.parent?.type;\n return parentType === 'binary_operator' || parentType === 'augmented_assignment';\n }\n if (text !== '?') {\n return true;\n }\n const parentType = node.parent?.type;\n return parentType !== undefined && questionOperatorParentTypes.has(parentType);\n}\n\nfunction findChildrenByFieldName(node: Parser.SyntaxNode, fieldName: string): Parser.SyntaxNode[] {\n const children: Parser.SyntaxNode[] = [];\n for (let index = 0; index < node.childCount; index += 1) {\n const child = node.child(index);\n if (child && node.fieldNameForChild(index) === fieldName) {\n children.push(child);\n }\n }\n return children;\n}\n\nfunction incrementCount(map: Map<string, number>, value: string): void {\n map.set(value, (map.get(value) ?? 0) + 1);\n}\n\nfunction maxCognitiveComplexity(functions: FunctionMetrics[]): number {\n return functions.length === 0 ? 0 : Math.max(...functions.map((fn) => fn.cognitiveComplexity));\n}\n\nfunction sum(values: Iterable<number>): number {\n let total = 0;\n for (const value of values) {\n total += value;\n }\n return total;\n}\n"],"mappings":"iQAsBA,MAAM,EAAmB,IAAI,IAAI,CAAC,KAAM,KAAM,MAAO,IAAI,CAAC,EACpD,EAAgB,IAAI,IAAI,uZAsG9B,CAAC,EAEK,EAAmB,IAAI,IAAI,4qBAoDjC,CAAC,EAUK,EAAyB,IAAI,IAAI,CACrC,6BACA,QACA,uBACA,gBACA,sBACA,uBACA,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":3,"file":"metrics.cjs","names":["createLanguageRegistry","measureCodeNative","collectCrossFileDataNative","collectFunctionTokenSequencesNative"],"sources":["../src/metrics.ts"],"sourcesContent":["import type { CrossFileDuplicateCandidate, CrossFileDuplicationFileData } from './duplication.js';\nimport { createLanguageRegistry } from './languages.js';\nimport {\n collectCrossFileDataNative,\n collectFunctionTokenSequencesNative,\n measureCodeNative,\n type NativeHalsteadCounts,\n type NativeMetricsPayload,\n} from './nativeMetrics.js';\nimport type { CodeMetrics, HalsteadMetrics, LanguageDefinition, LanguageName, MeasureOptions } from './types.js';\n\n/**\n * Measures code metrics for the built-in languages. Parsing and metric passes run in the bundled\n * Rust addon (tree-sitter); this class resolves language aliases, crosses the N-API boundary, and\n * derives the Halstead float metrics from the natively measured counts.\n */\nexport class TreeMeasurer {\n private readonly registry = createLanguageRegistry();\n\n getSupportedLanguages(): LanguageName[] {\n return [...new Set([...this.registry.values()].map((language) => language.name))];\n }\n\n measure(code: string, options: MeasureOptions): CodeMetrics {\n const language = this.resolveLanguage(options.language);\n const includeSyntaxTree = options.includeSyntaxTree ?? false;\n const payload = measureCodeNative(code, language.name, includeSyntaxTree, options.duplication);\n return assembleNativeMetrics(payload, includeSyntaxTree);\n }\n\n /** Collects one file's duplicate candidates for cross-file clone detection. */\n collectDuplicationCandidates(code: string, options: MeasureOptions): CrossFileDuplicateCandidate[] {\n return this.collectCrossFileDuplicationFileData(code, options).candidates;\n }\n\n /**\n * Collects one file's duplicate candidates, normalized tokens, and statement structure for\n * cross-file clone detection with measureCrossFileDuplication.\n */\n collectCrossFileDuplicationFileData(code: string, options: MeasureOptions): CrossFileDuplicationFileData {\n const language = this.resolveLanguage(options.language);\n const payload = collectCrossFileDataNative(code, language.name, options.duplication?.minTokens);\n return {\n candidates: payload.candidates,\n tokens: payload.tokens,\n containerStatements: payload.containerStatements,\n // Lets cross-file line coverage count only code lines, like within-file coverage.\n codeLineNumbers: new Set(payload.codeLineNumbers),\n };\n }\n\n /**\n * Normalized token hash sequences of every function, index-parallel to the functions array of\n * measure(): identifiers are anonymized by first occurrence within the function, literals by\n * kind, and keywords/operators kept verbatim, so the regression gate can re-match renamed or\n * moved functions across two revisions by token-LCS similarity.\n */\n collectFunctionTokenSequences(code: string, options: MeasureOptions): Int32Array[] {\n const language = this.resolveLanguage(options.language);\n return collectFunctionTokenSequencesNative(code, language.name);\n }\n\n private resolveLanguage(name: LanguageName): LanguageDefinition {\n const language = this.registry.get(name);\n if (!language) {\n throw new Error(`Unsupported language: ${name}`);\n }\n return language;\n }\n}\n\n/**\n * Completes a native measurement into CodeMetrics. The object is rebuilt field by field (rather\n * than spread from the parsed JSON) so the result has a stable shape, including\n * explicitly-undefined optional keys.\n */\nfunction assembleNativeMetrics(payload: NativeMetricsPayload, includeSyntaxTree: boolean): CodeMetrics {\n return {\n language: payload.language,\n bytes: payload.bytes,\n lines: payload.lines,\n functions: payload.functions.map((fn) => ({\n name: fn.name,\n nodeType: fn.nodeType,\n startLine: fn.startLine,\n startColumn: fn.startColumn,\n endLine: fn.endLine,\n cognitiveComplexity: fn.cognitiveComplexity,\n nestingDepth: fn.nestingDepth,\n ncss: fn.ncss,\n parameterCount: fn.parameterCount,\n halstead: deriveHalsteadMetrics(fn.halsteadCounts),\n depDegree: fn.depDegree,\n })),\n cognitiveComplexity: payload.cognitiveComplexity,\n maxCognitiveComplexity: payload.maxCognitiveComplexity,\n nestingDepth: payload.nestingDepth,\n ncssCount: payload.ncssCount,\n duplication: payload.duplication,\n halstead: deriveHalsteadMetrics(payload.halsteadCounts),\n syntaxTree: includeSyntaxTree ? payload.syntaxTree : undefined,\n };\n}\n\nfunction deriveHalsteadMetrics(counts: NativeHalsteadCounts): HalsteadMetrics {\n const { distinctOperators, distinctOperands, totalOperators, totalOperands } = counts;\n const vocabulary = distinctOperators + distinctOperands;\n const length = totalOperators + totalOperands;\n const volume = vocabulary === 0 ? 0 : length * Math.log2(vocabulary);\n const difficulty = distinctOperands === 0 ? 0 : (distinctOperators / 2) * (totalOperands / distinctOperands);\n const effort = difficulty * volume;\n\n return {\n distinctOperators,\n distinctOperands,\n totalOperators,\n totalOperands,\n vocabulary,\n length,\n volume,\n effort,\n };\n}\n\nexport const defaultMeasurer = new TreeMeasurer();\n\nexport function measureCode(code: string, options: MeasureOptions): CodeMetrics {\n return defaultMeasurer.measure(code, options);\n}\n\n/** Standalone helper mirroring measureCode for the default measurer. */\nexport function collectDuplicationCandidates(code: string, options: MeasureOptions): CrossFileDuplicateCandidate[] {\n return defaultMeasurer.collectDuplicationCandidates(code, options);\n}\n\n/** Standalone helper mirroring measureCode for the default measurer. */\nexport function collectFunctionTokenSequences(code: string, options: MeasureOptions): Int32Array[] {\n return defaultMeasurer.collectFunctionTokenSequences(code, options);\n}\n\n/** Standalone helper mirroring measureCode for the default measurer. */\nexport function collectCrossFileDuplicationFileData(\n code: string,\n options: MeasureOptions\n): CrossFileDuplicationFileData {\n return defaultMeasurer.collectCrossFileDuplicationFileData(code, options);\n}\n"],"mappings":"iFAgBA,IAAa,EAAb,KAA0B,CACxB,SAA4BA,EAAAA,uBAAuB,EAEnD,uBAAwC,CACtC,MAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,KAAK,SAAS,OAAO,CAAC,CAAC,CAAC,IAAK,GAAa,EAAS,IAAI,CAAC,CAAC,CAClF,CAEA,QAAQ,EAAc,EAAsC,CAC1D,IAAM,EAAW,KAAK,gBAAgB,EAAQ,QAAQ,EAChD,EAAoB,EAAQ,mBAAqB,GAEvD,OAAO,EADSC,EAAAA,kBAAkB,EAAM,EAAS,KAAM,EAAmB,EAAQ,WAC/C,EAAG,CAAiB,CACzD,CAGA,6BAA6B,EAAc,EAAwD,CACjG,OAAO,KAAK,oCAAoC,EAAM,CAAO,CAAC,CAAC,UACjE,CAMA,oCAAoC,EAAc,EAAuD,CACvG,IAAM,EAAW,KAAK,gBAAgB,EAAQ,QAAQ,EAChD,EAAUC,EAAAA,2BAA2B,EAAM,EAAS,KAAM,EAAQ,aAAa,S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,CACF,CAEA,MAAa,EAAkB,IAAI,EAEnC,SAAgB,EAAY,EAAc,EAAsC,CAC9E,OAAO,EAAgB,QAAQ,EAAM,CAAO,CAC9C,CAGA,SAAgB,EAA6B,EAAc,EAAwD,CACjH,OAAO,EAAgB,6BAA6B,EAAM,CAAO,CACnE,CAGA,SAAgB,EAA8B,EAAc,EAAuC,CACjG,OAAO,EAAgB,8BAA8B,EAAM,CAAO,CACpE,CAGA,SAAgB,EACd,EACA,EAC8B,CAC9B,OAAO,EAAgB,oCAAoC,EAAM,CAAO,CAC1E"}
|
package/dist/metrics.d.ts
CHANGED
|
@@ -1,27 +1,29 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type { CodeMetrics,
|
|
1
|
+
import type { CrossFileDuplicateCandidate, CrossFileDuplicationFileData } from './duplication.js';
|
|
2
|
+
import type { CodeMetrics, LanguageName, MeasureOptions } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Measures code metrics for the built-in languages. Parsing and metric passes run in the bundled
|
|
5
|
+
* Rust addon (tree-sitter); this class resolves language aliases, crosses the N-API boundary, and
|
|
6
|
+
* derives the Halstead float metrics from the natively measured counts.
|
|
7
|
+
*/
|
|
3
8
|
export declare class TreeMeasurer {
|
|
4
9
|
private readonly registry;
|
|
5
|
-
registerLanguage(language: LanguageDefinition): void;
|
|
6
10
|
getSupportedLanguages(): LanguageName[];
|
|
7
11
|
measure(code: string, options: MeasureOptions): CodeMetrics;
|
|
8
12
|
/** Collects one file's duplicate candidates for cross-file clone detection. */
|
|
9
13
|
collectDuplicationCandidates(code: string, options: MeasureOptions): CrossFileDuplicateCandidate[];
|
|
14
|
+
/**
|
|
15
|
+
* Collects one file's duplicate candidates, normalized tokens, and statement structure for
|
|
16
|
+
* cross-file clone detection with measureCrossFileDuplication.
|
|
17
|
+
*/
|
|
18
|
+
collectCrossFileDuplicationFileData(code: string, options: MeasureOptions): CrossFileDuplicationFileData;
|
|
10
19
|
/**
|
|
11
20
|
* Normalized token hash sequences of every function, index-parallel to the functions array of
|
|
12
21
|
* measure(): identifiers are anonymized by first occurrence within the function, literals by
|
|
13
22
|
* kind, and keywords/operators kept verbatim, so the regression gate can re-match renamed or
|
|
14
|
-
* moved functions across two revisions by token-LCS similarity.
|
|
15
|
-
* TypeScript backend.
|
|
23
|
+
* moved functions across two revisions by token-LCS similarity.
|
|
16
24
|
*/
|
|
17
25
|
collectFunctionTokenSequences(code: string, options: MeasureOptions): Int32Array[];
|
|
18
|
-
|
|
19
|
-
* Collects one file's duplicate candidates, normalized tokens, and statement structure for
|
|
20
|
-
* cross-file clone detection with measureCrossFileDuplication. Always measured by the
|
|
21
|
-
* TypeScript backend.
|
|
22
|
-
*/
|
|
23
|
-
collectCrossFileDuplicationFileData(code: string, options: MeasureOptions): CrossFileDuplicationFileData;
|
|
24
|
-
private parse;
|
|
26
|
+
private resolveLanguage;
|
|
25
27
|
}
|
|
26
28
|
export declare const defaultMeasurer: TreeMeasurer;
|
|
27
29
|
export declare function measureCode(code: string, options: MeasureOptions): CodeMetrics;
|
package/dist/metrics.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{collectCrossFileDuplicateCandidates as e,defaultDuplicationOptions as t,hashText as n,measureDuplication as r}from"./duplication.js";import{createLanguageRegistry as i}from"./languages.js";import{measureDepDegree as a}from"./depDegree.js";import{commentNodeTypes as o,countNcss as s,getNcssSets as c,invalidateNcssSetsCache as l,ncssContribution as u}from"./ncss.js";import{measureWithNativeBackend as d}from"./nativeMetrics.js";import f from"tree-sitter";const p=new Set([`&&`,`||`,`and`,`or`]),m=new Set(`+,-,*,/,%,**,=,+=,-=,*=,/=,%=,==,!=,===,!==,<,<=,>,>=,!,~,&,|,^,++,--,<<,>>,>>>,=>,**=,<<=,>>=,>>>=,&=,|=,^=,&&=,||=,??=,??,?.,?,//,//=,@,@=,:=,<-,<=>,=~,..,...,..=,&&,||,!~,&^,&^=,&.,.,->,::,->*,.*,sizeof,alignof,defined?,as,bitand,bitor,xor,compl,and_eq,or_eq,xor_eq,not_eq,and,or,not,in,is,instanceof,typeof,new,delete,return,throw,raise,yield,await,co_await,co_yield,co_return,break,continue`.split(`,`)),h=new Set(`identifier.property_identifier.field_identifier.type_identifier.constant.instance_variable.class_variable.global_variable.simple_symbol.self.this.super.primitive_type.boolean_type.void_type.auto.number.integer.float.integer_literal.float_literal.int_literal.rune_literal.imaginary_literal.number_literal.decimal_integer_literal.hex_integer_literal.octal_integer_literal.binary_integer_literal.decimal_floating_point_literal.hex_floating_point_literal.string.string_literal.raw_string_literal.string_fragment.multiline_string_fragment.string_content.raw_string_content.template_string.character_literal.char_literal.character.true.false.null.null_literal.undefined.nil.none`.split(`.`)),g=new Set([`interpreted_string_literal`,`regex`,`user_defined_literal`,`integral_type`,`floating_point_type`,`sized_type_specifier`,`placeholder_type_specifier`]);var _=class{registry=i();registerLanguage(e){ae(e),l(e),this.registry.set(e.name,e);for(let t of e.aliases??[])this.registry.set(t,e)}getSupportedLanguages(){return[...new Set([...this.registry.values()].map(e=>e.name))]}measure(e,t){let n=this.registry.get(t.language);if(!n)throw Error(`Unsupported language: ${t.language}`);let i=y(t)?d(e,n,t.includeSyntaxTree??!1):void 0;if(i)return T(i,t.includeSyntaxTree??!1);let a=v(e,n),o=E(a,U(a,new Set(n.functionNodeTypes)).filter(e=>!D(e)&&ie(e)),n,e),c=se(a,n),{lines:l,codeLineNumbers:u}=W(e,a);return{language:n.name,bytes:Buffer.byteLength(e),lines:l,functions:o,cognitiveComplexity:c.cognitiveComplexity,maxCognitiveComplexity:Ce(o),nestingDepth:c.nestingDepth,ncssCount:s(a,n),duplication:r(a,u,t.duplication),halstead:G(a,e),syntaxTree:t.includeSyntaxTree?a.toString():void 0}}collectDuplicationCandidates(e,t){return this.collectCrossFileDuplicationFileData(e,t).candidates}collectFunctionTokenSequences(e,t){let{language:n,root:r}=this.parse(e,t);return U(r,new Set(n.functionNodeTypes)).filter(e=>!D(e)&&ie(e)).map(e=>me(e))}collectCrossFileDuplicationFileData(t,n){let{root:r}=this.parse(t,n);return{...e(r,n.duplication),codeLineNumbers:W(t,r).codeLineNumbers}}parse(e,t){let n=this.registry.get(t.language);if(!n)throw Error(`Unsupported language: ${t.language}`);return{language:n,root:v(e,n)}}};function v(e,t){let n=new f;return n.setLanguage(t.parserLanguage),n.parse(e,void 0,{bufferSize:e.length+1}).rootNode}function y(e){let n=e.duplication;return(n?.minTokens??t.minTokens)===t.minTokens&&(n?.maxGapTokens??t.maxGapTokens)===t.maxGapTokens&&(n?.minSimilarityPercent??t.minSimilarityPercent)===t.minSimilarityPercent}const b=new _;function x(e,t){return b.measure(e,t)}function S(e,t){return b.collectDuplicationCandidates(e,t)}function C(e,t){return b.collectFunctionTokenSequences(e,t)}function w(e,t){return b.collectCrossFileDuplicationFileData(e,t)}function T(e,t){return{language:e.language,bytes:e.bytes,lines:e.lines,functions:e.functions.map(e=>({name:e.name,nodeType:e.nodeType,startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,cognitiveComplexity:e.cognitiveComplexity,nestingDepth:e.nestingDepth,ncss:e.ncss,parameterCount:e.parameterCount,halstead:K(e.halsteadCounts),depDegree:e.depDegree})),cognitiveComplexity:e.cognitiveComplexity,maxCognitiveComplexity:e.maxCognitiveComplexity,nestingDepth:e.nestingDepth,ncssCount:e.ncssCount,duplication:e.duplication,halstead:K(e.halsteadCounts),syntaxTree:t?e.syntaxTree:void 0}}function E(e,t,n,r){let i=oe(e,n),{functionNodes:o}=N(n);return t.map(e=>{let t=i.get(e.id);if(!t)throw Error(`missing body metrics for function node at line ${e.startPosition.row+1}`);return{name:he(e),nodeType:e.type,startLine:e.startPosition.row+1,startColumn:e.startPosition.column,endLine:e.endPosition.row+1,cognitiveComplexity:t.cognitiveComplexity,nestingDepth:t.nestingDepth,ncss:t.ncss,parameterCount:ee(e),halstead:G(e,r),depDegree:a(e,e=>O(e,o))}})}function ee(e){if(e.childForFieldName(`parameter`))return 1;let t=ne(e);if(!t)return 0;if(t.type===`identifier`)return 1;let n=new Set(Q(t,`locals`).map(e=>e.id)),r=0;for(let e of t.namedChildren)e.type===`comment`||e.type===`self_parameter`||e.type===`receiver_parameter`||e.type===`block_parameter`||e.type===`positional_separator`||e.type===`keyword_separator`||n.has(e.id)||te(e)||(r+=e.type===`parameter_declaration`?Math.max(1,Q(e,`name`).length):1);let i=t.children.filter(e=>!e.isNamed&&e.text===`...`).length;return r+i}function te(e){return e.type===`parameter_declaration`&&e.childForFieldName(`declarator`)===null&&e.childForFieldName(`type`)?.text===`void`}function ne(e){let t=e.childForFieldName(`parameters`);if(t)return t;if(e.type===`compact_constructor_declaration`)return e.parent?.parent?.childForFieldName(`parameters`)??void 0;let n=e.childForFieldName(`declarator`);for(;n;){let e=n.childForFieldName(`parameters`);if(e)return e;n=Y(n)}return e.namedChildren.find(e=>e.type===`formal_parameters`||e.type===`parameter_list`)}const re=new Set([`function_definition`,`constructor_declaration`,`compact_constructor_declaration`,`function_signature_item`]);function ie(e){return!re.has(e.type)||e.childForFieldName(`body`)!==null||e.namedChildren.some(e=>e.type===`try_statement`)}function D(e){return(e.type===`block`||e.type===`do_block`)&&e.parent?.type===`lambda`}function O(e,t){return t.has(e.type)&&!D(e)}const k=new Set([`switch_statement`,`switch_expression`,`expression_switch_statement`,`type_switch_statement`,`select_statement`,`match_expression`,`match_statement`,`case`,`case_match`]),A=new Set([`case_clause`,`switch_case`,`switch_block_statement_group`,`switch_rule`,`case_statement`,`expression_case`,`type_case`,`communication_case`,`match_arm`,`when`,`in_clause`]),j=new Set([`if_statement`,`if_expression`,`if`,`unless`]),M=new WeakMap;function ae(e){M.delete(e)}function N(e){let t=M.get(e);return t||(t={functionNodes:new Set(e.functionNodeTypes),decisionNodes:new Set(e.decisionNodeTypes),nestingNodes:new Set(e.nestingNodeTypes)},M.set(e,t)),t}function P(e,t){return{cognitiveComplexity:0,nestingSensitiveCount:0,nestingDepth:0,ncss:0,hasOwnNcssContribution:!1,entryCognitiveNesting:e,entryStructuralNesting:t}}function oe(e,t){let{functionNodes:n,decisionNodes:r,nestingNodes:i}=N(t),{countable:a,containers:o}=c(t),s=new Map,l=[P(0,0)];function d(e,t,c,f,p,m){let h=e.type===`class_body`&&f;h&&(p=!0,c+=1);let g=O(e,n);g&&(f&&!m&&(c+=1),f=!0);let _=l.at(-1),v=t+c-_.entryCognitiveNesting,y=!p&&!g,b=e.isNamed&&r.has(e.type)&&!V(e),x=e.isNamed&&A.has(e.type),S=e.isNamed&&(i.has(e.type)||e.type===`else`&&(e.parent?.type===`case`||e.parent?.type===`case_match`)),C=b&&B(e);b&&!x&&(C?_.cognitiveComplexity+=1:(_.cognitiveComplexity+=1+v,_.nestingSensitiveCount+=1)),e.isNamed&&k.has(e.type)&&(_.cognitiveComplexity+=1+v,_.nestingSensitiveCount+=1),_.cognitiveComplexity+=F(e),I(e)&&(_.cognitiveComplexity+=1),H(e)&&L(e)&&(_.cognitiveComplexity+=1),z(e)&&(_.cognitiveComplexity+=1);let w=S&&!C?t+1:t;y&&(_.nestingDepth=Math.max(_.nestingDepth,w-_.entryStructuralNesting)),g&&l.push(P(w+c,w));let T=u(e,a,o),E=l.at(-1);E.ncss+=T,g&&T>0&&(E.hasOwnNcssContribution=!0);for(let t of e.children)d(t,w,c,f,!g&&p,h);if(g){let t=l.pop();s.set(e.id,{cognitiveComplexity:t.cognitiveComplexity,nestingDepth:t.nestingDepth,ncss:t.ncss+ +!t.hasOwnNcssContribution});let n=l.at(-1);n.cognitiveComplexity+=t.cognitiveComplexity+t.nestingSensitiveCount*(t.entryCognitiveNesting-n.entryCognitiveNesting),n.nestingSensitiveCount+=t.nestingSensitiveCount,n.ncss+=t.ncss}}return d(e,0,0,!1,!1,!1),s}function se(e,t){let n=0,r=0,{functionNodes:i,decisionNodes:a,nestingNodes:o}=N(t);function s(e,t,c,l,u){let d=e.type===`class_body`&&l;d&&(c+=1),O(e,i)&&(l&&!u&&(c+=1),l=!0);let f=t+c,p=e.isNamed&&a.has(e.type)&&!V(e),m=e.isNamed&&A.has(e.type),h=e.isNamed&&(o.has(e.type)||e.type===`else`&&(e.parent?.type===`case`||e.parent?.type===`case_match`)),g=p&&B(e);p&&!m&&(n+=g?1:1+f),e.isNamed&&k.has(e.type)&&(n+=1+f),n+=F(e),I(e)&&(n+=1),H(e)&&L(e)&&(n+=1),z(e)&&(n+=1);let _=h&&!g?t+1:t;r=Math.max(r,_);for(let t of e.children)s(t,_,c,l,d)}for(let t of e.children)s(t,0,0,!1,!1);return{cognitiveComplexity:n,nestingDepth:r}}function F(e){if(!e.isNamed)return 0;if(e.type===`else`)return e.parent?.type===`case`||e.parent?.type===`case_match`?0:1;if(e.type===`else_clause`)return+!e.namedChildren.some(e=>j.has(e.type));if(e.type!==`if_statement`&&e.type!==`if_expression`)return 0;let t=0;for(let n=0;n<e.childCount;n+=1){let r=e.child(n);r&&e.fieldNameForChild(n)===`alternative`&&r.type!==`else_clause`&&r.type!==`elif_clause`&&!j.has(r.type)&&(t+=1)}return t}function I(e){return e.isNamed?e.type===`goto_statement`?!0:e.type===`break_expression`||e.type===`continue_expression`?e.namedChildren.some(e=>e.type===`label`||e.type===`loop_label`):(e.type===`break_statement`||e.type===`continue_statement`)&&e.namedChildren.some(e=>!o.has(e.type)):!1}const ce=new Set([`parenthesized_expression`,`parenthesized_statements`]);function L(e){let t=e.parent;if(!t)return!0;let n=t.parent;for(;n&&ce.has(n.type);)n=n.parent;return!n||n.type!==t.type||R(le(n))!==R(e.text)}function R(e){return e===`and`?`&&`:e===`or`?`||`:e}function le(e){let t=e.childForFieldName(`operator`);return t?t.text:e.children.find(e=>!e.isNamed&&p.has(e.text))?.text}function z(e){return e.isNamed?e.type===`guard`||e.type===`if_guard`||e.type===`unless_guard`||e.type===`if_clause`||e.type===`match_pattern`&&e.children.some(e=>!e.isNamed&&e.type===`if`):!1}function B(e){if(e.type===`elsif`||e.type===`elif_clause`)return!0;if(e.type!==`if_statement`&&e.type!==`if_expression`&&e.type!==`if`)return!1;let t=e.parent;return t?t.type===`else_clause`||t.childForFieldName(`alternative`)?.id===e.id:!1}function V(e){if(e.type===`case_statement`)return e.childForFieldName(`value`)===null;if(e.type===`switch_block_statement_group`||e.type===`switch_rule`){let t=e.namedChildren.find(e=>e.type===`switch_label`);return t!==void 0&&t.namedChildCount===0}if(e.type===`case_clause`||e.type===`match_arm`){let t=e.namedChildren.find(e=>e.type===`case_pattern`||e.type===`match_pattern`);if(!t)return!1;if(t.child(0)?.type===`_`&&(t.childCount===1||t.child(1)?.type===`if`))return!0;let n=t.namedChildCount===1?t.namedChild(0):void 0;return e.type===`case_clause`&&n?.type===`dotted_name`&&n.namedChildCount===1&&n.namedChild(0)?.type===`identifier`}return e.type===`in_clause`&&e.namedChild(0)?.type===`identifier`}const ue=new Set([`binary_expression`,`binary`,`boolean_operator`]);function H(e){if(e.isNamed||!p.has(e.text))return!1;let t=e.parent;return t!==null&&ue.has(t.type)}function U(e,t){let n=[];function r(e){t.has(e.type)&&n.push(e);for(let t of e.namedChildren)r(t)}return r(e),n}function W(e,t){let n=e.length===0?[]:e.split(/\r\n|\n|\r/),r=new Map;for(let e of de(t)){let t=r.get(e.line)??[];t.push(e),r.set(e.line,t)}let i=0,a=0,o=new Set;for(let[e,t]of n.entries()){if(t.trim()===``){i+=1;continue}fe(t,r.get(e)??[])?a+=1:o.add(e+1)}return{lines:{total:n.length,code:o.size,comment:a,blank:i},codeLineNumbers:o}}function de(e){let t=[];function n(e){if(e.type===`comment`||e.type===`line_comment`||e.type===`block_comment`)for(let n=e.startPosition.row;n<=e.endPosition.row;n+=1)t.push({line:n,startColumn:n===e.startPosition.row?e.startPosition.column:0,endColumn:n===e.endPosition.row?e.endPosition.column:1/0});for(let t of e.namedChildren)n(t)}return n(e),t}function fe(e,t){if(t.length===0)return!1;for(let n=0;n<e.length;n+=1)if(!/\s/u.test(e[n]??` `)&&!t.some(e=>e.startColumn<=n&&n<e.endColumn))return!1;return!0}function G(e,t){let n=new Map,r=new Map;function i(e){if(e.type!==`comment`&&e.type!==`line_comment`&&e.type!==`block_comment`){if(g.has(e.type)){$(r,t.slice(e.startIndex,e.endIndex));return}if(e.childCount===0){let i=t.slice(e.startIndex,e.endIndex);h.has(e.type)?$(r,i):(m.has(i)||m.has(e.type))&&Se(e,i)&&$(n,i||e.type);return}for(let t of e.children)i(t)}}return i(e),K({distinctOperators:n.size,distinctOperands:r.size,totalOperators:we(n.values()),totalOperands:we(r.values())})}function K(e){let{distinctOperators:t,distinctOperands:n,totalOperators:r,totalOperands:i}=e,a=t+n,o=r+i,s=a===0?0:o*Math.log2(a);return{distinctOperators:t,distinctOperands:n,totalOperators:r,totalOperands:i,vocabulary:a,length:o,volume:s,effort:(n===0?0:t/2*(i/n))*s}}const pe=new Set([`identifier`,`property_identifier`,`field_identifier`,`type_identifier`,`constant`,`instance_variable`,`class_variable`,`global_variable`]);function me(e){let t=[];return q(e,t,new Map),Int32Array.from(t)}function q(e,t,r){if(e.type!==`comment`&&e.type!==`line_comment`&&e.type!==`block_comment`){if(g.has(e.type)){t.push(n(e.type));return}if(e.childCount>0){for(let n of e.children)q(n,t,r);return}if(pe.has(e.type)){let i=r.get(e.text);i===void 0&&(i=r.size,r.set(e.text,i)),t.push(n(`id${i}`));return}t.push(n(h.has(e.type)?e.type:e.text))}}function he(e){let t=ye(e);if(t)return t;let n=e.childForFieldName(`name`);if(n)return n.text;let r=ge(e);if(r)return r;let i=e.parent;if(i){if(e.type===`closure_expression`&&i.type===`let_declaration`){let e=i.childForFieldName(`pattern`);return e?.type===`identifier`?e.text:void 0}return e.type===`lambda_expression`&&i.type===`init_declarator`?J(i.childForFieldName(`declarator`)):e.type===`func_literal`&&i.type===`expression_list`?ve(e,i):e.type===`lambda`&&i.type===`assignment`?X(i):(e.type===`block`||e.type===`do_block`)&&_e(i)?i.parent?.type===`assignment`?X(i.parent):void 0:i.childForFieldName(`name`)?.text}}function ge(e){return J(e.childForFieldName(`declarator`))}function J(e){let t=e;for(;t;)switch(t.type){case`identifier`:case`field_identifier`:case`type_identifier`:case`destructor_name`:case`operator_name`:return t.text;case`operator_cast`:return`operator ${t.childForFieldName(`type`)?.text??``}`.trimEnd();case`template_function`:case`qualified_identifier`:t=t.childForFieldName(`name`);break;default:t=Y(t)}}function Y(e){let t=e.childForFieldName(`declarator`);if(t)return t;if(e.type===`reference_declarator`||e.type===`parenthesized_declarator`)return e.namedChild(0)??void 0}function X(e){let t=e.childForFieldName(`left`);return t?.type===`identifier`||t?.type===`constant`?t.text:void 0}function _e(e){if(e.type!==`call`||e.childForFieldName(`receiver`))return!1;let t=e.childForFieldName(`method`);return t?.type===`identifier`&&(t.text===`lambda`||t.text===`proc`)}function ve(e,t){let n=t.parent,r=t.namedChildren.filter(e=>e.type!==`comment`).findIndex(t=>t.id===e.id);if(!(!n||r===-1)){if(n.type===`short_var_declaration`){let e=n.childForFieldName(`left`)?.namedChildren.filter(e=>e.type!==`comment`);return Z(e?.[r])}if(n.type===`var_spec`){let e=Q(n,`name`)[r];return Z(e)}}}function Z(e){return e?.type===`identifier`&&e.text!==`_`?e.text:void 0}function ye(e){let t=e;for(;t;){let e=t.parent,n=e?.parent;if(e?.type!==`arguments`||n?.type!==`call_expression`||!be(n))return;let r=n.parent;if(r?.type===`variable_declarator`)return r.childForFieldName(`name`)?.text;t=n}}function be(e){let t=e.childForFieldName(`function`)??e.namedChild(0);return t?.text===`memo`||t?.text===`React.memo`||t?.text===`forwardRef`||t?.text===`React.forwardRef`}const xe=new Set([`ternary_expression`,`conditional_expression`,`conditional`,`try_expression`,`conditional_type`]);function Se(e,t){if(t===`@`){let t=e.parent?.type;return t===`binary_operator`||t===`augmented_assignment`}if(t!==`?`)return!0;let n=e.parent?.type;return n!==void 0&&xe.has(n)}function Q(e,t){let n=[];for(let r=0;r<e.childCount;r+=1){let i=e.child(r);i&&e.fieldNameForChild(r)===t&&n.push(i)}return n}function $(e,t){e.set(t,(e.get(t)??0)+1)}function Ce(e){return e.length===0?0:Math.max(...e.map(e=>e.cognitiveComplexity))}function we(e){let t=0;for(let n of e)t+=n;return t}export{_ as TreeMeasurer,w as collectCrossFileDuplicationFileData,S as collectDuplicationCandidates,C as collectFunctionTokenSequences,b as defaultMeasurer,x as measureCode};
|
|
1
|
+
import{createLanguageRegistry as e}from"./languages.js";import{collectCrossFileDataNative as t,collectFunctionTokenSequencesNative as n,measureCodeNative as r}from"./nativeMetrics.js";var i=class{registry=e();getSupportedLanguages(){return[...new Set([...this.registry.values()].map(e=>e.name))]}measure(e,t){let n=this.resolveLanguage(t.language),i=t.includeSyntaxTree??!1;return a(r(e,n.name,i,t.duplication),i)}collectDuplicationCandidates(e,t){return this.collectCrossFileDuplicationFileData(e,t).candidates}collectCrossFileDuplicationFileData(e,n){let r=this.resolveLanguage(n.language),i=t(e,r.name,n.duplication?.minTokens);return{candidates:i.candidates,tokens:i.tokens,containerStatements:i.containerStatements,codeLineNumbers:new Set(i.codeLineNumbers)}}collectFunctionTokenSequences(e,t){let r=this.resolveLanguage(t.language);return n(e,r.name)}resolveLanguage(e){let t=this.registry.get(e);if(!t)throw Error(`Unsupported language: ${e}`);return t}};function a(e,t){return{language:e.language,bytes:e.bytes,lines:e.lines,functions:e.functions.map(e=>({name:e.name,nodeType:e.nodeType,startLine:e.startLine,startColumn:e.startColumn,endLine:e.endLine,cognitiveComplexity:e.cognitiveComplexity,nestingDepth:e.nestingDepth,ncss:e.ncss,parameterCount:e.parameterCount,halstead:o(e.halsteadCounts),depDegree:e.depDegree})),cognitiveComplexity:e.cognitiveComplexity,maxCognitiveComplexity:e.maxCognitiveComplexity,nestingDepth:e.nestingDepth,ncssCount:e.ncssCount,duplication:e.duplication,halstead:o(e.halsteadCounts),syntaxTree:t?e.syntaxTree:void 0}}function o(e){let{distinctOperators:t,distinctOperands:n,totalOperators:r,totalOperands:i}=e,a=t+n,o=r+i,s=a===0?0:o*Math.log2(a);return{distinctOperators:t,distinctOperands:n,totalOperators:r,totalOperands:i,vocabulary:a,length:o,volume:s,effort:(n===0?0:t/2*(i/n))*s}}const s=new i;function c(e,t){return s.measure(e,t)}function l(e,t){return s.collectDuplicationCandidates(e,t)}function u(e,t){return s.collectFunctionTokenSequences(e,t)}function d(e,t){return s.collectCrossFileDuplicationFileData(e,t)}export{i as TreeMeasurer,d as collectCrossFileDuplicationFileData,l as collectDuplicationCandidates,u as collectFunctionTokenSequences,s as defaultMeasurer,c as measureCode};
|
|
2
2
|
//# sourceMappingURL=metrics.js.map
|
package/dist/metrics.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metrics.js","names":[],"sources":["../src/metrics.ts"],"sourcesContent":["import Parser from 'tree-sitter';\nimport { measureDepDegree } from './depDegree.js';\nimport {\n collectCrossFileDuplicateCandidates,\n defaultDuplicationOptions,\n hashText,\n measureDuplication,\n type CrossFileDuplicateCandidate,\n type CrossFileDuplicationFileData,\n} from './duplication.js';\nimport { createLanguageRegistry } from './languages.js';\nimport { commentNodeTypes, countNcss, getNcssSets, invalidateNcssSetsCache, ncssContribution } from './ncss.js';\nimport { measureWithNativeBackend, type NativeHalsteadCounts, type NativeMetricsPayload } from './nativeMetrics.js';\nimport type {\n CodeMetrics,\n FunctionMetrics,\n HalsteadMetrics,\n LanguageDefinition,\n LanguageName,\n MeasureOptions,\n} from './types.js';\n\nconst booleanOperators = new Set(['&&', '||', 'and', 'or']);\nconst operatorTexts = new Set([\n '+',\n '-',\n '*',\n '/',\n '%',\n '**',\n '=',\n '+=',\n '-=',\n '*=',\n '/=',\n '%=',\n '==',\n '!=',\n '===',\n '!==',\n '<',\n '<=',\n '>',\n '>=',\n '!',\n '~',\n '&',\n '|',\n '^',\n '++',\n '--',\n '<<',\n '>>',\n '>>>',\n '=>',\n '**=',\n '<<=',\n '>>=',\n '>>>=',\n '&=',\n '|=',\n '^=',\n '&&=',\n '||=',\n '??=',\n '??',\n '?.',\n '?',\n '//',\n '//=',\n '@',\n '@=',\n ':=',\n '<-',\n '<=>',\n '=~',\n '..',\n '...',\n '..=',\n '&&',\n '||',\n '!~',\n '&^',\n '&^=',\n '&.',\n // Member access/qualification are classical Halstead operators (floats and range/spread tokens\n // are distinct leaves, so `.` cannot collide with them). `->` also captures Python/Rust\n // return-type arrows, consistent with the counted `=>`.\n '.',\n '->',\n '::',\n '->*',\n '.*',\n 'sizeof',\n 'alignof',\n 'defined?',\n 'as',\n // C++ alternative operator tokens parse as anonymous leaves like their symbolic forms.\n 'bitand',\n 'bitor',\n 'xor',\n 'compl',\n 'and_eq',\n 'or_eq',\n 'xor_eq',\n 'not_eq',\n 'and',\n 'or',\n 'not',\n 'in',\n 'is',\n 'instanceof',\n 'typeof',\n 'new',\n 'delete',\n 'return',\n 'throw',\n 'raise',\n 'yield',\n 'await',\n 'co_await',\n 'co_yield',\n 'co_return',\n 'break',\n 'continue',\n]);\n\nconst operandNodeTypes = new Set([\n 'identifier',\n 'property_identifier',\n 'field_identifier',\n 'type_identifier',\n 'constant',\n 'instance_variable',\n 'class_variable',\n 'global_variable',\n 'simple_symbol',\n 'self',\n 'this',\n 'super',\n // C/C++/Rust built-in types are leaves of their own node type, unlike Go's `type_identifier`.\n 'primitive_type',\n 'boolean_type',\n 'void_type',\n 'auto',\n 'number',\n 'integer',\n 'float',\n 'integer_literal',\n 'float_literal',\n 'int_literal',\n 'rune_literal',\n 'imaginary_literal',\n 'number_literal',\n 'decimal_integer_literal',\n 'hex_integer_literal',\n 'octal_integer_literal',\n 'binary_integer_literal',\n 'decimal_floating_point_literal',\n 'hex_floating_point_literal',\n 'string',\n 'string_literal',\n // Go raw strings are leaves with no content child, unlike Rust/C++ `raw_string_literal`s.\n 'raw_string_literal',\n 'string_fragment',\n 'multiline_string_fragment',\n 'string_content',\n 'raw_string_content',\n 'template_string',\n 'character_literal',\n 'char_literal',\n 'character',\n 'true',\n 'false',\n 'null',\n 'null_literal',\n 'undefined',\n 'nil',\n 'none',\n]);\n\n/**\n * Non-leaf literals counted as one Halstead operand without descending: Go interpreted strings\n * have no content leaf at all, and regex literals would otherwise count their `/` delimiters as\n * division operators. Interpolated regex contents are deliberately swallowed by the atom.\n */\n// C++ user-defined literals (`42_km`) are atomic too, keeping their suffix in the operand identity,\n// and multi-token built-in types (Java `int`, C `unsigned long`) wrap anonymous keyword leaves so\n// they count as one operand.\nconst atomicOperandNodeTypes = new Set([\n 'interpreted_string_literal',\n 'regex',\n 'user_defined_literal',\n 'integral_type',\n 'floating_point_type',\n 'sized_type_specifier',\n 'placeholder_type_specifier',\n]);\n\ninterface ComplexityResult {\n cognitiveComplexity: number;\n nestingDepth: number;\n}\n\ninterface CommentSpan {\n line: number;\n startColumn: number;\n endColumn: number;\n}\n\nexport class TreeMeasurer {\n private readonly registry = createLanguageRegistry();\n\n registerLanguage(language: LanguageDefinition): void {\n // Re-registering may carry mutated node-type arrays; drop derived caches so they rebuild.\n invalidateComplexityNodeSetsCache(language);\n invalidateNcssSetsCache(language);\n this.registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n this.registry.set(alias, language);\n }\n }\n\n getSupportedLanguages(): LanguageName[] {\n return [...new Set([...this.registry.values()].map((language) => language.name))];\n }\n\n measure(code: string, options: MeasureOptions): CodeMetrics {\n const language = this.registry.get(options.language);\n if (!language) {\n throw new Error(`Unsupported language: ${options.language}`);\n }\n\n // The native backend implements only the default duplication settings, so custom settings\n // measure through the TypeScript backend instead of silently ignoring them.\n const nativePayload = usesDefaultDuplicationOptions(options)\n ? measureWithNativeBackend(code, language, options.includeSyntaxTree ?? false)\n : undefined;\n if (nativePayload) {\n return assembleNativeMetrics(nativePayload, options.includeSyntaxTree ?? false);\n }\n\n const root = parseRoot(code, language);\n const functions = collectNodes(root, new Set(language.functionNodeTypes)).filter(\n (node) => !isLambdaBodyBlock(node) && isImplementedFunction(node)\n );\n const functionMetrics = collectFunctionMetrics(root, functions, language, code);\n const globalComplexity = measureComplexity(root, language);\n const { lines, codeLineNumbers } = classifyLines(code, root);\n\n return {\n language: language.name,\n bytes: Buffer.byteLength(code),\n lines,\n functions: functionMetrics,\n cognitiveComplexity: globalComplexity.cognitiveComplexity,\n maxCognitiveComplexity: maxCognitiveComplexity(functionMetrics),\n nestingDepth: globalComplexity.nestingDepth,\n ncssCount: countNcss(root, language),\n duplication: measureDuplication(root, codeLineNumbers, options.duplication),\n halstead: measureHalstead(root, code),\n syntaxTree: options.includeSyntaxTree ? root.toString() : undefined,\n };\n }\n\n /** Collects one file's duplicate candidates for cross-file clone detection. */\n collectDuplicationCandidates(code: string, options: MeasureOptions): CrossFileDuplicateCandidate[] {\n return this.collectCrossFileDuplicationFileData(code, options).candidates;\n }\n\n /**\n * Normalized token hash sequences of every function, index-parallel to the functions array of\n * measure(): identifiers are anonymized by first occurrence within the function, literals by\n * kind, and keywords/operators kept verbatim, so the regression gate can re-match renamed or\n * moved functions across two revisions by token-LCS similarity. Always measured by the\n * TypeScript backend.\n */\n collectFunctionTokenSequences(code: string, options: MeasureOptions): Int32Array[] {\n const { language, root } = this.parse(code, options);\n const functions = collectNodes(root, new Set(language.functionNodeTypes)).filter(\n (node) => !isLambdaBodyBlock(node) && isImplementedFunction(node)\n );\n return functions.map((node) => tokenizeFunction(node));\n }\n\n /**\n * Collects one file's duplicate candidates, normalized tokens, and statement structure for\n * cross-file clone detection with measureCrossFileDuplication. Always measured by the\n * TypeScript backend.\n */\n collectCrossFileDuplicationFileData(code: string, options: MeasureOptions): CrossFileDuplicationFileData {\n const { root } = this.parse(code, options);\n return {\n ...collectCrossFileDuplicateCandidates(root, options.duplication),\n // Lets cross-file line coverage count only code lines, like within-file coverage.\n codeLineNumbers: classifyLines(code, root).codeLineNumbers,\n };\n }\n\n private parse(code: string, options: MeasureOptions): { language: LanguageDefinition; root: Parser.SyntaxNode } {\n const language = this.registry.get(options.language);\n if (!language) {\n throw new Error(`Unsupported language: ${options.language}`);\n }\n return { language, root: parseRoot(code, language) };\n }\n}\n\nfunction parseRoot(code: string, language: LanguageDefinition): Parser.SyntaxNode {\n const parser = new Parser();\n parser.setLanguage(language.parserLanguage);\n return parser.parse(code, undefined, { bufferSize: code.length + 1 }).rootNode;\n}\n\nfunction usesDefaultDuplicationOptions(options: MeasureOptions): boolean {\n const duplication = options.duplication;\n return (\n (duplication?.minTokens ?? defaultDuplicationOptions.minTokens) === defaultDuplicationOptions.minTokens &&\n (duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens) === defaultDuplicationOptions.maxGapTokens &&\n (duplication?.minSimilarityPercent ?? defaultDuplicationOptions.minSimilarityPercent) ===\n defaultDuplicationOptions.minSimilarityPercent\n );\n}\n\nexport const defaultMeasurer = new TreeMeasurer();\n\nexport function measureCode(code: string, options: MeasureOptions): CodeMetrics {\n return defaultMeasurer.measure(code, options);\n}\n\n/** Standalone helper mirroring measureCode for the default measurer. */\nexport function collectDuplicationCandidates(code: string, options: MeasureOptions): CrossFileDuplicateCandidate[] {\n return defaultMeasurer.collectDuplicationCandidates(code, options);\n}\n\n/** Standalone helper mirroring measureCode for the default measurer. */\nexport function collectFunctionTokenSequences(code: string, options: MeasureOptions): Int32Array[] {\n return defaultMeasurer.collectFunctionTokenSequences(code, options);\n}\n\n/** Standalone helper mirroring measureCode for the default measurer. */\nexport function collectCrossFileDuplicationFileData(\n code: string,\n options: MeasureOptions\n): CrossFileDuplicationFileData {\n return defaultMeasurer.collectCrossFileDuplicationFileData(code, options);\n}\n\n/**\n * Completes a native measurement into CodeMetrics. The object is rebuilt field by field (rather\n * than spread from the parsed JSON) so the result has exactly the shape the TypeScript backend\n * produces, including explicitly-undefined optional keys.\n */\nfunction assembleNativeMetrics(payload: NativeMetricsPayload, includeSyntaxTree: boolean): CodeMetrics {\n return {\n language: payload.language,\n bytes: payload.bytes,\n lines: payload.lines,\n functions: payload.functions.map((fn) => ({\n name: fn.name,\n nodeType: fn.nodeType,\n startLine: fn.startLine,\n startColumn: fn.startColumn,\n endLine: fn.endLine,\n cognitiveComplexity: fn.cognitiveComplexity,\n nestingDepth: fn.nestingDepth,\n ncss: fn.ncss,\n parameterCount: fn.parameterCount,\n halstead: deriveHalsteadMetrics(fn.halsteadCounts),\n depDegree: fn.depDegree,\n })),\n cognitiveComplexity: payload.cognitiveComplexity,\n maxCognitiveComplexity: payload.maxCognitiveComplexity,\n nestingDepth: payload.nestingDepth,\n ncssCount: payload.ncssCount,\n duplication: payload.duplication,\n halstead: deriveHalsteadMetrics(payload.halsteadCounts),\n syntaxTree: includeSyntaxTree ? payload.syntaxTree : undefined,\n };\n}\n\nfunction collectFunctionMetrics(\n root: Parser.SyntaxNode,\n functions: Parser.SyntaxNode[],\n language: LanguageDefinition,\n code: string\n): FunctionMetrics[] {\n const bodyMetricsByNodeId = measureFunctionBodyMetrics(root, language);\n const { functionNodes } = getComplexityNodeSets(language);\n return functions.map((node) => {\n const bodyMetrics = bodyMetricsByNodeId.get(node.id);\n if (!bodyMetrics) {\n throw new Error(`missing body metrics for function node at line ${node.startPosition.row + 1}`);\n }\n return {\n name: findFunctionName(node),\n nodeType: node.type,\n startLine: node.startPosition.row + 1,\n startColumn: node.startPosition.column,\n endLine: node.endPosition.row + 1,\n cognitiveComplexity: bodyMetrics.cognitiveComplexity,\n nestingDepth: bodyMetrics.nestingDepth,\n ncss: bodyMetrics.ncss,\n parameterCount: countParameters(node),\n halstead: measureHalstead(node, code),\n depDegree: measureDepDegree(node, (nested) => isFunctionBoundary(nested, functionNodes)),\n };\n });\n}\n\n/** Counts declared parameters of a function/method, ignoring punctuation and comments. */\nfunction countParameters(node: Parser.SyntaxNode): number {\n // An unparenthesized arrow-function parameter (`x => x + 1`) is a bare `parameter` field.\n if (node.childForFieldName('parameter')) {\n return 1;\n }\n\n const parametersNode = findParametersNode(node);\n if (!parametersNode) {\n return 0;\n }\n\n // A Java bare lambda parameter (`x -> x + 1`) puts a lone identifier in the `parameters` field.\n if (parametersNode.type === 'identifier') {\n return 1;\n }\n\n // Ruby block-locals after `;` (`{ |x; memo| ... }`) occupy `locals` fields and receive no arguments.\n const blockLocalIds = new Set(findChildrenByFieldName(parametersNode, 'locals').map((child) => child.id));\n // Rust's `self` and Java's explicit receiver (`void f(X this)`) are not declared parameters, and\n // C/C++ `f(void)` declares none. A Ruby block parameter (`&blk`) binds the block, which call\n // sites pass outside the argument list, so it counts toward no arity.\n let count = 0;\n for (const child of parametersNode.namedChildren) {\n if (\n child.type === 'comment' ||\n child.type === 'self_parameter' ||\n child.type === 'receiver_parameter' ||\n child.type === 'block_parameter' ||\n // Python's PEP 570/3102 markers (`/`, `*`) separate parameter kinds but bind nothing.\n child.type === 'positional_separator' ||\n child.type === 'keyword_separator' ||\n blockLocalIds.has(child.id) ||\n isVoidParameter(child)\n ) {\n continue;\n }\n // Go declares several names per declaration (`a, b int`); each name is a parameter.\n count += child.type === 'parameter_declaration' ? Math.max(1, findChildrenByFieldName(child, 'name').length) : 1;\n }\n // C++ C-style varargs (`int f(int a, ...)`) leave `...` as an anonymous token, unlike C's named\n // `variadic_parameter`.\n const anonymousVariadicCount = parametersNode.children.filter(\n (child) => !child.isNamed && child.text === '...'\n ).length;\n return count + anonymousVariadicCount;\n}\n\n/** C/C++ `int f(void)` has a `parameter_declaration` whose type is a bare `void` with no declarator. */\nfunction isVoidParameter(node: Parser.SyntaxNode): boolean {\n return (\n node.type === 'parameter_declaration' &&\n node.childForFieldName('declarator') === null &&\n node.childForFieldName('type')?.text === 'void'\n );\n}\n\nfunction findParametersNode(node: Parser.SyntaxNode): Parser.SyntaxNode | undefined {\n const direct = node.childForFieldName('parameters');\n if (direct) {\n return direct;\n }\n\n // A Java compact constructor implicitly takes the record's components, declared on the\n // `record_declaration` two levels up (via `class_body`).\n if (node.type === 'compact_constructor_declaration') {\n return node.parent?.parent?.childForFieldName('parameters') ?? undefined;\n }\n\n // C/C++ parameters hang off the (possibly pointer/reference-wrapped) declarator, not the\n // definition itself.\n let declarator: Parser.SyntaxNode | null | undefined = node.childForFieldName('declarator');\n while (declarator) {\n const parameters = declarator.childForFieldName('parameters');\n if (parameters) {\n return parameters;\n }\n declarator = nextDeclarator(declarator);\n }\n\n return node.namedChildren.find((child) => child.type === 'formal_parameters' || child.type === 'parameter_list');\n}\n\n/**\n * C++ `function_definition` also covers pure-virtual/`= default`/`= delete` members; those have no\n * `body` and are signatures, not implementations, matching how TypeScript method signatures are\n * excluded. Java `method_declaration` is NOT here: PMD reports abstract/interface methods as\n * methods (NCSS 1), so bodyless Java methods stay in the function list.\n */\nconst bodyRequiredFunctionTypes = new Set([\n 'function_definition',\n 'constructor_declaration',\n 'compact_constructor_declaration',\n // Rust trait method signatures (`fn required(&self);`) never carry a body.\n 'function_signature_item',\n]);\n\nfunction isImplementedFunction(node: Parser.SyntaxNode): boolean {\n if (!bodyRequiredFunctionTypes.has(node.type) || node.childForFieldName('body') !== null) {\n return true;\n }\n\n // C++ constructor/destructor function-try-blocks carry their `try_statement` outside the\n // `body` field; they are implementations, unlike `= 0`/`= default`/`= delete` members.\n return node.namedChildren.some((child) => child.type === 'try_statement');\n}\n\n/**\n * A Ruby stabby lambda (`->(x) { ... }`) wraps its body in a `block`/`do_block`, which is itself a\n * function node type; the wrapper is part of the lambda, not a separate function, so it must not\n * count as one or act as a nested-function boundary.\n */\nfunction isLambdaBodyBlock(node: Parser.SyntaxNode): boolean {\n return (node.type === 'block' || node.type === 'do_block') && node.parent?.type === 'lambda';\n}\n\nfunction isFunctionBoundary(node: Parser.SyntaxNode, functionNodeTypes: Set<string>): boolean {\n return functionNodeTypes.has(node.type) && !isLambdaBodyBlock(node);\n}\n\n// Sonar cognitive complexity charges a switch/match once as a whole, not per case label. Only\n// named nodes are consulted, so anonymous keyword tokens never match.\nconst switchLikeNodeTypes = new Set([\n 'switch_statement',\n 'switch_expression',\n 'expression_switch_statement',\n 'type_switch_statement',\n 'select_statement',\n 'match_expression',\n 'match_statement',\n 'case',\n 'case_match',\n]);\n\n// Per-case decision nodes add no cognitive point because the switch itself carries the cost.\nconst caseClauseNodeTypes = new Set([\n 'case_clause',\n 'switch_case',\n 'switch_block_statement_group',\n 'switch_rule',\n 'case_statement',\n 'expression_case',\n 'type_case',\n 'communication_case',\n 'match_arm',\n 'when',\n 'in_clause',\n]);\n\nconst ifLikeNodeTypes = new Set(['if_statement', 'if_expression', 'if', 'unless']);\n\ninterface ComplexityNodeSets {\n functionNodes: Set<string>;\n decisionNodes: Set<string>;\n nestingNodes: Set<string>;\n}\n\n// Cached per language: measureComplexity runs once per function plus once per file, so per-call\n// Set construction would add a measurable constant factor on large files.\nconst complexityNodeSetsCache = new WeakMap<LanguageDefinition, ComplexityNodeSets>();\n\n/** Drops the cached sets so a re-registered (possibly mutated) definition rebuilds them. */\nfunction invalidateComplexityNodeSetsCache(language: LanguageDefinition): void {\n complexityNodeSetsCache.delete(language);\n}\n\nfunction getComplexityNodeSets(language: LanguageDefinition): ComplexityNodeSets {\n let sets = complexityNodeSetsCache.get(language);\n if (!sets) {\n sets = {\n functionNodes: new Set(language.functionNodeTypes),\n decisionNodes: new Set(language.decisionNodeTypes),\n nestingNodes: new Set(language.nestingNodeTypes),\n };\n complexityNodeSetsCache.set(language, sets);\n }\n return sets;\n}\n\ninterface FunctionBodyMetrics {\n cognitiveComplexity: number;\n nestingDepth: number;\n ncss: number;\n}\n\n/** Accumulator for one function body during measureFunctionBodyMetrics' post-order pass. */\ninterface FunctionBodyFrame {\n cognitiveComplexity: number;\n /** Count of `1 + nesting` cognitive increments, for re-basing on hoist into the parent frame. */\n nestingSensitiveCount: number;\n nestingDepth: number;\n ncss: number;\n hasOwnNcssContribution: boolean;\n /** Cognitive nesting (structural nesting + function/class bonuses) carried into this body. */\n entryCognitiveNesting: number;\n /** Structural nesting carried into this body (bonuses excluded), for nesting depth. */\n entryStructuralNesting: number;\n}\n\nfunction createFrame(entryCognitiveNesting: number, entryStructuralNesting: number): FunctionBodyFrame {\n return {\n cognitiveComplexity: 0,\n nestingSensitiveCount: 0,\n nestingDepth: 0,\n ncss: 0,\n hasOwnNcssContribution: false,\n entryCognitiveNesting,\n entryStructuralNesting,\n };\n}\n\n/**\n * Per-function complexity and NCSS for every function boundary, in one post-order pass so each\n * node is visited once instead of once per enclosing function (issue #35). A function's metrics\n * are its own-body contributions plus, per directly nested function, that function's\n * already-computed totals: NCSS hoists as-is; cognitive complexity re-bases the nested function's\n * nesting-sensitive increments (each worth `1 + nesting`) by the nesting offset at the embedding\n * site, while flat increments (else branches, boolean-operator sequences, chain continuations,\n * jumps, guards) hoist unchanged; nesting depth describes the own body only, so it does not hoist.\n */\nfunction measureFunctionBodyMetrics(\n root: Parser.SyntaxNode,\n language: LanguageDefinition\n): Map<number, FunctionBodyMetrics> {\n const { functionNodes, decisionNodes, nestingNodes } = getComplexityNodeSets(language);\n const { countable, containers } = getNcssSets(language);\n const results = new Map<number, FunctionBodyMetrics>();\n // frames[0] is a sentinel for top-level code; its accumulation is discarded.\n const frames: FunctionBodyFrame[] = [createFrame(0, 0)];\n\n function visit(\n current: Parser.SyntaxNode,\n currentNesting: number,\n functionNestingBonus: number,\n insideFunction: boolean,\n insideNestedRegion: boolean,\n insideChargedClassBody: boolean\n ): void {\n // A class body nested in a function (anonymous/local classes) raises the cognitive nesting\n // level once for everything inside it — PMD charges the class body, not the methods it holds\n // (verified: an anonymous-class instance initializer's `if` costs 1 + 1 nesting), so methods\n // directly inside a charged class body skip the function-boundary bonus.\n const isChargedClassBody = current.type === 'class_body' && insideFunction;\n if (isChargedClassBody) {\n insideNestedRegion = true;\n functionNestingBonus += 1;\n }\n const opensFrame = isFunctionBoundary(current, functionNodes);\n if (opensFrame) {\n if (insideFunction && !insideChargedClassBody) {\n functionNestingBonus += 1;\n }\n insideFunction = true;\n }\n // The node's own increments target the frame it is embedded in, not the one it opens; a\n // frame-opening or charged-class-body node contributes nothing to that frame's own body\n // (nesting), matching the per-function traversal this pass replaces.\n const frame = frames.at(-1) as FunctionBodyFrame;\n const relativeNesting = currentNesting + functionNestingBonus - frame.entryCognitiveNesting;\n const countsForOwnBody = !insideNestedRegion && !opensFrame;\n\n // Anonymous keyword tokens can share a type with named nodes (Ruby's `if` node contains an\n // `if` keyword token), so only named nodes count as decisions.\n const isDecision = current.isNamed && decisionNodes.has(current.type) && !isDefaultSwitchBranch(current);\n const isCaseClause = current.isNamed && caseClauseNodeTypes.has(current.type);\n // Ruby's `case ... else` arm is an `else` node; like every other language's default branch it\n // nests its contents inside the switch (it cannot go in the Ruby nesting set because\n // `if`/`begin` else branches would then double-nest under their already-nesting parent).\n const isNesting =\n current.isNamed &&\n (nestingNodes.has(current.type) ||\n (current.type === 'else' && (current.parent?.type === 'case' || current.parent?.type === 'case_match')));\n // `elsif`/`elif`/`else if` continue a flat chain: they add a decision without a nesting\n // surcharge, and their bodies stay at the chain's nesting level (Sonar cognitive-complexity\n // semantics); genuinely nested conditionals inside those bodies still deepen.\n const isContinuation = isDecision && isFlatChainContinuation(current);\n\n if (isDecision && !isCaseClause) {\n if (isContinuation) {\n frame.cognitiveComplexity += 1;\n } else {\n frame.cognitiveComplexity += 1 + relativeNesting;\n frame.nestingSensitiveCount += 1;\n }\n }\n if (current.isNamed && switchLikeNodeTypes.has(current.type)) {\n frame.cognitiveComplexity += 1 + relativeNesting;\n frame.nestingSensitiveCount += 1;\n }\n // A plain `else` branch adds one flat cognitive point; `else if` chains are charged on the\n // nested if instead.\n frame.cognitiveComplexity += countPlainElseBranches(current);\n // Sonar charges flow-breaking jumps: goto and labeled break/continue add one flat point.\n if (isFlowBreakingJump(current)) {\n frame.cognitiveComplexity += 1;\n }\n\n // A sequence of identical boolean operators reads as one condition, so only the operator\n // starting a sequence adds a cognitive point (Sonar spec).\n if (isBooleanOperator(current) && startsBooleanOperatorSequence(current)) {\n frame.cognitiveComplexity += 1;\n }\n\n // Pattern guards (Java `when`, Ruby `in y if ...`, Python `case n if ...`, Rust `n if ... =>`)\n // add one independent execution path without nesting.\n if (isPatternGuard(current)) {\n frame.cognitiveComplexity += 1;\n }\n\n const childNesting = isNesting && !isContinuation ? currentNesting + 1 : currentNesting;\n if (countsForOwnBody) {\n frame.nestingDepth = Math.max(frame.nestingDepth, childNesting - frame.entryStructuralNesting);\n }\n\n if (opensFrame) {\n frames.push(createFrame(childNesting + functionNestingBonus, childNesting));\n }\n // The node's NCSS contribution belongs to the innermost frame whose subtree holds it — the\n // frame the node opens, if any (per-function NCSS includes the declaration node itself).\n const ownNcss = ncssContribution(current, countable, containers);\n const ncssFrame = frames.at(-1) as FunctionBodyFrame;\n ncssFrame.ncss += ownNcss;\n if (opensFrame && ownNcss > 0) {\n ncssFrame.hasOwnNcssContribution = true;\n }\n\n for (const child of current.children) {\n visit(\n child,\n childNesting,\n functionNestingBonus,\n insideFunction,\n opensFrame ? false : insideNestedRegion,\n isChargedClassBody\n );\n }\n\n if (opensFrame) {\n const closed = frames.pop() as FunctionBodyFrame;\n results.set(current.id, {\n cognitiveComplexity: closed.cognitiveComplexity,\n nestingDepth: closed.nestingDepth,\n // A function node without a countable declaration of its own (arrow functions, lambdas,\n // blocks) still counts 1 for the declaration itself.\n ncss: closed.ncss + (closed.hasOwnNcssContribution ? 0 : 1),\n });\n const parent = frames.at(-1) as FunctionBodyFrame;\n parent.cognitiveComplexity +=\n closed.cognitiveComplexity +\n closed.nestingSensitiveCount * (closed.entryCognitiveNesting - parent.entryCognitiveNesting);\n parent.nestingSensitiveCount += closed.nestingSensitiveCount;\n parent.ncss += closed.ncss;\n }\n }\n\n visit(root, 0, 0, false, false, false);\n return results;\n}\n\n/**\n * File-level complexity over the whole tree. Cognitive complexity charges nested function/lambda\n * content one nesting level deeper per function boundary crossed (Sonar spec); nesting depth\n * counts every node once.\n */\nfunction measureComplexity(node: Parser.SyntaxNode, language: LanguageDefinition): ComplexityResult {\n let cognitiveComplexity = 0;\n let nestingDepth = 0;\n const { functionNodes, decisionNodes, nestingNodes } = getComplexityNodeSets(language);\n\n function visit(\n current: Parser.SyntaxNode,\n currentNesting: number,\n functionNestingBonus: number,\n insideFunction: boolean,\n insideChargedClassBody: boolean\n ): void {\n // A class body nested in a function (anonymous/local classes) raises the cognitive nesting\n // level once for everything inside it — PMD charges the class body, not the methods it holds,\n // so methods directly inside a charged class body skip the function-boundary bonus.\n const isChargedClassBody = current.type === 'class_body' && insideFunction;\n if (isChargedClassBody) {\n functionNestingBonus += 1;\n }\n if (isFunctionBoundary(current, functionNodes)) {\n if (insideFunction && !insideChargedClassBody) {\n functionNestingBonus += 1;\n }\n insideFunction = true;\n }\n const cognitiveNesting = currentNesting + functionNestingBonus;\n\n // Anonymous keyword tokens can share a type with named nodes (Ruby's `if` node contains an\n // `if` keyword token), so only named nodes count as decisions.\n const isDecision = current.isNamed && decisionNodes.has(current.type) && !isDefaultSwitchBranch(current);\n const isCaseClause = current.isNamed && caseClauseNodeTypes.has(current.type);\n // Ruby's `case ... else` arm is an `else` node; like every other language's default branch it\n // nests its contents inside the switch (it cannot go in the Ruby nesting set because\n // `if`/`begin` else branches would then double-nest under their already-nesting parent).\n const isNesting =\n current.isNamed &&\n (nestingNodes.has(current.type) ||\n (current.type === 'else' && (current.parent?.type === 'case' || current.parent?.type === 'case_match')));\n // `elsif`/`elif`/`else if` continue a flat chain: they add a decision without a nesting\n // surcharge, and their bodies stay at the chain's nesting level (Sonar cognitive-complexity\n // semantics); genuinely nested conditionals inside those bodies still deepen.\n const isContinuation = isDecision && isFlatChainContinuation(current);\n\n if (isDecision && !isCaseClause) {\n cognitiveComplexity += isContinuation ? 1 : 1 + cognitiveNesting;\n }\n if (current.isNamed && switchLikeNodeTypes.has(current.type)) {\n cognitiveComplexity += 1 + cognitiveNesting;\n }\n // A plain `else` branch adds one flat cognitive point; `else if` chains are charged on the\n // nested if instead.\n cognitiveComplexity += countPlainElseBranches(current);\n // Sonar charges flow-breaking jumps: goto and labeled break/continue add one flat point.\n if (isFlowBreakingJump(current)) {\n cognitiveComplexity += 1;\n }\n\n // A sequence of identical boolean operators reads as one condition, so only the operator\n // starting a sequence adds a cognitive point (Sonar spec).\n if (isBooleanOperator(current) && startsBooleanOperatorSequence(current)) {\n cognitiveComplexity += 1;\n }\n\n // Pattern guards (Java `when`, Ruby `in y if ...`, Python `case n if ...`, Rust `n if ... =>`)\n // add one independent execution path without nesting.\n if (isPatternGuard(current)) {\n cognitiveComplexity += 1;\n }\n\n const childNesting = isNesting && !isContinuation ? currentNesting + 1 : currentNesting;\n nestingDepth = Math.max(nestingDepth, childNesting);\n\n for (const child of current.children) {\n visit(child, childNesting, functionNestingBonus, insideFunction, isChargedClassBody);\n }\n }\n\n for (const child of node.children) {\n visit(child, 0, 0, false, false);\n }\n\n return { cognitiveComplexity, nestingDepth };\n}\n\n/**\n * Plain else branches attached to `current`: an `else_clause`/Ruby `else` whose branch is not an\n * `else if` continuation, or a bare Java/Go `alternative:` statement without a clause wrapper.\n */\nfunction countPlainElseBranches(current: Parser.SyntaxNode): number {\n if (!current.isNamed) {\n return 0;\n }\n if (current.type === 'else') {\n // A Ruby `case ... else` is the default arm of a switch, which already counts as a whole\n // (sonar-ruby models it as a match case, not an else branch); `if`/`unless`/`begin` else\n // branches count one point each.\n return current.parent?.type === 'case' || current.parent?.type === 'case_match' ? 0 : 1;\n }\n if (current.type === 'else_clause') {\n return current.namedChildren.some((child) => ifLikeNodeTypes.has(child.type)) ? 0 : 1;\n }\n if (current.type !== 'if_statement' && current.type !== 'if_expression') {\n return 0;\n }\n let count = 0;\n for (let index = 0; index < current.childCount; index += 1) {\n const child = current.child(index);\n if (\n child &&\n current.fieldNameForChild(index) === 'alternative' &&\n child.type !== 'else_clause' &&\n child.type !== 'elif_clause' &&\n !ifLikeNodeTypes.has(child.type)\n ) {\n count += 1;\n }\n }\n return count;\n}\n\n/** goto, and break/continue that jump to a label (their only named child is the label). */\nfunction isFlowBreakingJump(node: Parser.SyntaxNode): boolean {\n if (!node.isNamed) {\n return false;\n }\n if (node.type === 'goto_statement') {\n return true;\n }\n // Rust jumps are expressions; `break value` carries a named expression child, so only an\n // explicit `label` child marks a labeled jump.\n if (node.type === 'break_expression' || node.type === 'continue_expression') {\n return node.namedChildren.some((child) => child.type === 'label' || child.type === 'loop_label');\n }\n // Comments are named children too (`break /* done */;`), so only non-comment children mark a\n // label.\n return (\n (node.type === 'break_statement' || node.type === 'continue_statement') &&\n node.namedChildren.some((child) => !commentNodeTypes.has(child.type))\n );\n}\n\n// Wrappers that are transparent when locating the enclosing boolean operation: PMD/Sonar keep a\n// sequence continuous across parentheses (`a && (b && c)` costs one point).\nconst parenthesizedNodeTypes = new Set(['parenthesized_expression', 'parenthesized_statements']);\n\n/**\n * Whether this boolean operator token starts a new sequence, i.e. its binary node is the root of a\n * run of same-operator binaries (possibly through parentheses). Only the root operator counts one\n * cognitive point: `a && b && c` and `a && (b && c)` cost one, `a && b || c` costs two, matching\n * the Sonar specification and PMD 7.26.0.\n */\nfunction startsBooleanOperatorSequence(token: Parser.SyntaxNode): boolean {\n const binary = token.parent;\n if (!binary) {\n return true;\n }\n let ancestor = binary.parent;\n while (ancestor && parenthesizedNodeTypes.has(ancestor.type)) {\n ancestor = ancestor.parent;\n }\n if (!ancestor || ancestor.type !== binary.type) {\n return true;\n }\n return normalizeBooleanOperator(findBooleanOperatorText(ancestor)) !== normalizeBooleanOperator(token.text);\n}\n\n/** C++ `and`/`or` are alternative spellings of `&&`/`||`, so mixing them keeps one sequence. */\nfunction normalizeBooleanOperator(text: string | undefined): string | undefined {\n if (text === 'and') {\n return '&&';\n }\n if (text === 'or') {\n return '||';\n }\n return text;\n}\n\nfunction findBooleanOperatorText(binaryNode: Parser.SyntaxNode): string | undefined {\n const operator = binaryNode.childForFieldName('operator');\n if (operator) {\n return operator.text;\n }\n return binaryNode.children.find((child) => !child.isNamed && booleanOperators.has(child.text))?.text;\n}\n\n/** Java `guard`, Ruby `if_guard`, Python `if_clause`, and Rust guards inside `match_pattern`. */\nfunction isPatternGuard(node: Parser.SyntaxNode): boolean {\n if (!node.isNamed) {\n return false;\n }\n if (node.type === 'guard' || node.type === 'if_guard' || node.type === 'unless_guard' || node.type === 'if_clause') {\n return true;\n }\n return node.type === 'match_pattern' && node.children.some((child) => !child.isNamed && child.type === 'if');\n}\n\n/** Ruby `elsif`, Python `elif`, and `else if` (an if node in an else/alternative position). */\nfunction isFlatChainContinuation(node: Parser.SyntaxNode): boolean {\n if (node.type === 'elsif' || node.type === 'elif_clause') {\n return true;\n }\n if (node.type !== 'if_statement' && node.type !== 'if_expression' && node.type !== 'if') {\n return false;\n }\n const parent = node.parent;\n if (!parent) {\n return false;\n }\n // JS/C/C++/Rust wrap `else if` in an else clause; Java/Go put it directly in `alternative`.\n return parent.type === 'else_clause' || parent.childForFieldName('alternative')?.id === node.id;\n}\n\n/**\n * C/C++ `default:` shares the `case_statement` node type with `case` (only `case` has a `value`\n * field), and Java's default group/rule carries an expressionless `switch_label`; a default branch\n * adds no decision, though its contents still nest inside the switch like any other arm.\n */\nfunction isDefaultSwitchBranch(node: Parser.SyntaxNode): boolean {\n if (node.type === 'case_statement') {\n return node.childForFieldName('value') === null;\n }\n\n if (node.type === 'switch_block_statement_group' || node.type === 'switch_rule') {\n const label = node.namedChildren.find((child) => child.type === 'switch_label');\n return label !== undefined && label.namedChildCount === 0;\n }\n\n // Python `case _:` / `case y:` and Rust `_ =>` fallback arms are unconditional like `default`\n // (a bare Python name is always a capture); a guard is charged separately as a flat decision,\n // so the arm itself still adds nothing. Rust bare identifiers are NOT suppressed: they can name\n // constants or unit variants, which the grammar cannot distinguish from captures.\n if (node.type === 'case_clause' || node.type === 'match_arm') {\n const pattern = node.namedChildren.find((child) => child.type === 'case_pattern' || child.type === 'match_pattern');\n if (!pattern) {\n return false;\n }\n if (pattern.child(0)?.type === '_' && (pattern.childCount === 1 || pattern.child(1)?.type === 'if')) {\n return true;\n }\n const soleChild = pattern.namedChildCount === 1 ? pattern.namedChild(0) : undefined;\n return (\n node.type === 'case_clause' &&\n soleChild?.type === 'dotted_name' &&\n soleChild.namedChildCount === 1 &&\n soleChild.namedChild(0)?.type === 'identifier'\n );\n }\n\n // Ruby `in y` binds unconditionally (bare lowercase names are variable captures; constants and\n // literals are tests).\n if (node.type === 'in_clause') {\n return node.namedChild(0)?.type === 'identifier';\n }\n\n return false;\n}\n\n/** Parents under which `&&`/`||`/`and`/`or` tokens are actual boolean operators. */\nconst booleanOperatorParentTypes = new Set(['binary_expression', 'binary', 'boolean_operator']);\n\n/**\n * The parent guard is required because the same tokens appear in non-boolean syntax: C++ rvalue\n * references (`int&&`), ref-qualifiers, `operator&&`, and Rust's empty closure parameter list\n * (`|| 5`) must not count as decisions.\n */\nfunction isBooleanOperator(node: Parser.SyntaxNode): boolean {\n if (node.isNamed || !booleanOperators.has(node.text)) {\n return false;\n }\n\n const parent = node.parent;\n return parent !== null && booleanOperatorParentTypes.has(parent.type);\n}\n\nfunction collectNodes(root: Parser.SyntaxNode, nodeTypes: Set<string>): Parser.SyntaxNode[] {\n const nodes: Parser.SyntaxNode[] = [];\n\n function visit(node: Parser.SyntaxNode): void {\n if (nodeTypes.has(node.type)) {\n nodes.push(node);\n }\n\n for (const child of node.namedChildren) {\n visit(child);\n }\n }\n\n visit(root);\n return nodes;\n}\n\n/**\n * 1-based numbers of lines that are neither blank nor comment-only, matching measureLines'\n * classification so duplication line coverage and its code-line denominator agree.\n */\nfunction classifyLines(\n code: string,\n root: Parser.SyntaxNode\n): { lines: CodeMetrics['lines']; codeLineNumbers: Set<number> } {\n const sourceLines = code.length === 0 ? [] : code.split(/\\r\\n|\\n|\\r/);\n // Spans are bucketed by line so classification stays linear; scanning every span per line made\n // this pass quadratic on comment-heavy files.\n const commentSpansByLine = new Map<number, CommentSpan[]>();\n for (const span of collectCommentSpans(root)) {\n const spans = commentSpansByLine.get(span.line) ?? [];\n spans.push(span);\n commentSpansByLine.set(span.line, spans);\n }\n let blank = 0;\n let comment = 0;\n const codeLineNumbers = new Set<number>();\n\n for (const [index, line] of sourceLines.entries()) {\n if (line.trim() === '') {\n blank += 1;\n continue;\n }\n if (isCommentOnlyLine(line, commentSpansByLine.get(index) ?? [])) {\n comment += 1;\n } else {\n codeLineNumbers.add(index + 1);\n }\n }\n\n return {\n lines: {\n total: sourceLines.length,\n code: codeLineNumbers.size,\n comment,\n blank,\n },\n codeLineNumbers,\n };\n}\n\nfunction collectCommentSpans(root: Parser.SyntaxNode): CommentSpan[] {\n const spans: CommentSpan[] = [];\n\n function visit(node: Parser.SyntaxNode): void {\n if (node.type === 'comment' || node.type === 'line_comment' || node.type === 'block_comment') {\n for (let row = node.startPosition.row; row <= node.endPosition.row; row += 1) {\n spans.push({\n line: row,\n startColumn: row === node.startPosition.row ? node.startPosition.column : 0,\n endColumn: row === node.endPosition.row ? node.endPosition.column : Number.POSITIVE_INFINITY,\n });\n }\n }\n\n for (const child of node.namedChildren) {\n visit(child);\n }\n }\n\n visit(root);\n return spans;\n}\n\nfunction isCommentOnlyLine(line: string, relevantSpans: CommentSpan[]): boolean {\n if (relevantSpans.length === 0) {\n return false;\n }\n\n // A line may hold several comments (`/* one */ /* two */`), so every non-whitespace column must\n // be covered by the UNION of spans, not by a single span.\n for (let column = 0; column < line.length; column += 1) {\n if (/\\s/u.test(line[column] ?? ' ')) {\n continue;\n }\n if (!relevantSpans.some((span) => span.startColumn <= column && column < span.endColumn)) {\n return false;\n }\n }\n return true;\n}\n\nfunction measureHalstead(root: Parser.SyntaxNode, code: string): HalsteadMetrics {\n const operators = new Map<string, number>();\n const operands = new Map<string, number>();\n\n function visit(node: Parser.SyntaxNode): void {\n if (node.type === 'comment' || node.type === 'line_comment' || node.type === 'block_comment') {\n return;\n }\n\n if (atomicOperandNodeTypes.has(node.type)) {\n incrementCount(operands, code.slice(node.startIndex, node.endIndex));\n return;\n }\n\n // Operators are counted from leaf tokens only: keyword-named nodes (Ruby `return`, Python\n // `await`, ...) always contain a same-text anonymous keyword leaf, so counting the named node\n // as well would double-count.\n if (node.childCount === 0) {\n const text = code.slice(node.startIndex, node.endIndex);\n // Operands win over text matches so identifiers spelled like word operators (`cache.delete(...)`,\n // a Go parameter named `in`) stay operands; genuine keyword operators are anonymous leaves whose\n // types are never operand types. A blanket `isNamed` guard would break JS's named `optional_chain`.\n if (operandNodeTypes.has(node.type)) {\n incrementCount(operands, text);\n } else if ((operatorTexts.has(text) || operatorTexts.has(node.type)) && isCountableContextualToken(node, text)) {\n incrementCount(operators, text || node.type);\n }\n return;\n }\n\n for (const child of node.children) {\n visit(child);\n }\n }\n\n visit(root);\n\n return deriveHalsteadMetrics({\n distinctOperators: operators.size,\n distinctOperands: operands.size,\n totalOperators: sum(operators.values()),\n totalOperands: sum(operands.values()),\n });\n}\n\n/** Derives the full Halstead metrics from the four base counts (shared with the native backend). */\nfunction deriveHalsteadMetrics(counts: NativeHalsteadCounts): HalsteadMetrics {\n const { distinctOperators, distinctOperands, totalOperators, totalOperands } = counts;\n const vocabulary = distinctOperators + distinctOperands;\n const length = totalOperators + totalOperands;\n const volume = vocabulary === 0 ? 0 : length * Math.log2(vocabulary);\n const difficulty = distinctOperands === 0 ? 0 : (distinctOperators / 2) * (totalOperands / distinctOperands);\n const effort = difficulty * volume;\n\n return {\n distinctOperators,\n distinctOperands,\n totalOperators,\n totalOperands,\n vocabulary,\n length,\n volume,\n effort,\n };\n}\n\n/** Name-carrying leaf types anonymized by tokenizeFunction so consistent renames still match. */\nconst identifierLeafNodeTypes = new Set([\n 'identifier',\n 'property_identifier',\n 'field_identifier',\n 'type_identifier',\n 'constant',\n 'instance_variable',\n 'class_variable',\n 'global_variable',\n]);\n\n/** See TreeMeasurer.collectFunctionTokenSequences. */\nfunction tokenizeFunction(functionNode: Parser.SyntaxNode): Int32Array {\n const symbols: number[] = [];\n collectTokenSymbols(functionNode, symbols, new Map());\n return Int32Array.from(symbols);\n}\n\nfunction collectTokenSymbols(node: Parser.SyntaxNode, symbols: number[], idIndexByName: Map<string, number>): void {\n if (node.type === 'comment' || node.type === 'line_comment' || node.type === 'block_comment') {\n return;\n }\n if (atomicOperandNodeTypes.has(node.type)) {\n symbols.push(hashText(node.type));\n return;\n }\n if (node.childCount > 0) {\n for (const child of node.children) {\n collectTokenSymbols(child, symbols, idIndexByName);\n }\n return;\n }\n if (identifierLeafNodeTypes.has(node.type)) {\n let index = idIndexByName.get(node.text);\n if (index === undefined) {\n index = idIndexByName.size;\n idIndexByName.set(node.text, index);\n }\n symbols.push(hashText(`id${index}`));\n return;\n }\n // Remaining operand leaves are literals, normalized by kind; everything else (keywords,\n // operators, punctuation) is kept verbatim.\n symbols.push(hashText(operandNodeTypes.has(node.type) ? node.type : node.text));\n}\n\nfunction findFunctionName(node: Parser.SyntaxNode): string | undefined {\n const wrappedName = findWrappedComponentName(node);\n if (wrappedName) {\n return wrappedName;\n }\n\n const nameNode = node.childForFieldName('name');\n if (nameNode) {\n return nameNode.text;\n }\n\n // C/C++ definitions name the function inside the (possibly pointer-wrapped) declarator chain.\n const declaratorName = findDeclaratorName(node);\n if (declaratorName) {\n return declaratorName;\n }\n\n const parent = node.parent;\n if (!parent) {\n return undefined;\n }\n\n // A Rust closure bound to a simple `let` identifier (`let add = |x| ...;`) takes that identifier\n // as its name, mirroring how JS arrow functions assigned to a variable are named, so calls to the\n // binding resolve as intra-file edges.\n if (node.type === 'closure_expression' && parent.type === 'let_declaration') {\n const patternNode = parent.childForFieldName('pattern');\n return patternNode?.type === 'identifier' ? patternNode.text : undefined;\n }\n\n // A C++ lambda assigned to a variable (`auto f = [](int x) { ... };`) takes the variable name,\n // like Rust `let` closures above, so calls to the binding resolve as intra-file edges.\n if (node.type === 'lambda_expression' && parent.type === 'init_declarator') {\n return unwrapDeclaratorName(parent.childForFieldName('declarator'));\n }\n\n // A Go func literal bound via `add := func...` or `var add = func...` takes the identifier at\n // the same list position; unpaired or non-identifier targets stay unnamed.\n if (node.type === 'func_literal' && parent.type === 'expression_list') {\n return findGoFuncLiteralName(node, parent);\n }\n\n // Ruby lambdas assigned to a name (`choose = ->(x) {...}` / `ADD = lambda { ... }`) take that\n // name; Ruby assignments use the `left` field, and `lambda { }` blocks hang off a `call`.\n if (node.type === 'lambda' && parent.type === 'assignment') {\n return findRubyAssignmentName(parent);\n }\n if ((node.type === 'block' || node.type === 'do_block') && isRubyLambdaCall(parent)) {\n return parent.parent?.type === 'assignment' ? findRubyAssignmentName(parent.parent) : undefined;\n }\n\n const parentName = parent.childForFieldName('name');\n return parentName?.text;\n}\n\nfunction findDeclaratorName(node: Parser.SyntaxNode): string | undefined {\n return unwrapDeclaratorName(node.childForFieldName('declarator'));\n}\n\n/**\n * Unwraps a C/C++ declarator chain to the declared name, handling parenthesized declarators\n * (function pointers), qualified names, destructors, and operator overloads explicitly; a\n * rightmost-identifier fallback would pick up parameter names from nested `function_declarator`s.\n */\nfunction unwrapDeclaratorName(declarator: Parser.SyntaxNode | null): string | undefined {\n let current: Parser.SyntaxNode | null | undefined = declarator;\n while (current) {\n switch (current.type) {\n case 'identifier':\n case 'field_identifier':\n case 'type_identifier':\n case 'destructor_name':\n case 'operator_name': {\n return current.text;\n }\n // A C++ conversion operator (`operator int()`) is its own declarator node whose text spans\n // the parameter list and qualifiers; only `operator <type>` is the name.\n case 'operator_cast': {\n return `operator ${current.childForFieldName('type')?.text ?? ''}`.trimEnd();\n }\n // Template specializations (`id<int>`) and qualified names both carry a `name` field.\n case 'template_function':\n case 'qualified_identifier': {\n current = current.childForFieldName('name');\n break;\n }\n default: {\n current = nextDeclarator(current);\n }\n }\n }\n return undefined;\n}\n\n/**\n * Steps into the inner declarator; `reference_declarator` and `parenthesized_declarator` do not\n * expose a `declarator` field in tree-sitter-cpp, so their sole named child is the inner node.\n */\nfunction nextDeclarator(node: Parser.SyntaxNode): Parser.SyntaxNode | undefined {\n const direct = node.childForFieldName('declarator');\n if (direct) {\n return direct;\n }\n if (node.type === 'reference_declarator' || node.type === 'parenthesized_declarator') {\n return node.namedChild(0) ?? undefined;\n }\n return undefined;\n}\n\nfunction findRubyAssignmentName(assignment: Parser.SyntaxNode): string | undefined {\n const leftNode = assignment.childForFieldName('left');\n return leftNode?.type === 'identifier' || leftNode?.type === 'constant' ? leftNode.text : undefined;\n}\n\nfunction isRubyLambdaCall(node: Parser.SyntaxNode): boolean {\n if (node.type !== 'call' || node.childForFieldName('receiver')) {\n return false;\n }\n const methodNode = node.childForFieldName('method');\n return methodNode?.type === 'identifier' && (methodNode.text === 'lambda' || methodNode.text === 'proc');\n}\n\nfunction findGoFuncLiteralName(node: Parser.SyntaxNode, expressionList: Parser.SyntaxNode): string | undefined {\n const holder = expressionList.parent;\n // Comments interleave with expressions in the list but have no matching binding target, so\n // positions are aligned over non-comment children on both sides.\n const values = expressionList.namedChildren.filter((child) => child.type !== 'comment');\n const valueIndex = values.findIndex((child) => child.id === node.id);\n if (!holder || valueIndex === -1) {\n return undefined;\n }\n\n if (holder.type === 'short_var_declaration') {\n const targets = holder.childForFieldName('left')?.namedChildren.filter((child) => child.type !== 'comment');\n return asGoBindingName(targets?.[valueIndex]);\n }\n\n if (holder.type === 'var_spec') {\n const target = findChildrenByFieldName(holder, 'name')[valueIndex];\n return asGoBindingName(target);\n }\n\n return undefined;\n}\n\n/** Go's blank identifier `_` discards the value and creates no callable binding. */\nfunction asGoBindingName(target: Parser.SyntaxNode | undefined): string | undefined {\n return target?.type === 'identifier' && target.text !== '_' ? target.text : undefined;\n}\n\nfunction findWrappedComponentName(node: Parser.SyntaxNode): string | undefined {\n let current: Parser.SyntaxNode | undefined = node;\n while (current) {\n const argumentsNode: Parser.SyntaxNode | null = current.parent;\n const callNode: Parser.SyntaxNode | null | undefined = argumentsNode?.parent;\n if (argumentsNode?.type !== 'arguments' || callNode?.type !== 'call_expression') {\n return undefined;\n }\n\n if (!isReactComponentWrapperCall(callNode)) {\n return undefined;\n }\n\n const declaratorNode = callNode.parent;\n if (declaratorNode?.type === 'variable_declarator') {\n return declaratorNode.childForFieldName('name')?.text;\n }\n\n current = callNode;\n }\n\n return undefined;\n}\n\nfunction isReactComponentWrapperCall(node: Parser.SyntaxNode): boolean {\n const calleeNode = node.childForFieldName('function') ?? node.namedChild(0);\n return (\n calleeNode?.text === 'memo' ||\n calleeNode?.text === 'React.memo' ||\n calleeNode?.text === 'forwardRef' ||\n calleeNode?.text === 'React.forwardRef'\n );\n}\n\n/** Ternary/conditional and Rust try parents make `?` an operator; TS optional markers do not. */\nconst questionOperatorParentTypes = new Set([\n 'ternary_expression',\n 'conditional_expression',\n 'conditional',\n 'try_expression',\n // TypeScript conditional types (`T extends U ? X : Y`) select like a ternary.\n 'conditional_type',\n]);\n\nfunction isCountableContextualToken(node: Parser.SyntaxNode, text: string): boolean {\n if (text === '@') {\n // Python matrix multiplication only; decorator/annotation `@` marks are not operators.\n const parentType = node.parent?.type;\n return parentType === 'binary_operator' || parentType === 'augmented_assignment';\n }\n if (text !== '?') {\n return true;\n }\n const parentType = node.parent?.type;\n return parentType !== undefined && questionOperatorParentTypes.has(parentType);\n}\n\nfunction findChildrenByFieldName(node: Parser.SyntaxNode, fieldName: string): Parser.SyntaxNode[] {\n const children: Parser.SyntaxNode[] = [];\n for (let index = 0; index < node.childCount; index += 1) {\n const child = node.child(index);\n if (child && node.fieldNameForChild(index) === fieldName) {\n children.push(child);\n }\n }\n return children;\n}\n\nfunction incrementCount(map: Map<string, number>, value: string): void {\n map.set(value, (map.get(value) ?? 0) + 1);\n}\n\nfunction maxCognitiveComplexity(functions: FunctionMetrics[]): number {\n return functions.length === 0 ? 0 : Math.max(...functions.map((fn) => fn.cognitiveComplexity));\n}\n\nfunction sum(values: Iterable<number>): number {\n let total = 0;\n for (const value of values) {\n total += value;\n }\n return total;\n}\n"],"mappings":"+cAsBA,MAAM,EAAmB,IAAI,IAAI,CAAC,KAAM,KAAM,MAAO,IAAI,CAAC,EACpD,EAAgB,IAAI,IAAI,uZAsG9B,CAAC,EAEK,EAAmB,IAAI,IAAI,4qBAoDjC,CAAC,EAUK,EAAyB,IAAI,IAAI,CACrC,6BACA,QACA,uBACA,gBACA,sBACA,uBACA,4BACF,CAAC,EAaD,IAAa,EAAb,KAA0B,CACxB,SAA4B,EAAuB,EAEnD,iBAAiB,EAAoC,CAEnD,GAAkC,CAAQ,EAC1C,EAAwB,CAAQ,EAChC,KAAK,SAAS,IAAI,EAAS,KAAM,CAAQ,EACzC,IAAK,IAAM,KAAS,EAAS,SAAW,CAA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F,CAAC,EAED,SAAS,GAA2B,EAAyB,EAAuB,CAClF,GAAI,IAAS,IAAK,CAEhB,IAAM,EAAa,EAAK,QAAQ,KAChC,OAAO,IAAe,mBAAqB,IAAe,sBAC5D,CACA,GAAI,IAAS,IACX,MAAO,GAET,IAAM,EAAa,EAAK,QAAQ,KAChC,OAAO,IAAe,IAAA,IAAa,GAA4B,IAAI,CAAU,CAC/E,CAEA,SAAS,EAAwB,EAAyB,EAAwC,CAChG,IAAM,EAAgC,CAAC,EACvC,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAK,WAAY,GAAS,EAAG,CACvD,IAAM,EAAQ,EAAK,MAAM,CAAK,EAC1B,GAAS,EAAK,kBAAkB,CAAK,IAAM,GAC7C,EAAS,KAAK,CAAK,CAEvB,CACA,OAAO,CACT,CAEA,SAAS,EAAe,EAA0B,EAAqB,CACrE,EAAI,IAAI,GAAQ,EAAI,IAAI,CAAK,GAAK,GAAK,CAAC,CAC1C,CAEA,SAAS,GAAuB,EAAsC,CACpE,OAAO,EAAU,SAAW,EAAI,EAAI,KAAK,IAAI,GAAG,EAAU,IAAK,GAAO,EAAG,mBAAmB,CAAC,CAC/F,CAEA,SAAS,GAAI,EAAkC,CAC7C,IAAI,EAAQ,EACZ,IAAK,IAAM,KAAS,EAClB,GAAS,EAEX,OAAO,CACT"}
|
|
1
|
+
{"version":3,"file":"metrics.js","names":[],"sources":["../src/metrics.ts"],"sourcesContent":["import type { CrossFileDuplicateCandidate, CrossFileDuplicationFileData } from './duplication.js';\nimport { createLanguageRegistry } from './languages.js';\nimport {\n collectCrossFileDataNative,\n collectFunctionTokenSequencesNative,\n measureCodeNative,\n type NativeHalsteadCounts,\n type NativeMetricsPayload,\n} from './nativeMetrics.js';\nimport type { CodeMetrics, HalsteadMetrics, LanguageDefinition, LanguageName, MeasureOptions } from './types.js';\n\n/**\n * Measures code metrics for the built-in languages. Parsing and metric passes run in the bundled\n * Rust addon (tree-sitter); this class resolves language aliases, crosses the N-API boundary, and\n * derives the Halstead float metrics from the natively measured counts.\n */\nexport class TreeMeasurer {\n private readonly registry = createLanguageRegistry();\n\n getSupportedLanguages(): LanguageName[] {\n return [...new Set([...this.registry.values()].map((language) => language.name))];\n }\n\n measure(code: string, options: MeasureOptions): CodeMetrics {\n const language = this.resolveLanguage(options.language);\n const includeSyntaxTree = options.includeSyntaxTree ?? false;\n const payload = measureCodeNative(code, language.name, includeSyntaxTree, options.duplication);\n return assembleNativeMetrics(payload, includeSyntaxTree);\n }\n\n /** Collects one file's duplicate candidates for cross-file clone detection. */\n collectDuplicationCandidates(code: string, options: MeasureOptions): CrossFileDuplicateCandidate[] {\n return this.collectCrossFileDuplicationFileData(code, options).candidates;\n }\n\n /**\n * Collects one file's duplicate candidates, normalized tokens, and statement structure for\n * cross-file clone detection with measureCrossFileDuplication.\n */\n collectCrossFileDuplicationFileData(code: string, options: MeasureOptions): CrossFileDuplicationFileData {\n const language = this.resolveLanguage(options.language);\n const payload = collectCrossFileDataNative(code, language.name, options.duplication?.minTokens);\n return {\n candidates: payload.candidates,\n tokens: payload.tokens,\n containerStatements: payload.containerStatements,\n // Lets cross-file line coverage count only code lines, like within-file coverage.\n codeLineNumbers: new Set(payload.codeLineNumbers),\n };\n }\n\n /**\n * Normalized token hash sequences of every function, index-parallel to the functions array of\n * measure(): identifiers are anonymized by first occurrence within the function, literals by\n * kind, and keywords/operators kept verbatim, so the regression gate can re-match renamed or\n * moved functions across two revisions by token-LCS similarity.\n */\n collectFunctionTokenSequences(code: string, options: MeasureOptions): Int32Array[] {\n const language = this.resolveLanguage(options.language);\n return collectFunctionTokenSequencesNative(code, language.name);\n }\n\n private resolveLanguage(name: LanguageName): LanguageDefinition {\n const language = this.registry.get(name);\n if (!language) {\n throw new Error(`Unsupported language: ${name}`);\n }\n return language;\n }\n}\n\n/**\n * Completes a native measurement into CodeMetrics. The object is rebuilt field by field (rather\n * than spread from the parsed JSON) so the result has a stable shape, including\n * explicitly-undefined optional keys.\n */\nfunction assembleNativeMetrics(payload: NativeMetricsPayload, includeSyntaxTree: boolean): CodeMetrics {\n return {\n language: payload.language,\n bytes: payload.bytes,\n lines: payload.lines,\n functions: payload.functions.map((fn) => ({\n name: fn.name,\n nodeType: fn.nodeType,\n startLine: fn.startLine,\n startColumn: fn.startColumn,\n endLine: fn.endLine,\n cognitiveComplexity: fn.cognitiveComplexity,\n nestingDepth: fn.nestingDepth,\n ncss: fn.ncss,\n parameterCount: fn.parameterCount,\n halstead: deriveHalsteadMetrics(fn.halsteadCounts),\n depDegree: fn.depDegree,\n })),\n cognitiveComplexity: payload.cognitiveComplexity,\n maxCognitiveComplexity: payload.maxCognitiveComplexity,\n nestingDepth: payload.nestingDepth,\n ncssCount: payload.ncssCount,\n duplication: payload.duplication,\n halstead: deriveHalsteadMetrics(payload.halsteadCounts),\n syntaxTree: includeSyntaxTree ? payload.syntaxTree : undefined,\n };\n}\n\nfunction deriveHalsteadMetrics(counts: NativeHalsteadCounts): HalsteadMetrics {\n const { distinctOperators, distinctOperands, totalOperators, totalOperands } = counts;\n const vocabulary = distinctOperators + distinctOperands;\n const length = totalOperators + totalOperands;\n const volume = vocabulary === 0 ? 0 : length * Math.log2(vocabulary);\n const difficulty = distinctOperands === 0 ? 0 : (distinctOperators / 2) * (totalOperands / distinctOperands);\n const effort = difficulty * volume;\n\n return {\n distinctOperators,\n distinctOperands,\n totalOperators,\n totalOperands,\n vocabulary,\n length,\n volume,\n effort,\n };\n}\n\nexport const defaultMeasurer = new TreeMeasurer();\n\nexport function measureCode(code: string, options: MeasureOptions): CodeMetrics {\n return defaultMeasurer.measure(code, options);\n}\n\n/** Standalone helper mirroring measureCode for the default measurer. */\nexport function collectDuplicationCandidates(code: string, options: MeasureOptions): CrossFileDuplicateCandidate[] {\n return defaultMeasurer.collectDuplicationCandidates(code, options);\n}\n\n/** Standalone helper mirroring measureCode for the default measurer. */\nexport function collectFunctionTokenSequences(code: string, options: MeasureOptions): Int32Array[] {\n return defaultMeasurer.collectFunctionTokenSequences(code, options);\n}\n\n/** Standalone helper mirroring measureCode for the default measurer. */\nexport function collectCrossFileDuplicationFileData(\n code: string,\n options: MeasureOptions\n): CrossFileDuplicationFileData {\n return defaultMeasurer.collectCrossFileDuplicationFileData(code, options);\n}\n"],"mappings":"wLAgBA,IAAa,EAAb,KAA0B,CACxB,SAA4B,EAAuB,EAEnD,uBAAwC,CACtC,MAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,KAAK,SAAS,OAAO,CAAC,CAAC,CAAC,IAAK,GAAa,EAAS,IAAI,CAAC,CAAC,CAClF,CAEA,QAAQ,EAAc,EAAsC,CAC1D,IAAM,EAAW,KAAK,gBAAgB,EAAQ,QAAQ,EAChD,EAAoB,EAAQ,mBAAqB,GAEvD,OAAO,EADS,EAAkB,EAAM,EAAS,KAAM,EAAmB,EAAQ,WAC/C,EAAG,CAAiB,CACzD,CAGA,6BAA6B,EAAc,EAAwD,CACjG,OAAO,KAAK,oCAAoC,EAAM,CAAO,CAAC,CAAC,UACjE,CAMA,oCAAoC,EAAc,EAAuD,CACvG,IAAM,EAAW,KAAK,gBAAgB,EAAQ,QAAQ,EAChD,EAAU,EAA2B,EAAM,EAAS,KAAM,EAAQ,aAAa,SAAS,EAC9F,MAAO,CACL,WAAY,EAAQ,WACpB,OAAQ,EAAQ,OAChB,oBAAqB,EAAQ,oBAE7B,gBAAiB,IAAI,IAAI,EAAQ,eAAe,CAClD,CACF,CAQA,8BAA8B,EAAc,EAAuC,CACjF,IAAM,EAAW,KAAK,gBAAgB,EAAQ,QAAQ,EACtD,OAAO,EAAoC,EAAM,EAAS,IAAI,CAChE,CAEA,gBAAwB,EAAwC,CAC9D,IAAM,EAAW,KAAK,SAAS,IAAI,CAAI,EACvC,GAAI,CAAC,EACH,MAAU,MAAM,yBAAyB,GAAM,EAEjD,OAAO,CACT,CACF,EAOA,SAAS,EAAsB,EAA+B,EAAyC,CACrG,MAAO,CACL,SAAU,EAAQ,SAClB,MAAO,EAAQ,MACf,MAAO,EAAQ,MACf,UAAW,EAAQ,UAAU,IAAK,IAAQ,CACxC,KAAM,EAAG,KACT,SAAU,EAAG,SACb,UAAW,EAAG,UACd,YAAa,EAAG,YAChB,QAAS,EAAG,QACZ,oBAAqB,EAAG,oBACxB,aAAc,EAAG,aACjB,KAAM,EAAG,KACT,eAAgB,EAAG,eACnB,SAAU,EAAsB,EAAG,cAAc,EACjD,UAAW,EAAG,SAChB,EAAE,EACF,oBAAqB,EAAQ,oBAC7B,uBAAwB,EAAQ,uBAChC,aAAc,EAAQ,aACtB,UAAW,EAAQ,UACnB,YAAa,EAAQ,YACrB,SAAU,EAAsB,EAAQ,cAAc,EACtD,WAAY,EAAoB,EAAQ,WAAa,IAAA,EACvD,CACF,CAEA,SAAS,EAAsB,EAA+C,CAC5E,GAAM,CAAE,oBAAmB,mBAAkB,iBAAgB,iBAAkB,EACzE,EAAa,EAAoB,EACjC,EAAS,EAAiB,EAC1B,EAAS,IAAe,EAAI,EAAI,EAAS,KAAK,KAAK,CAAU,EAInE,MAAO,CACL,oBACA,mBACA,iBACA,gBACA,aACA,SACA,SACA,QAXiB,IAAqB,EAAI,EAAK,EAAoB,GAAM,EAAgB,IAC/D,CAW5B,CACF,CAEA,MAAa,EAAkB,IAAI,EAEnC,SAAgB,EAAY,EAAc,EAAsC,CAC9E,OAAO,EAAgB,QAAQ,EAAM,CAAO,CAC9C,CAGA,SAAgB,EAA6B,EAAc,EAAwD,CACjH,OAAO,EAAgB,6BAA6B,EAAM,CAAO,CACnE,CAGA,SAAgB,EAA8B,EAAc,EAAuC,CACjG,OAAO,EAAgB,8BAA8B,EAAM,CAAO,CACpE,CAGA,SAAgB,EACd,EACA,EAC8B,CAC9B,OAAO,EAAgB,oCAAoC,EAAM,CAAO,CAC1E"}
|
package/dist/nativeMetrics.cjs
CHANGED
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
"use strict";
|
|
1
|
+
"use strict";let e=require("node:module");function t(e,t,n,r){return JSON.parse(l().measureCodeNative(i(e),t,n,a(r?.minTokens),a(r?.maxGapTokens),a(r?.minSimilarityPercent)))}function n(e,t,n){return JSON.parse(l().collectCrossFileDataNative(i(e),t,a(n)))}function r(e,t){return JSON.parse(l().collectFunctionTokenSequencesNative(i(e),t)).map(e=>Int32Array.from(e))}function i(e){return e.isWellFormed()?e:e.toWellFormed()}function a(e){return e===void 0||Number.isNaN(e)?void 0:Math.min(Math.max(Math.trunc(e),0),4294967295)}var o=class extends Error{};let s,c;function l(){if(s)return s;if(c)throw c;let t=(0,e.createRequire)(require("url").pathToFileURL(__filename).href),n=[`code-gauge-${u()}`,`../native/code-gauge.node`],r=[];for(let e of n){let n;try{n=t(e)}catch(t){r.push(` ${e}: ${t instanceof Error?t.message.split(`
|
|
2
|
+
`)[0]:String(t)}`);continue}let i=n.payloadVersion?.();if(i!==4){r.push(` ${e}: payload version ${i??`unknown`} does not match the expected 4; rebuild the addon with \`bun run build-native\``);continue}return s=n,n}throw c=new o(`The code-gauge native addon is not available for ${u()}. Build it with \`node scripts/buildNative.mjs\` in the code-gauge package directory (requires a Rust toolchain); when installing with npm, also allow install scripts for code-gauge so its postinstall build can run.\n${r.join(`
|
|
3
|
+
`)}`),c}function u(){let e=`${process.platform}-${process.arch}`;return process.platform===`win32`?`${e}-msvc`:process.platform===`linux`?(process.report?.getReport())?.header?.glibcVersionRuntime?`${e}-gnu`:`${e}-musl`:e}exports.NativeAddonError=o,exports.collectCrossFileDataNative=n,exports.collectFunctionTokenSequencesNative=r,exports.measureCodeNative=t;
|
|
2
4
|
//# sourceMappingURL=nativeMetrics.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nativeMetrics.cjs","names":["
|
|
1
|
+
{"version":3,"file":"nativeMetrics.cjs","names":["createRequire"],"sources":["../src/nativeMetrics.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport type { CrossFileDuplicateCandidate, Token, TokenRange } from './duplication.js';\nimport type { CodeMetrics, DuplicationOptions, FunctionMetrics } from './types.js';\n\n/**\n * Halstead counts measured natively; the derived float metrics (volume, effort, ...) are\n * computed in TypeScript because they involve transcendental functions (log2) whose last-bit\n * results can differ between V8 and Rust's libm, and results must not depend on the Rust side's\n * libm build.\n */\nexport interface NativeHalsteadCounts {\n distinctOperators: number;\n distinctOperands: number;\n totalOperators: number;\n totalOperands: number;\n}\n\nexport interface NativeFunctionMetricsPayload extends Omit<FunctionMetrics, 'halstead'> {\n halsteadCounts: NativeHalsteadCounts;\n}\n\nexport interface NativeMetricsPayload extends Omit<CodeMetrics, 'halstead' | 'functions' | 'syntaxTree'> {\n functions: NativeFunctionMetricsPayload[];\n halsteadCounts: NativeHalsteadCounts;\n syntaxTree?: string;\n}\n\n/** One file's cross-file clone-detection contribution as serialized by the native addon. */\nexport interface NativeCrossFileDataPayload {\n candidates: CrossFileDuplicateCandidate[];\n tokens: Token[];\n containerStatements: TokenRange[][];\n /** 1-based lines that are neither blank nor comment-only, sorted ascending. */\n codeLineNumbers: number[];\n}\n\ninterface NativeBinding {\n measureCodeNative(\n code: string,\n language: string,\n includeSyntaxTree: boolean,\n minTokens?: number,\n maxGapTokens?: number,\n minSimilarityPercent?: number\n ): string;\n collectCrossFileDataNative(code: string, language: string, minTokens?: number): string;\n collectFunctionTokenSequencesNative(code: string, language: string): string;\n payloadVersion?(): number;\n}\n\n/**\n * Must equal `payload_version` in native/src/lib.rs. A previously built addon survives a\n * `git pull` untouched, so without this handshake it would silently return payloads missing\n * newer fields instead of failing with a clear rebuild message.\n */\nconst expectedPayloadVersion = 4;\n\n/** Measures one file via the native addon, returning the raw payload for assembly in metrics.ts. */\nexport function measureCodeNative(\n code: string,\n language: string,\n includeSyntaxTree: boolean,\n duplication?: DuplicationOptions\n): NativeMetricsPayload {\n return JSON.parse(\n loadBinding().measureCodeNative(\n toWellFormed(code),\n language,\n includeSyntaxTree,\n clampToU32(duplication?.minTokens),\n clampToU32(duplication?.maxGapTokens),\n clampToU32(duplication?.minSimilarityPercent)\n )\n ) as NativeMetricsPayload;\n}\n\n/** Collects one file's cross-file clone-detection contribution via the native addon. */\nexport function collectCrossFileDataNative(\n code: string,\n language: string,\n minTokens?: number\n): NativeCrossFileDataPayload {\n return JSON.parse(\n loadBinding().collectCrossFileDataNative(toWellFormed(code), language, clampToU32(minTokens))\n ) as NativeCrossFileDataPayload;\n}\n\n/** Collects normalized token hash sequences of every function via the native addon. */\nexport function collectFunctionTokenSequencesNative(code: string, language: string): Int32Array[] {\n const sequences = JSON.parse(\n loadBinding().collectFunctionTokenSequencesNative(toWellFormed(code), language)\n ) as number[][];\n return sequences.map((sequence) => Int32Array.from(sequence));\n}\n\n/**\n * Lone surrogates cannot cross the N-API boundary losslessly, so ill-formed strings (invalid\n * UTF-16 occasionally present in real-world files) are measured with U+FFFD replacements — the\n * same code units V8's own UTF-8 conversion would substitute.\n */\nfunction toWellFormed(code: string): string {\n return code.isWellFormed() ? code : code.toWellFormed();\n}\n\n/**\n * The duplication settings cross the boundary as u32, whose JavaScript conversion wraps modulo\n * 2^32 (2 ** 32 would become 0 and match everything). The public API accepts any safe integer, so\n * out-of-range values clamp to [0, u32::MAX] — no source can hold 2^32 tokens, so a clamped\n * threshold behaves identically to the requested one. NaN (e.g. `Number(unsetEnvVariable)`)\n * survives clamping arithmetic and would also convert to 0, so it is treated as an absent setting\n * instead.\n */\nfunction clampToU32(value: number | undefined): number | undefined {\n return value === undefined || Number.isNaN(value)\n ? undefined\n : Math.min(Math.max(Math.trunc(value), 0), 0xFF_FF_FF_FF);\n}\n\n/**\n * Raised when no usable native addon can be loaded. Every measurement fails identically until the\n * addon is built, so callers measuring many files (the CLI scan) treat it as fatal for the whole\n * run instead of recording one \"skipped\" entry per file.\n */\nexport class NativeAddonError extends Error {}\n\nlet cachedBinding: NativeBinding | undefined;\nlet cachedFailure: NativeAddonError | undefined;\n\nfunction loadBinding(): NativeBinding {\n if (cachedBinding) {\n return cachedBinding;\n }\n // The failure is memoized too: resolution (including platformTriplet's diagnostic-report call\n // on Linux) would otherwise repeat for every measured file of an already-failing run.\n if (cachedFailure) {\n throw cachedFailure;\n }\n // Resolved relative to this file, so both src/ (tests) and dist/ (build) find the addon.\n const requireNative = createRequire(import.meta.url);\n const specifiers = [\n // A prebuilt platform package, when published for this platform.\n `code-gauge-${platformTriplet()}`,\n // A locally built addon (`bun run build-native`).\n '../native/code-gauge.node',\n ];\n const failures: string[] = [];\n for (const specifier of specifiers) {\n let binding: NativeBinding;\n try {\n binding = requireNative(specifier) as NativeBinding;\n } catch (error) {\n failures.push(` ${specifier}: ${error instanceof Error ? error.message.split('\\n')[0] : String(error)}`);\n continue;\n }\n const version = binding.payloadVersion?.();\n if (version !== expectedPayloadVersion) {\n failures.push(\n ` ${specifier}: payload version ${version ?? 'unknown'} does not match the expected ` +\n `${expectedPayloadVersion}; rebuild the addon with \\`bun run build-native\\``\n );\n continue;\n }\n cachedBinding = binding;\n return binding;\n }\n cachedFailure = new NativeAddonError(\n `The code-gauge native addon is not available for ${platformTriplet()}. Build it with ` +\n '`node scripts/buildNative.mjs` in the code-gauge package directory (requires a Rust ' +\n 'toolchain); when installing with npm, also allow install scripts for code-gauge so its ' +\n `postinstall build can run.\\n${failures.join('\\n')}`\n );\n throw cachedFailure;\n}\n\n/**\n * The platform-package suffix in the napi-rs naming convention: Linux targets are qualified by\n * libc ABI (`linux-x64-gnu` / `linux-x64-musl`) because a glibc-linked addon cannot load on\n * Alpine/musl, and Windows by toolchain ABI (`win32-x64-msvc`), matching what napi-rs tooling\n * generates. Must match scripts/installNative.mjs and the build-native workflow's target list.\n */\nfunction platformTriplet(): string {\n const base = `${process.platform}-${process.arch}`;\n if (process.platform === 'win32') {\n return `${base}-msvc`;\n }\n if (process.platform !== 'linux') {\n return base;\n }\n // Musl builds of Node report no glibc runtime version; see napi-rs's isMusl detection.\n const report = process.report?.getReport() as { header?: { glibcVersionRuntime?: string } } | undefined;\n return report?.header?.glibcVersionRuntime ? `${base}-gnu` : `${base}-musl`;\n}\n"],"mappings":"0C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