code-gauge 1.11.1 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +38 -21
  2. package/dist/_virtual/_rolldown/runtime.cjs +1 -1
  3. package/dist/cli.cjs +3 -3
  4. package/dist/cli.cjs.map +1 -1
  5. package/dist/cli.js +3 -3
  6. package/dist/cli.js.map +1 -1
  7. package/dist/cliConfig.cjs +1 -1
  8. package/dist/cliConfig.cjs.map +1 -1
  9. package/dist/cliConfig.d.ts +9 -0
  10. package/dist/cliConfig.js +1 -1
  11. package/dist/cliConfig.js.map +1 -1
  12. package/dist/crossFileDuplication.cjs +2 -0
  13. package/dist/crossFileDuplication.cjs.map +1 -0
  14. package/dist/crossFileDuplication.d.ts +31 -0
  15. package/dist/crossFileDuplication.js +2 -0
  16. package/dist/crossFileDuplication.js.map +1 -0
  17. package/dist/duplicateSelection.cjs +2 -0
  18. package/dist/duplicateSelection.cjs.map +1 -0
  19. package/dist/duplicateSelection.d.ts +25 -0
  20. package/dist/duplicateSelection.js +2 -0
  21. package/dist/duplicateSelection.js.map +1 -0
  22. package/dist/duplication.cjs +1 -1
  23. package/dist/duplication.cjs.map +1 -1
  24. package/dist/duplication.d.ts +25 -5
  25. package/dist/duplication.js +1 -1
  26. package/dist/duplication.js.map +1 -1
  27. package/dist/index.cjs +1 -1
  28. package/dist/index.d.ts +5 -2
  29. package/dist/index.js +1 -1
  30. package/dist/languages.cjs +1 -1
  31. package/dist/languages.cjs.map +1 -1
  32. package/dist/languages.js +1 -1
  33. package/dist/languages.js.map +1 -1
  34. package/dist/metrics.cjs +2 -2
  35. package/dist/metrics.cjs.map +1 -1
  36. package/dist/metrics.d.ts +8 -0
  37. package/dist/metrics.js +2 -2
  38. package/dist/metrics.js.map +1 -1
  39. package/dist/nativeMetrics.cjs.map +1 -1
  40. package/dist/nativeMetrics.js.map +1 -1
  41. package/dist/ncss.cjs +2 -0
  42. package/dist/ncss.cjs.map +1 -0
  43. package/dist/ncss.d.ts +11 -0
  44. package/dist/ncss.js +2 -0
  45. package/dist/ncss.js.map +1 -0
  46. package/dist/types.d.ts +40 -1
  47. package/dist/typescriptProject.cjs.map +1 -1
  48. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"duplication.js","names":[],"sources":["../src/duplication.ts"],"sourcesContent":["import type Parser from 'tree-sitter';\nimport type { DuplicationMetrics } from './types.js';\n\n/**\n * Block-like nodes considered as whole-subtree duplicate candidates. Detection itself is\n * token-based, so this set only decides which subtrees are compared; Ruby's keyword-like node\n * types (`if`, `case`, ...) are safe here because only named nodes become candidates.\n */\nconst duplicateBlockTypes = new Set([\n 'statement_block',\n 'block',\n 'compound_statement',\n 'body_statement',\n 'constructor_body',\n 'do_block',\n 'if_statement',\n 'for_statement',\n 'for_in_statement',\n 'enhanced_for_statement',\n 'for_range_loop',\n 'while_statement',\n 'do_statement',\n 'try_statement',\n 'try_with_resources_statement',\n 'with_statement',\n 'switch_statement',\n 'switch_expression',\n 'switch_case',\n 'switch_block_statement_group',\n 'switch_rule',\n 'case_clause',\n 'case_statement',\n 'match_statement',\n 'match_arm',\n 'except_clause',\n 'catch_clause',\n 'finally_clause',\n 'elif_clause',\n 'ensure',\n 'expression_statement',\n 'return_statement',\n 'return_expression',\n 'if_expression',\n 'for_expression',\n 'while_expression',\n 'loop_expression',\n 'match_expression',\n 'jsx_element',\n 'jsx_self_closing_element',\n // Ruby\n 'if',\n 'unless',\n 'case',\n 'case_match',\n 'while',\n 'until',\n 'for',\n 'begin',\n 'when',\n]);\n\n/** Nodes whose direct named children form statement sequences scanned for copy-pasted runs. */\nconst statementContainerTypes = new Set([\n 'program',\n 'source_file',\n 'translation_unit',\n 'module',\n 'statement_block',\n 'block',\n 'compound_statement',\n 'body_statement',\n 'constructor_body',\n 'class_body',\n 'block_body',\n 'do_block',\n // Ruby loop bodies are a named `do` node, and `ensure` holds statements directly.\n 'do',\n 'ensure',\n 'then',\n 'else',\n // Case-like nodes hold their statements directly, without an inner block.\n 'case_statement',\n 'switch_block_statement_group',\n 'switch_rule',\n 'expression_case',\n 'type_case',\n 'communication_case',\n 'default_case',\n]);\n\n/**\n * Identifier leaves anonymized by occurrence order so consistently renamed copies still match.\n * Member/type names (`property_identifier`, `field_identifier`, `type_identifier`, ...) are kept\n * verbatim instead: calling a different API is a semantic difference, not a rename.\n */\nconst anonymizedIdentifierTypes = new Set([\n 'identifier',\n 'constant',\n 'instance_variable',\n 'class_variable',\n 'global_variable',\n]);\n\n/**\n * JS shorthand properties (`{ alpha }`) both emit the property name (semantic output shape) and\n * reference the binding, so they tokenize as the desugared `name: binding` — one verbatim text\n * token plus one anonymized id token — matching how the explicit form is tokenized.\n */\nconst shorthandPropertyTypes = new Set(['shorthand_property_identifier', 'shorthand_property_identifier_pattern']);\n\n/** Literal leaves normalized to a kind tag so copies differing only in literal values still match. */\nconst literalKindByType = new Map([\n ['number', '#num'],\n ['number_literal', '#num'],\n ['integer', '#num'],\n ['float', '#num'],\n ['integer_literal', '#num'],\n ['float_literal', '#num'],\n ['int_literal', '#num'],\n ['rune_literal', '#char'],\n ['imaginary_literal', '#num'],\n ['decimal_integer_literal', '#num'],\n ['hex_integer_literal', '#num'],\n ['octal_integer_literal', '#num'],\n ['binary_integer_literal', '#num'],\n ['decimal_floating_point_literal', '#num'],\n ['hex_floating_point_literal', '#num'],\n ['string_fragment', '#str'],\n ['multiline_string_fragment', '#str'],\n ['string_content', '#str'],\n ['raw_string_content', '#str'],\n ['heredoc_content', '#str'],\n // Heredoc marker names (`<<~SQL` vs `<<~QUERY`) have no string-value significance.\n ['heredoc_beginning', '#heredoc'],\n ['heredoc_end', '#heredoc'],\n // Strings are leaves in some grammars (Go/Rust) and fragment containers in others.\n ['string', '#str'],\n ['template_string', '#str'],\n ['string_literal', '#str'],\n ['interpreted_string_literal', '#str'],\n ['raw_string_literal', '#str'],\n ['raw_string', '#str'],\n ['escape_sequence', '#str'],\n ['char_literal', '#char'],\n ['character_literal', '#char'],\n ['character', '#char'],\n ['regex_pattern', '#regex'],\n]);\n\nconst commentTypes = new Set(['comment', 'line_comment', 'block_comment']);\n\n/** Children of a string node that carry only literal content; anything else is interpolation. */\nconst stringFragmentTypes = new Set([\n 'string_fragment',\n 'multiline_string_fragment',\n 'string_content',\n 'raw_string_content',\n 'escape_sequence',\n 'heredoc_content',\n // Python string delimiters are named children; they never carry interpolation.\n 'string_start',\n 'string_end',\n]);\n\n/**\n * Where a grammar names callees/members with a plain `identifier` (Java `method_invocation.name`,\n * Ruby `call.method`, Python `attribute.attribute`, plain calls elsewhere), the leaf in that field\n * must stay verbatim like `property_identifier` does: calling a different API is a semantic\n * difference, not a rename.\n */\nconst semanticNameFieldByParentType = new Map([\n ['call_expression', 'function'],\n ['method_invocation', 'name'],\n ['call', 'method'],\n ['attribute', 'attribute'],\n ['macro_invocation', 'macro'],\n // Java names accessed fields with a plain identifier in the `field` field.\n ['field_access', 'field'],\n // JS/TS `new Foo(...)` names the constructed API in the `constructor` field.\n ['new_expression', 'constructor'],\n // Python `f(timeout=...)` and Java `@Anno(key=...)` name parameters of the callee's API.\n ['keyword_argument', 'name'],\n ['element_value_pair', 'key'],\n // Rust turbofish and C++ template callees (`compute::<u32>(...)`); type arguments stay\n // anonymized via their own node types.\n ['generic_function', 'function'],\n ['template_function', 'name'],\n]);\n\n/** Minimum normalized token count for a region to be considered for duplication, to skip trivial repeats. */\nconst minDuplicateTokenCount = 40;\n/** Minimum consecutive statements for a statement-sequence duplicate candidate. */\nconst minSequenceStatementCount = 2;\n/**\n * Caps the window length so statement-sequence enumeration stays linear in the statement count.\n * Heterogeneous clones longer than the cap are reported as capped windows (a deliberate\n * conservative undercount trading completeness for bounded discovery cost).\n */\nconst maxSequenceStatementCount = 100;\n/** Caps how often the maximal-region selection reruns after shedding failed duplicate groups. */\nconst maxSelectionRerunCount = 20;\n\ninterface Token {\n /** Normalization target: identifiers to anonymize, literal kind tags, or the raw token text. */\n kind: 'id' | 'text';\n text: string;\n /** 0-based source rows the token occupies, so line coverage counts only matched-token lines. */\n startRow: number;\n endRow: number;\n}\n\ninterface TokenRange {\n startTokenIndex: number;\n endTokenIndex: number;\n node: Parser.SyntaxNode;\n}\n\ninterface DuplicateCandidate {\n fingerprint: string;\n tokenCount: number;\n startTokenIndex: number;\n endTokenIndex: number;\n startIndex: number;\n endIndex: number;\n startLine: number;\n endLine: number;\n}\n\n/**\n * Detects copy-pasted regions within a file. Regions are compared by their normalized token\n * sequence: identifiers are anonymized consistently by first-occurrence order (`a.f(a, b)` matches\n * `x.f(x, y)` but not `x.f(y, z)`), literals are normalized by kind, and member/type names and all\n * keywords/operators are kept verbatim. Candidates are whole block-like subtrees plus runs of\n * consecutive sibling statements, so a copy pasted into the middle of a longer block is still\n * found. Only maximal, non-overlapping regions are counted.\n */\nexport function measureDuplication(root: Parser.SyntaxNode, codeLineNumbers: Set<number>): DuplicationMetrics {\n const tokens: Token[] = [];\n const blockRanges: TokenRange[] = [];\n const containerStatementRanges: TokenRange[][] = [];\n collectTokens(root, tokens, blockRanges, containerStatementRanges);\n\n const candidates = [\n ...collectBlockCandidates(tokens, blockRanges),\n ...collectSequenceCandidates(tokens, containerStatementRanges),\n ];\n const counted = selectMaximalDuplicates(candidates);\n return summarizeDuplicates(counted, codeLineNumbers, tokens);\n}\n\nfunction collectTokens(\n root: Parser.SyntaxNode,\n tokens: Token[],\n blockRanges: TokenRange[],\n containerStatementRanges: TokenRange[][]\n): void {\n function visit(node: Parser.SyntaxNode): TokenRange {\n const startTokenIndex = tokens.length;\n const atomicKind = node.childCount === 0 ? undefined : atomicLiteralKind(node);\n if (node.childCount === 0) {\n appendLeafToken(node, tokens);\n } else if (atomicKind !== undefined) {\n // Interpolation-free strings collapse to their kind tag so copies differing only in quote\n // style or content still match; delimiter tokens would otherwise break the equivalence.\n tokens.push({ kind: 'text', text: atomicKind, startRow: node.startPosition.row, endRow: node.endPosition.row });\n } else if (!commentTypes.has(node.type)) {\n const statementRanges: TokenRange[] = [];\n const isContainer = node.isNamed && statementContainerTypes.has(node.type);\n for (const child of node.children) {\n const childRange = visit(child);\n if (isContainer && child.isNamed && !commentTypes.has(child.type)) {\n statementRanges.push(childRange);\n }\n }\n if (isContainer && statementRanges.length >= minSequenceStatementCount) {\n containerStatementRanges.push(statementRanges);\n }\n }\n\n const range = { startTokenIndex, endTokenIndex: tokens.length, node };\n if (node.isNamed && duplicateBlockTypes.has(node.type)) {\n blockRanges.push(range);\n }\n return range;\n }\n\n visit(root);\n}\n\n/** The kind tag of a string-like node with no interpolation, or undefined to descend normally. */\nfunction atomicLiteralKind(node: Parser.SyntaxNode): string | undefined {\n const kind = node.isNamed ? literalKindByType.get(node.type) : undefined;\n if (kind === undefined) {\n return undefined;\n }\n return node.namedChildren.every((child) => stringFragmentTypes.has(child.type)) ? kind : undefined;\n}\n\nfunction appendLeafToken(node: Parser.SyntaxNode, tokens: Token[]): void {\n if (commentTypes.has(node.type)) {\n return;\n }\n\n const startRow = node.startPosition.row;\n const endRow = node.endPosition.row;\n if (node.isNamed && shorthandPropertyTypes.has(node.type)) {\n tokens.push(\n { kind: 'text', text: node.text, startRow, endRow },\n { kind: 'text', text: ':', startRow, endRow },\n { kind: 'id', text: node.text, startRow, endRow }\n );\n return;\n }\n\n if (node.isNamed && anonymizedIdentifierTypes.has(node.type) && !isSemanticNameLeaf(node)) {\n tokens.push({ kind: 'id', text: node.text, startRow, endRow });\n return;\n }\n\n // Anything else keeps its text: keywords, operators, punctuation, and semantic names such as\n // `property_identifier`/`type_identifier`, which must distinguish otherwise-identical structures.\n const literalKind = node.isNamed ? literalKindByType.get(node.type) : undefined;\n tokens.push({ kind: 'text', text: literalKind ?? node.text, startRow, endRow });\n}\n\nfunction isSemanticNameLeaf(node: Parser.SyntaxNode): boolean {\n const parent = node.parent;\n if (!parent) {\n return false;\n }\n\n // Java method references (`Foo::bar`) name their identifiers without grammar fields; both the\n // type/object and the referenced method are semantic.\n if (parent.type === 'method_reference') {\n return true;\n }\n\n // `call` names its callee `method` in Ruby but `function` in Python; accept both fields.\n if (parent.type === 'call' && parent.childForFieldName('function')?.id === node.id) {\n return true;\n }\n\n // A Ruby constant receiving a call (`Alpha.new(...)`) names the invoked API; constants used as\n // plain values stay anonymized so renamed clones referencing constants still match.\n if (node.type === 'constant' && parent.type === 'call' && parent.childForFieldName('receiver')?.id === node.id) {\n return true;\n }\n\n // Java static receivers (`Alpha.run(...)`) name the invoked type. The tokenizer has no symbol\n // table, so PascalCase — Java's universal type-naming convention — is the discriminator;\n // camelCase instance receivers stay anonymized for rename tolerance.\n if (\n parent.type === 'method_invocation' &&\n parent.childForFieldName('object')?.id === node.id &&\n /^\\p{Lu}/u.test(node.text)\n ) {\n return true;\n }\n\n // Qualified callees (Rust `crate::alpha::make(...)`, C++ `detail::make(...)`) and generic\n // callees (`compute::<u32>(...)`, `compute<int>(...)`) wrap their identifiers arbitrarily deep;\n // every path/name segment is semantic there — but only in call position, so renamed clones that\n // merely reference scoped constants or `use` paths still match.\n if (\n (parent.type === 'scoped_identifier' || parent.type === 'qualified_identifier') &&\n (parent.childForFieldName('name')?.id === node.id || parent.childForFieldName('path')?.id === node.id)\n ) {\n let outer = parent;\n while (\n outer.parent &&\n (outer.parent.type === 'scoped_identifier' ||\n outer.parent.type === 'qualified_identifier' ||\n outer.parent.type === 'generic_function' ||\n outer.parent.type === 'template_function')\n ) {\n outer = outer.parent;\n }\n if (outer.parent?.type === 'call_expression' && outer.parent.childForFieldName('function')?.id === outer.id) {\n return true;\n }\n }\n\n // Go struct-literal keys (`Config{Timeout: ...}`) have no `key` field in the grammar: the key\n // is the keyed_element's first named child, a literal_element wrapping the identifier.\n if (\n parent.type === 'literal_element' &&\n parent.parent?.type === 'keyed_element' &&\n parent.parent.namedChild(0)?.id === parent.id\n ) {\n return true;\n }\n\n const field = semanticNameFieldByParentType.get(parent.type);\n return field !== undefined && parent.childForFieldName(field)?.id === node.id;\n}\n\nfunction collectBlockCandidates(tokens: Token[], blockRanges: TokenRange[]): DuplicateCandidate[] {\n const candidates: DuplicateCandidate[] = [];\n for (const range of blockRanges) {\n const tokenCount = range.endTokenIndex - range.startTokenIndex;\n if (tokenCount < minDuplicateTokenCount) {\n continue;\n }\n candidates.push(\n toCandidate(\n `b:${fingerprintTokens(tokens, range.startTokenIndex, range.endTokenIndex)}`,\n range.startTokenIndex,\n range.endTokenIndex,\n range.node,\n range.node\n )\n );\n }\n return candidates;\n}\n\ninterface WindowOccurrences {\n count: number;\n /** -1 once occurrences span more than one container. */\n containerIndex: number;\n minStart: number;\n maxStart: number;\n}\n\ninterface SequenceWindow {\n containerIndex: number;\n start: number;\n length: number;\n}\n\n/**\n * Enumerates runs of consecutive sibling statements. Every container statement participates; only\n * the window length is capped, so enumeration stays linear in the statement count. Windows are\n * grouped by a cheap rolling hash of per-statement fingerprints, and only locally maximal repeated\n * windows — those whose one-statement extensions stop repeating — become candidates with an exact\n * (window-consistent) fingerprint. Without the maximality filter a degenerate file of\n * near-identical statements would fingerprint every sub-window of every repeated region.\n */\nfunction collectSequenceCandidates(tokens: Token[], containers: TokenRange[][]): DuplicateCandidate[] {\n const candidates: DuplicateCandidate[] = [];\n const occurrencesByWindowKey = new Map<number, WindowOccurrences>();\n const containerWindows = containers.map((statements) => enumerateContainerWindows(tokens, statements));\n for (const [containerIndex, windows] of containerWindows.entries()) {\n for (const [start, row] of windows.windowKeysByStart.entries()) {\n for (const windowKey of row) {\n if (windowKey === undefined) {\n continue;\n }\n const occurrences = occurrencesByWindowKey.get(windowKey);\n if (occurrences) {\n occurrences.count += 1;\n if (occurrences.containerIndex !== containerIndex) {\n occurrences.containerIndex = -1;\n }\n occurrences.minStart = Math.min(occurrences.minStart, start);\n occurrences.maxStart = Math.max(occurrences.maxStart, start);\n } else {\n occurrencesByWindowKey.set(windowKey, { count: 1, containerIndex, minStart: start, maxStart: start });\n }\n }\n }\n }\n\n // A window only \"repeats\" when two of its occurrences can coexist without overlapping: sliding\n // matches inside a homogeneous run (start spread smaller than the window length) can never both\n // be counted and must neither qualify a window nor dominate its sub-windows.\n const repeats = (windowKey: number | undefined, length: number): boolean => {\n if (windowKey === undefined) {\n return false;\n }\n const occurrences = occurrencesByWindowKey.get(windowKey);\n return (\n occurrences !== undefined &&\n occurrences.count >= 2 &&\n (occurrences.containerIndex === -1 || occurrences.maxStart - occurrences.minStart >= length)\n );\n };\n\n // A window whose statements all share one normalized shape (sixteen `let x = 0;` declarations,\n // a constant table) is a homogeneous preamble, not a copy-paste: requiring two distinct\n // per-statement shapes keeps such runs out of duplicate groups and the duplication ratio.\n const hasDistinctStatements = (window: SequenceWindow): boolean => {\n const hashes = containerWindows[window.containerIndex]?.statementHashes ?? [];\n const firstHash = hashes[window.start];\n for (let index = window.start + 1; index < window.start + window.length; index += 1) {\n if (hashes[index] !== firstHash) {\n return true;\n }\n }\n return false;\n };\n\n const maximalWindows: SequenceWindow[] = [];\n for (const [containerIndex, windows] of containerWindows.entries()) {\n for (const [start, row] of windows.windowKeysByStart.entries()) {\n for (const [length, windowKey] of row.entries()) {\n if (!repeats(windowKey, length) || !hasDistinctStatements({ containerIndex, start, length })) {\n continue;\n }\n // Dominated windows are skipped: the one-statement extension also repeats, so a larger\n // candidate covering this window exists.\n const extendedRight = windows.windowKeysByStart[start]?.[length + 1];\n const extendedLeft = windows.windowKeysByStart[start - 1]?.[length + 1];\n if (repeats(extendedRight, length + 1) || repeats(extendedLeft, length + 1)) {\n continue;\n }\n maximalWindows.push({ containerIndex, start, length });\n }\n }\n }\n\n // The rolling hash anonymizes identifiers per statement, so a window can look repeated coarsely\n // while its exact (window-consistent) fingerprints differ, and a longer window's match can\n // dominate sub-windows that other copies still need (three copies where only two extend one\n // statement further). Every emitted window therefore exposes its repeating, unvisited\n // sub-windows; `visited` bounds the worklist and lengths strictly decrease, so it terminates.\n const visited = new Set(maximalWindows.map(windowId));\n let frontier = maximalWindows;\n while (frontier.length > 0) {\n const emitted: SequenceWindow[] = [];\n for (const window of frontier) {\n const statements = containers[window.containerIndex];\n const first = statements?.[window.start];\n const last = statements?.[window.start + window.length - 1];\n if (!first || !last) {\n continue;\n }\n const fingerprint = `s:${fingerprintTokens(tokens, first.startTokenIndex, last.endTokenIndex)}`;\n candidates.push(toCandidate(fingerprint, first.startTokenIndex, last.endTokenIndex, first.node, last.node));\n emitted.push(window);\n }\n frontier = [];\n for (const window of emitted) {\n for (const start of [window.start, window.start + 1]) {\n const subWindow = { containerIndex: window.containerIndex, start, length: window.length - 1 };\n const subWindowKey = containerWindows[window.containerIndex]?.windowKeysByStart[start]?.[subWindow.length];\n if (\n visited.has(windowId(subWindow)) ||\n !repeats(subWindowKey, subWindow.length) ||\n !hasDistinctStatements(subWindow)\n ) {\n continue;\n }\n visited.add(windowId(subWindow));\n frontier.push(subWindow);\n }\n }\n }\n return candidates;\n}\n\nfunction windowId(window: SequenceWindow): string {\n return `${window.containerIndex}:${window.start}:${window.length}`;\n}\n\ninterface ContainerWindows {\n /** windowKeysByStart[start][length] is the rolling-hash key of the window, or undefined if it is below the size thresholds. */\n windowKeysByStart: (number | undefined)[][];\n /** Per-statement fingerprint hashes, for the distinct-shape requirement on windows. */\n statementHashes: number[];\n}\n\nfunction enumerateContainerWindows(tokens: Token[], statements: TokenRange[]): ContainerWindows {\n const statementHashes = statements.map((statement) =>\n hashText(fingerprintTokens(tokens, statement.startTokenIndex, statement.endTokenIndex))\n );\n const windowKeysByStart: (number | undefined)[][] = [];\n for (let start = 0; start < statements.length; start += 1) {\n const row: (number | undefined)[] = [];\n let hash = 5381;\n let tokenCount = 0;\n const maxEnd = Math.min(statements.length, start + maxSequenceStatementCount);\n for (let end = start; end < maxEnd; end += 1) {\n const statement = statements[end];\n const statementHash = statementHashes[end];\n if (!statement || statementHash === undefined) {\n break;\n }\n hash = combineHashes(hash, statementHash);\n tokenCount += statement.endTokenIndex - statement.startTokenIndex;\n const statementCount = end - start + 1;\n row[statementCount] =\n statementCount >= minSequenceStatementCount && tokenCount >= minDuplicateTokenCount\n ? combineHashes(hash, statementCount)\n : undefined;\n }\n windowKeysByStart.push(row);\n }\n return { windowKeysByStart, statementHashes };\n}\n\nfunction toCandidate(\n fingerprint: string,\n startTokenIndex: number,\n endTokenIndex: number,\n firstNode: Parser.SyntaxNode,\n lastNode: Parser.SyntaxNode\n): DuplicateCandidate {\n return {\n fingerprint,\n tokenCount: endTokenIndex - startTokenIndex,\n startTokenIndex,\n endTokenIndex,\n startIndex: firstNode.startIndex,\n endIndex: lastNode.endIndex,\n startLine: firstNode.startPosition.row + 1,\n endLine: lastNode.endPosition.row + 1,\n };\n}\n\n/** Serializes a token range with identifiers anonymized consistently by first-occurrence order. */\nfunction fingerprintTokens(tokens: Token[], startTokenIndex: number, endTokenIndex: number): string {\n const indexByIdentifier = new Map<string, number>();\n const parts: string[] = [];\n for (let index = startTokenIndex; index < endTokenIndex; index += 1) {\n const token = tokens[index];\n if (!token) {\n continue;\n }\n if (token.kind === 'id') {\n let identifierIndex = indexByIdentifier.get(token.text);\n if (identifierIndex === undefined) {\n identifierIndex = indexByIdentifier.size;\n indexByIdentifier.set(token.text, identifierIndex);\n }\n parts.push(`$${identifierIndex}`);\n } else {\n parts.push(token.text);\n }\n }\n return parts.join(' ');\n}\n\n/** djb2-style hash; XOR keeps the value in signed 32-bit range, which is fine for a grouping key. */\nfunction hashText(text: string): number {\n let hash = 5381;\n for (let index = 0; index < text.length; index += 1) {\n // oxlint-disable-next-line unicorn/prefer-code-point -- djb2 hashes UTF-16 code units; codePointAt would hash surrogate pairs twice (full code point, then the lone low surrogate).\n hash = Math.imul(hash, 33) ^ text.charCodeAt(index);\n }\n return hash;\n}\n\nfunction combineHashes(hash: number, value: number): number {\n return Math.imul(hash, 31) + value;\n}\n\n/**\n * Keeps only maximal, non-overlapping duplicates: candidates are grouped by fingerprint, larger\n * regions win over regions overlapping them, and groups reduced below two survivors are dropped.\n */\nfunction selectMaximalDuplicates(candidates: DuplicateCandidate[]): Map<string, DuplicateCandidate[]> {\n const byFingerprint = new Map<string, DuplicateCandidate[]>();\n for (const candidate of candidates) {\n const group = byFingerprint.get(candidate.fingerprint) ?? [];\n group.push(candidate);\n byFingerprint.set(candidate.fingerprint, group);\n }\n\n const groups = [...byFingerprint.values()].map(dedupeByRegion).filter((group) => group.length >= 2);\n // Greedy order ranks by total coverage (region size × copies): a 3×3-statement group must beat\n // a 2×4-statement group overlapping two of its copies, or the third copy is silently dropped\n // and the reported duplication shrinks as more copies are added.\n const groupSizeByFingerprint = new Map(groups.map((group) => [group[0]?.fingerprint ?? '', group.length]));\n const coverage = (candidate: DuplicateCandidate): number =>\n candidate.tokenCount * (groupSizeByFingerprint.get(candidate.fingerprint) ?? 1);\n let duplicates = groups.flat();\n duplicates.sort((left, right) => coverage(right) - coverage(left));\n\n // Greedy selection can keep a candidate whose group ends up below two survivors; such an\n // uncounted region must not block smaller groups, so the largest failed group is removed and the\n // selection reruns. One group at a time: freeing a failed group's regions can rescue another.\n // The rerun cap bounds degenerate inputs; past it the remaining failed groups are dropped,\n // trading a sliver of recall on such files for bounded runtime.\n for (let rerun = 0; ; rerun += 1) {\n const keptRegions: { startIndex: number; endIndex: number }[] = [];\n const counted = new Map<string, DuplicateCandidate[]>();\n for (const candidate of duplicates) {\n if (keptRegions.some((region) => overlaps(region, candidate))) {\n continue;\n }\n keptRegions.push(candidate);\n const group = counted.get(candidate.fingerprint) ?? [];\n group.push(candidate);\n counted.set(candidate.fingerprint, group);\n }\n\n let failedFingerprint: string | undefined;\n let failedTokenCount = -1;\n for (const [fingerprint, group] of counted) {\n const tokenCount = group[0]?.tokenCount ?? 0;\n if (group.length < 2 && tokenCount > failedTokenCount) {\n failedFingerprint = fingerprint;\n failedTokenCount = tokenCount;\n }\n }\n // No failed fingerprint means every counted group kept at least two survivors.\n if (failedFingerprint === undefined) {\n return counted;\n }\n if (rerun >= maxSelectionRerunCount) {\n for (const [fingerprint, group] of counted) {\n if (group.length < 2) {\n counted.delete(fingerprint);\n }\n }\n return counted;\n }\n\n duplicates = duplicates.filter((candidate) => candidate.fingerprint !== failedFingerprint);\n }\n}\n\n/** Drops candidates covering the same source region (a block and the statement run spanning it). */\nfunction dedupeByRegion(group: DuplicateCandidate[]): DuplicateCandidate[] {\n const byRegion = new Map<string, DuplicateCandidate>();\n for (const candidate of group) {\n const key = `${candidate.startIndex}:${candidate.endIndex}`;\n const existing = byRegion.get(key);\n if (!existing || candidate.tokenCount > existing.tokenCount) {\n byRegion.set(key, candidate);\n }\n }\n return [...byRegion.values()];\n}\n\nfunction overlaps(\n left: { startIndex: number; endIndex: number },\n right: { startIndex: number; endIndex: number }\n): boolean {\n return left.startIndex < right.endIndex && right.startIndex < left.endIndex;\n}\n\nfunction summarizeDuplicates(\n counted: Map<string, DuplicateCandidate[]>,\n codeLineNumbers: Set<number>,\n tokens: Token[]\n): DuplicationMetrics {\n let duplicateBlockCount = 0;\n let maxDuplicateBlockSize = 0;\n const duplicateBlockGroups: { startLine: number; endLine: number }[][] = [];\n const duplicatedLines = new Set<number>();\n for (const group of counted.values()) {\n duplicateBlockCount += group.length - 1;\n for (const candidate of group) {\n maxDuplicateBlockSize = Math.max(maxDuplicateBlockSize, candidate.tokenCount);\n // Only CODE lines carrying matched tokens count: comments and blank gaps inside a\n // candidate's bounding range — and blank rows inside a multi-row token (heredocs, template\n // literals) — are not duplicated content and would push the ratio past 1.\n for (let index = candidate.startTokenIndex; index < candidate.endTokenIndex; index += 1) {\n const token = tokens[index];\n for (let row = token?.startRow ?? 0; row <= (token?.endRow ?? -1); row += 1) {\n if (codeLineNumbers.has(row + 1)) {\n duplicatedLines.add(row + 1);\n }\n }\n }\n }\n duplicateBlockGroups.push(\n group\n .map(({ startLine, endLine }) => ({ startLine, endLine }))\n .toSorted((left, right) => left.startLine - right.startLine)\n );\n }\n duplicateBlockGroups.sort((left, right) => (left[0]?.startLine ?? 0) - (right[0]?.startLine ?? 0));\n\n return {\n duplicateBlockCount,\n duplicateBlockGroupCount: counted.size,\n duplicateBlockGroups,\n duplicateLineCount: duplicatedLines.size,\n duplicationRatio: codeLineNumbers.size === 0 ? 0 : duplicatedLines.size / codeLineNumbers.size,\n maxDuplicateBlockSize,\n };\n}\n"],"mappings":"AAQA,MAAM,EAAsB,IAAI,IAAI,irBAmDpC,CAAC,EAGK,EAA0B,IAAI,IAAI,CACtC,UACA,cACA,mBACA,SACA,kBACA,QACA,qBACA,iBACA,mBACA,aACA,aACA,WAEA,KACA,SACA,OACA,OAEA,iBACA,+BACA,cACA,kBACA,YACA,qBACA,cACF,CAAC,EAOK,EAA4B,IAAI,IAAI,CACxC,aACA,WACA,oBACA,iBACA,iBACF,CAAC,EAOK,EAAyB,IAAI,IAAI,CAAC,gCAAiC,uCAAuC,CAAC,EAG3G,EAAoB,IAAI,IAAI,CAChC,CAAC,SAAU,MAAM,EACjB,CAAC,iBAAkB,MAAM,EACzB,CAAC,UAAW,MAAM,EAClB,CAAC,QAAS,MAAM,EAChB,CAAC,kBAAmB,MAAM,EAC1B,CAAC,gBAAiB,MAAM,EACxB,CAAC,cAAe,MAAM,EACtB,CAAC,eAAgB,OAAO,EACxB,CAAC,oBAAqB,MAAM,EAC5B,CAAC,0BAA2B,MAAM,EAClC,CAAC,sBAAuB,MAAM,EAC9B,CAAC,wBAAyB,MAAM,EAChC,CAAC,yBAA0B,MAAM,EACjC,CAAC,iCAAkC,MAAM,EACzC,CAAC,6BAA8B,MAAM,EACrC,CAAC,kBAAmB,MAAM,EAC1B,CAAC,4BAA6B,MAAM,EACpC,CAAC,iBAAkB,MAAM,EACzB,CAAC,qBAAsB,MAAM,EAC7B,CAAC,kBAAmB,MAAM,EAE1B,CAAC,oBAAqB,UAAU,EAChC,CAAC,cAAe,UAAU,EAE1B,CAAC,SAAU,MAAM,EACjB,CAAC,kBAAmB,MAAM,EAC1B,CAAC,iBAAkB,MAAM,EACzB,CAAC,6BAA8B,MAAM,EACrC,CAAC,qBAAsB,MAAM,EAC7B,CAAC,aAAc,MAAM,EACrB,CAAC,kBAAmB,MAAM,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AAK,IAAM,KAAS,EAAQ,OAAO,EAAG,CACpC,GAAuB,EAAM,OAAS,EACtC,IAAK,IAAM,KAAa,EAAO,CAC7B,EAAwB,KAAK,IAAI,EAAuB,EAAU,UAAU,EAI5E,IAAK,IAAI,EAAQ,EAAU,gBAAiB,EAAQ,EAAU,cAAe,GAAS,EAAG,CACvF,IAAM,EAAQ,EAAO,GACrB,IAAK,IAAI,EAAM,GAAO,UAAY,EAAG,IAAQ,GAAO,QAAU,IAAK,GAAO,EACpE,EAAgB,IAAI,EAAM,CAAC,GAC7B,EAAgB,IAAI,EAAM,CAAC,CAGjC,CACF,CACA,EAAqB,KACnB,EACG,KAAK,CAAE,YAAW,cAAe,CAAE,YAAW,SAAQ,EAAE,CAAC,CACzD,UAAU,EAAM,IAAU,EAAK,UAAY,EAAM,SAAS,CAC/D,CACF,CAGA,OAFA,EAAqB,MAAM,EAAM,KAAW,EAAK,EAAE,EAAE,WAAa,IAAM,EAAM,EAAE,EAAE,WAAa,EAAE,EAE1F,CACL,sBACA,yBAA0B,EAAQ,KAClC,uBACA,mBAAoB,EAAgB,KACpC,iBAAkB,EAAgB,OAAS,EAAI,EAAI,EAAgB,KAAO,EAAgB,KAC1F,uBACF,CACF"}
1
+ {"version":3,"file":"duplication.js","names":[],"sources":["../src/duplication.ts"],"sourcesContent":["import type Parser from 'tree-sitter';\nimport { dedupeByRegion, selectMaximalGroups } from './duplicateSelection.js';\nimport type { DuplicationMetrics, DuplicationOptions } from './types.js';\n\n/**\n * Block-like nodes considered as whole-subtree duplicate candidates. Detection itself is\n * token-based, so this set only decides which subtrees are compared; Ruby's keyword-like node\n * types (`if`, `case`, ...) are safe here because only named nodes become candidates.\n */\nconst duplicateBlockTypes = new Set([\n 'statement_block',\n 'block',\n 'compound_statement',\n 'body_statement',\n 'constructor_body',\n 'do_block',\n 'if_statement',\n 'for_statement',\n 'for_in_statement',\n 'enhanced_for_statement',\n 'for_range_loop',\n 'while_statement',\n 'do_statement',\n 'try_statement',\n 'try_with_resources_statement',\n 'with_statement',\n 'switch_statement',\n 'switch_expression',\n 'switch_case',\n 'switch_block_statement_group',\n 'switch_rule',\n 'case_clause',\n 'case_statement',\n 'match_statement',\n 'match_arm',\n 'except_clause',\n 'catch_clause',\n 'finally_clause',\n 'elif_clause',\n 'ensure',\n 'expression_statement',\n 'return_statement',\n 'return_expression',\n 'if_expression',\n 'for_expression',\n 'while_expression',\n 'loop_expression',\n 'match_expression',\n 'jsx_element',\n 'jsx_self_closing_element',\n // Ruby\n 'if',\n 'unless',\n 'case',\n 'case_match',\n 'while',\n 'until',\n 'for',\n 'begin',\n 'when',\n]);\n\n/** Nodes whose direct named children form statement sequences scanned for copy-pasted runs. */\nconst statementContainerTypes = new Set([\n 'program',\n 'source_file',\n 'translation_unit',\n 'module',\n 'statement_block',\n 'block',\n 'compound_statement',\n 'body_statement',\n 'constructor_body',\n 'class_body',\n 'block_body',\n 'do_block',\n // Ruby loop bodies are a named `do` node, and `ensure` holds statements directly.\n 'do',\n 'ensure',\n 'then',\n 'else',\n // Case-like nodes hold their statements directly, without an inner block.\n 'case_statement',\n 'switch_block_statement_group',\n 'switch_rule',\n 'expression_case',\n 'type_case',\n 'communication_case',\n 'default_case',\n]);\n\n/**\n * Identifier leaves anonymized by occurrence order so consistently renamed copies still match.\n * Member/type names (`property_identifier`, `field_identifier`, `type_identifier`, ...) are kept\n * verbatim instead: calling a different API is a semantic difference, not a rename.\n */\nconst anonymizedIdentifierTypes = new Set([\n 'identifier',\n 'constant',\n 'instance_variable',\n 'class_variable',\n 'global_variable',\n]);\n\n/**\n * JS shorthand properties (`{ alpha }`) both emit the property name (semantic output shape) and\n * reference the binding, so they tokenize as the desugared `name: binding` — one verbatim text\n * token plus one anonymized id token — matching how the explicit form is tokenized.\n */\nconst shorthandPropertyTypes = new Set(['shorthand_property_identifier', 'shorthand_property_identifier_pattern']);\n\n/** Literal leaves normalized to a kind tag so copies differing only in literal values still match. */\nconst literalKindByType = new Map([\n ['number', '#num'],\n ['number_literal', '#num'],\n ['integer', '#num'],\n ['float', '#num'],\n ['integer_literal', '#num'],\n ['float_literal', '#num'],\n ['int_literal', '#num'],\n ['rune_literal', '#char'],\n ['imaginary_literal', '#num'],\n ['decimal_integer_literal', '#num'],\n ['hex_integer_literal', '#num'],\n ['octal_integer_literal', '#num'],\n ['binary_integer_literal', '#num'],\n ['decimal_floating_point_literal', '#num'],\n ['hex_floating_point_literal', '#num'],\n ['string_fragment', '#str'],\n ['multiline_string_fragment', '#str'],\n ['string_content', '#str'],\n ['raw_string_content', '#str'],\n ['heredoc_content', '#str'],\n // Heredoc marker names (`<<~SQL` vs `<<~QUERY`) have no string-value significance.\n ['heredoc_beginning', '#heredoc'],\n ['heredoc_end', '#heredoc'],\n // Strings are leaves in some grammars (Go/Rust) and fragment containers in others.\n ['string', '#str'],\n ['template_string', '#str'],\n ['string_literal', '#str'],\n ['interpreted_string_literal', '#str'],\n ['raw_string_literal', '#str'],\n ['raw_string', '#str'],\n ['escape_sequence', '#str'],\n ['char_literal', '#char'],\n ['character_literal', '#char'],\n ['character', '#char'],\n ['regex_pattern', '#regex'],\n]);\n\n/**\n * Kind tags whose raw source text re-enters the fingerprint in literal-dense (data-like) regions.\n * `#heredoc` is excluded: heredoc marker names are naming choices, not data values.\n */\nconst valueCarryingLiteralKinds = new Set(['#num', '#str', '#char', '#regex']);\n\nconst commentTypes = new Set(['comment', 'line_comment', 'block_comment']);\n\n/**\n * String children that carry actual content, i.e. stringFragmentTypes minus the delimiter nodes\n * (Python's `string_start`/`string_end`), for delimiter-independent literal values.\n */\nconst stringContentFragmentTypes = new Set([\n 'string_fragment',\n 'multiline_string_fragment',\n 'string_content',\n 'raw_string_content',\n 'escape_sequence',\n 'heredoc_content',\n]);\n\n/** Children of a string node that carry only literal content; anything else is interpolation. */\nconst stringFragmentTypes = new Set([\n 'string_fragment',\n 'multiline_string_fragment',\n 'string_content',\n 'raw_string_content',\n 'escape_sequence',\n 'heredoc_content',\n // Python string delimiters are named children; they never carry interpolation.\n 'string_start',\n 'string_end',\n]);\n\n/**\n * Where a grammar names callees/members with a plain `identifier` (Java `method_invocation.name`,\n * Ruby `call.method`, Python `attribute.attribute`, plain calls elsewhere), the leaf in that field\n * must stay verbatim like `property_identifier` does: calling a different API is a semantic\n * difference, not a rename.\n */\nconst semanticNameFieldByParentType = new Map([\n ['call_expression', 'function'],\n ['method_invocation', 'name'],\n ['call', 'method'],\n ['attribute', 'attribute'],\n ['macro_invocation', 'macro'],\n // Java names accessed fields with a plain identifier in the `field` field.\n ['field_access', 'field'],\n // JS/TS `new Foo(...)` names the constructed API in the `constructor` field.\n ['new_expression', 'constructor'],\n // Python `f(timeout=...)` and Java `@Anno(key=...)` name parameters of the callee's API.\n ['keyword_argument', 'name'],\n ['element_value_pair', 'key'],\n // Rust turbofish and C++ template callees (`compute::<u32>(...)`); type arguments stay\n // anonymized via their own node types.\n ['generic_function', 'function'],\n ['template_function', 'name'],\n]);\n\nexport const defaultDuplicationOptions: Required<DuplicationOptions> = {\n minTokens: 40,\n maxGapTokens: 30,\n};\n\n/** Minimum consecutive statements for a statement-sequence duplicate candidate. */\nconst minSequenceStatementCount = 2;\n/**\n * Caps the window length so statement-sequence enumeration stays linear in the statement count.\n * Heterogeneous clones longer than the cap are reported as capped windows (a deliberate\n * conservative undercount trading completeness for bounded discovery cost).\n */\nconst maxSequenceStatementCount = 100;\n\n/**\n * A region whose normalized tokens are at least 20% literal values is data-like (a lookup table, a\n * constant list, a value-mapping switch), not logic: literal values re-enter its fingerprint so\n * tables that merely share their shape stop counting as copy-paste. Logic-heavy code sits well\n * below the bound (5-10% literals) while object/array tables sit above it (25-50%); punctuation\n * and member names dilute tables, which is why the bound is far below half. Compared in integer\n * math (5 * literals >= total) so the TypeScript and native backends cannot disagree on the\n * boundary.\n */\nfunction isLiteralDense(literalCount: number, tokenCount: number): boolean {\n return literalCount * 5 >= tokenCount;\n}\n\ninterface Token {\n /** Normalization target: identifiers to anonymize, literal kind tags, or the raw token text. */\n kind: 'id' | 'text';\n text: string;\n /**\n * Two INDEPENDENT hashes of `text` (djb2 and FNV-1a), precomputed so fingerprinting nested\n * regions never re-hashes a token. Feeding the same per-token hash to both fingerprint\n * accumulators would collapse the key to 32 effective bits: one djb2 collision between two\n * token texts would then equate whole regions.\n */\n textHash: number;\n textHash2: number;\n /** Hash pair of a value-carrying literal's value, folded into data-like region fingerprints. */\n literalHash?: number;\n literalHash2?: number;\n /** 0-based source rows the token occupies, so line coverage counts only matched-token lines. */\n startRow: number;\n endRow: number;\n}\n\ninterface TokenRange {\n startTokenIndex: number;\n endTokenIndex: number;\n node: Parser.SyntaxNode;\n}\n\n/** A contiguous run of matched tokens; gapped (merged) duplicates carry several per occurrence. */\ninterface TokenSegment {\n startTokenIndex: number;\n endTokenIndex: number;\n}\n\ninterface DuplicateCandidate {\n fingerprint: string;\n tokenCount: number;\n startTokenIndex: number;\n endTokenIndex: number;\n startIndex: number;\n endIndex: number;\n startLine: number;\n endLine: number;\n}\n\ninterface CountedOccurrence {\n /** Matched token runs; more than one once gapped groups are merged. */\n segments: TokenSegment[];\n /** Sum of segment token counts (the gap tokens are not matched content). */\n tokenCount: number;\n startTokenIndex: number;\n endTokenIndex: number;\n startIndex: number;\n endIndex: number;\n startLine: number;\n endLine: number;\n}\n\n/** A duplicate region found in one file, exported for cross-file matching by fingerprint. */\nexport interface CrossFileDuplicateCandidate {\n /** Content key: equal fingerprints mean equal normalized token sequences (up to hash collision). */\n fingerprint: string;\n tokenCount: number;\n startIndex: number;\n endIndex: number;\n startLine: number;\n endLine: number;\n}\n\n/**\n * Detects copy-pasted regions within a file. Regions are compared by their normalized token\n * sequence: identifiers are anonymized consistently by first-occurrence order (`a.f(a, b)` matches\n * `x.f(x, y)` but not `x.f(y, z)`), literals are normalized by kind, and member/type names and all\n * keywords/operators are kept verbatim. Literal-dense (data-like) regions additionally require\n * equal literal values. Candidates are whole block-like subtrees plus runs of consecutive sibling\n * statements, so a copy pasted into the middle of a longer block is still found. Only maximal,\n * non-overlapping regions are counted, and adjacent groups separated by a small token gap merge\n * into one gapped (Type-3) clone group.\n */\nexport function measureDuplication(\n root: Parser.SyntaxNode,\n codeLineNumbers: Set<number>,\n options?: DuplicationOptions\n): DuplicationMetrics {\n const minTokens = options?.minTokens ?? defaultDuplicationOptions.minTokens;\n const maxGapTokens = options?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens;\n const tokens: Token[] = [];\n const blockRanges: TokenRange[] = [];\n const containerStatementRanges: TokenRange[][] = [];\n collectTokens(root, tokens, blockRanges, containerStatementRanges);\n const literalCountPrefix = buildLiteralCountPrefix(tokens);\n\n const candidates = [\n ...collectBlockCandidates(tokens, literalCountPrefix, blockRanges, minTokens),\n ...collectSequenceCandidates(tokens, literalCountPrefix, containerStatementRanges, minTokens),\n ];\n const counted = selectMaximalGroups(candidates, (group) => group.length >= 2);\n const groups = mergeAdjacentGroups(toCountedGroups(counted), maxGapTokens);\n return summarizeDuplicates(groups, codeLineNumbers, tokens);\n}\n\n/**\n * Collects this file's duplicate-candidate fingerprints for cross-file clone detection: whole\n * block-like subtrees plus each statement container's full run (so wholly copied files and class\n * bodies match even when no inner block clears the threshold on its own). Nested and overlapping\n * candidates are all returned; the project-level selection keeps only maximal ones.\n */\nexport function collectCrossFileDuplicateCandidates(\n root: Parser.SyntaxNode,\n options?: DuplicationOptions\n): CrossFileDuplicateCandidate[] {\n const minTokens = options?.minTokens ?? defaultDuplicationOptions.minTokens;\n const tokens: Token[] = [];\n const blockRanges: TokenRange[] = [];\n const containerStatementRanges: TokenRange[][] = [];\n collectTokens(root, tokens, blockRanges, containerStatementRanges);\n const literalCountPrefix = buildLiteralCountPrefix(tokens);\n\n const candidates = collectBlockCandidates(tokens, literalCountPrefix, blockRanges, minTokens);\n for (const statements of containerStatementRanges) {\n const first = statements[0];\n const last = statements.at(-1);\n if (!first || !last) {\n continue;\n }\n const tokenCount = last.endTokenIndex - first.startTokenIndex;\n if (tokenCount < minTokens) {\n continue;\n }\n candidates.push(\n toCandidate(\n `s:${fingerprintKey(tokens, literalCountPrefix, first.startTokenIndex, last.endTokenIndex)}`,\n first.startTokenIndex,\n last.endTokenIndex,\n first.node,\n last.node\n )\n );\n }\n return dedupeByRegion(candidates).map(({ fingerprint, tokenCount, startIndex, endIndex, startLine, endLine }) => ({\n fingerprint,\n tokenCount,\n startIndex,\n endIndex,\n startLine,\n endLine,\n }));\n}\n\nfunction collectTokens(\n root: Parser.SyntaxNode,\n tokens: Token[],\n blockRanges: TokenRange[],\n containerStatementRanges: TokenRange[][]\n): void {\n function visit(node: Parser.SyntaxNode): TokenRange {\n const startTokenIndex = tokens.length;\n const atomicKind = node.childCount === 0 ? undefined : atomicLiteralKind(node);\n if (node.childCount === 0) {\n appendLeafToken(node, tokens);\n } else if (atomicKind !== undefined) {\n // Interpolation-free strings collapse to their kind tag so copies differing only in quote\n // style or content still match; delimiter tokens would otherwise break the equivalence.\n tokens.push(\n makeTextToken(atomicKind, literalValueText(node, atomicKind), node.startPosition.row, node.endPosition.row)\n );\n } else if (!commentTypes.has(node.type)) {\n const statementRanges: TokenRange[] = [];\n const isContainer = node.isNamed && statementContainerTypes.has(node.type);\n for (const child of node.children) {\n const childRange = visit(child);\n if (isContainer && child.isNamed && !commentTypes.has(child.type)) {\n statementRanges.push(childRange);\n }\n }\n // Single-statement containers are recorded too: within-file window enumeration needs two\n // statements and simply yields nothing for them, but cross-file matching must still see a\n // file whose only top-level statement is not a catalogued block type (a lone exported table).\n if (isContainer && statementRanges.length > 0) {\n containerStatementRanges.push(statementRanges);\n }\n }\n\n const range = { startTokenIndex, endTokenIndex: tokens.length, node };\n if (node.isNamed && duplicateBlockTypes.has(node.type)) {\n blockRanges.push(range);\n }\n return range;\n }\n\n visit(root);\n}\n\n/** The kind tag of a string-like node with no interpolation, or undefined to descend normally. */\nfunction atomicLiteralKind(node: Parser.SyntaxNode): string | undefined {\n const kind = node.isNamed ? literalKindByType.get(node.type) : undefined;\n if (kind === undefined) {\n return undefined;\n }\n return node.namedChildren.every((child) => stringFragmentTypes.has(child.type)) ? kind : undefined;\n}\n\nfunction appendLeafToken(node: Parser.SyntaxNode, tokens: Token[]): void {\n if (commentTypes.has(node.type)) {\n return;\n }\n\n const startRow = node.startPosition.row;\n const endRow = node.endPosition.row;\n if (node.isNamed && shorthandPropertyTypes.has(node.type)) {\n tokens.push(\n makeTextToken(node.text, undefined, startRow, endRow),\n makeTextToken(':', undefined, startRow, endRow),\n { kind: 'id', text: node.text, textHash: 0, textHash2: 0, startRow, endRow }\n );\n return;\n }\n\n if (node.isNamed && anonymizedIdentifierTypes.has(node.type) && !isSemanticNameLeaf(node)) {\n tokens.push({ kind: 'id', text: node.text, textHash: 0, textHash2: 0, startRow, endRow });\n return;\n }\n\n // Anything else keeps its text: keywords, operators, punctuation, and semantic names such as\n // `property_identifier`/`type_identifier`, which must distinguish otherwise-identical structures.\n const literalKind = node.isNamed ? literalKindByType.get(node.type) : undefined;\n if (literalKind === undefined) {\n tokens.push(makeTextToken(node.text, undefined, startRow, endRow));\n } else {\n tokens.push(makeTextToken(literalKind, literalValueText(node, literalKind), startRow, endRow));\n }\n}\n\nfunction makeTextToken(text: string, literalValueText: string | undefined, startRow: number, endRow: number): Token {\n const token: Token = { kind: 'text', text, textHash: hashText(text), textHash2: hashText2(text), startRow, endRow };\n if (literalValueText !== undefined && valueCarryingLiteralKinds.has(text)) {\n token.literalHash = hashText(literalValueText);\n token.literalHash2 = hashText2(literalValueText);\n }\n return token;\n}\n\n/**\n * The value of a literal as folded into literal-dense fingerprints. Strings hash their CONTENT,\n * not their source spelling: formatters rewrite quote style on paste (`'one'` vs `\"one\"`), so\n * delimiters must not make two copied tables differ. Content comes from the fragment children when\n * the grammar provides them (which also drops Python's `string_start`/`string_end` delimiter\n * nodes), else from the text with one matching pair of surrounding quotes stripped. Numbers keep\n * their raw text: formatters preserve numeric spelling, and canonicalizing values (`0x10` vs `16`)\n * identically in JavaScript and Rust would be far riskier than the rare mismatch it would unify.\n */\nfunction literalValueText(node: Parser.SyntaxNode, kind: string): string {\n if (kind !== '#str' && kind !== '#char') {\n return node.text;\n }\n // Fragment leaves (string_fragment, escape_sequence, heredoc_content, ...) already carry bare\n // content; a quote appearing there is content, not a delimiter.\n if (stringContentFragmentTypes.has(node.type)) {\n return node.text;\n }\n const fragments = node.namedChildren.filter((child) => stringContentFragmentTypes.has(child.type));\n if (fragments.length > 0) {\n return fragments.map((child) => child.text).join('');\n }\n return stripMatchingQuotes(node.text);\n}\n\nconst quoteCharacters = new Set(['\"', \"'\", '`']);\n\nfunction stripMatchingQuotes(text: string): string {\n const first = text[0];\n return text.length >= 2 && first !== undefined && quoteCharacters.has(first) && text.endsWith(first)\n ? text.slice(1, -1)\n : text;\n}\n\n/** literalCountPrefix[i] = value-carrying literal tokens in tokens[0..i), for O(1) density checks. */\nfunction buildLiteralCountPrefix(tokens: Token[]): Int32Array {\n const prefix = new Int32Array(tokens.length + 1);\n for (const [index, token] of tokens.entries()) {\n prefix[index + 1] = (prefix[index] ?? 0) + (token.literalHash === undefined ? 0 : 1);\n }\n return prefix;\n}\n\nfunction isSemanticNameLeaf(node: Parser.SyntaxNode): boolean {\n const parent = node.parent;\n if (!parent) {\n return false;\n }\n\n // Java method references (`Foo::bar`) name their identifiers without grammar fields; both the\n // type/object and the referenced method are semantic.\n if (parent.type === 'method_reference') {\n return true;\n }\n\n // `call` names its callee `method` in Ruby but `function` in Python; accept both fields.\n if (parent.type === 'call' && parent.childForFieldName('function')?.id === node.id) {\n return true;\n }\n\n // A Ruby constant receiving a call (`Alpha.new(...)`) names the invoked API; constants used as\n // plain values stay anonymized so renamed clones referencing constants still match.\n if (node.type === 'constant' && parent.type === 'call' && parent.childForFieldName('receiver')?.id === node.id) {\n return true;\n }\n\n // Java static receivers (`Alpha.run(...)`) name the invoked type. The tokenizer has no symbol\n // table, so PascalCase — Java's universal type-naming convention — is the discriminator;\n // camelCase instance receivers stay anonymized for rename tolerance.\n if (\n parent.type === 'method_invocation' &&\n parent.childForFieldName('object')?.id === node.id &&\n /^\\p{Lu}/u.test(node.text)\n ) {\n return true;\n }\n\n // Qualified callees (Rust `crate::alpha::make(...)`, C++ `detail::make(...)`) and generic\n // callees (`compute::<u32>(...)`, `compute<int>(...)`) wrap their identifiers arbitrarily deep;\n // every path/name segment is semantic there — but only in call position, so renamed clones that\n // merely reference scoped constants or `use` paths still match.\n if (\n (parent.type === 'scoped_identifier' || parent.type === 'qualified_identifier') &&\n (parent.childForFieldName('name')?.id === node.id || parent.childForFieldName('path')?.id === node.id)\n ) {\n let outer = parent;\n while (\n outer.parent &&\n (outer.parent.type === 'scoped_identifier' ||\n outer.parent.type === 'qualified_identifier' ||\n outer.parent.type === 'generic_function' ||\n outer.parent.type === 'template_function')\n ) {\n outer = outer.parent;\n }\n if (outer.parent?.type === 'call_expression' && outer.parent.childForFieldName('function')?.id === outer.id) {\n return true;\n }\n }\n\n // Go struct-literal keys (`Config{Timeout: ...}`) have no `key` field in the grammar: the key\n // is the keyed_element's first named child, a literal_element wrapping the identifier.\n if (\n parent.type === 'literal_element' &&\n parent.parent?.type === 'keyed_element' &&\n parent.parent.namedChild(0)?.id === parent.id\n ) {\n return true;\n }\n\n const field = semanticNameFieldByParentType.get(parent.type);\n return field !== undefined && parent.childForFieldName(field)?.id === node.id;\n}\n\nfunction collectBlockCandidates(\n tokens: Token[],\n literalCountPrefix: Int32Array,\n blockRanges: TokenRange[],\n minTokens: number\n): DuplicateCandidate[] {\n const candidates: DuplicateCandidate[] = [];\n for (const range of blockRanges) {\n const tokenCount = range.endTokenIndex - range.startTokenIndex;\n if (tokenCount < minTokens) {\n continue;\n }\n candidates.push(\n toCandidate(\n `b:${fingerprintKey(tokens, literalCountPrefix, range.startTokenIndex, range.endTokenIndex)}`,\n range.startTokenIndex,\n range.endTokenIndex,\n range.node,\n range.node\n )\n );\n }\n return candidates;\n}\n\ninterface WindowOccurrences {\n count: number;\n /** -1 once occurrences span more than one container. */\n containerIndex: number;\n minStart: number;\n maxStart: number;\n}\n\ninterface SequenceWindow {\n containerIndex: number;\n start: number;\n length: number;\n}\n\n/**\n * Enumerates runs of consecutive sibling statements. Every container statement participates; only\n * the window length is capped, so enumeration stays linear in the statement count. Windows are\n * grouped by a cheap rolling hash of per-statement fingerprints, and only locally maximal repeated\n * windows — those whose one-statement extensions stop repeating — become candidates with an exact\n * (window-consistent) fingerprint. Without the maximality filter a degenerate file of\n * near-identical statements would fingerprint every sub-window of every repeated region.\n */\nfunction collectSequenceCandidates(\n tokens: Token[],\n literalCountPrefix: Int32Array,\n containers: TokenRange[][],\n minTokens: number\n): DuplicateCandidate[] {\n const candidates: DuplicateCandidate[] = [];\n const occurrencesByWindowKey = new Map<number, WindowOccurrences>();\n const containerWindows = containers.map((statements) => enumerateContainerWindows(tokens, statements, minTokens));\n for (const [containerIndex, windows] of containerWindows.entries()) {\n for (const [start, row] of windows.windowKeysByStart.entries()) {\n for (const windowKey of row) {\n if (windowKey === undefined) {\n continue;\n }\n const occurrences = occurrencesByWindowKey.get(windowKey);\n if (occurrences) {\n occurrences.count += 1;\n if (occurrences.containerIndex !== containerIndex) {\n occurrences.containerIndex = -1;\n }\n occurrences.minStart = Math.min(occurrences.minStart, start);\n occurrences.maxStart = Math.max(occurrences.maxStart, start);\n } else {\n occurrencesByWindowKey.set(windowKey, { count: 1, containerIndex, minStart: start, maxStart: start });\n }\n }\n }\n }\n\n // A window only \"repeats\" when two of its occurrences can coexist without overlapping: sliding\n // matches inside a homogeneous run (start spread smaller than the window length) can never both\n // be counted and must neither qualify a window nor dominate its sub-windows.\n const repeats = (windowKey: number | undefined, length: number): boolean => {\n if (windowKey === undefined) {\n return false;\n }\n const occurrences = occurrencesByWindowKey.get(windowKey);\n return (\n occurrences !== undefined &&\n occurrences.count >= 2 &&\n (occurrences.containerIndex === -1 || occurrences.maxStart - occurrences.minStart >= length)\n );\n };\n\n // A window whose statements all share one normalized shape (sixteen `let x = 0;` declarations,\n // a constant table) is a homogeneous preamble, not a copy-paste: requiring two distinct\n // per-statement shapes keeps such runs out of duplicate groups and the duplication ratio.\n const hasDistinctStatements = (window: SequenceWindow): boolean => {\n const hashes = containerWindows[window.containerIndex]?.statementHashes ?? [];\n const firstHash = hashes[window.start];\n for (let index = window.start + 1; index < window.start + window.length; index += 1) {\n if (hashes[index] !== firstHash) {\n return true;\n }\n }\n return false;\n };\n\n const maximalWindows: SequenceWindow[] = [];\n for (const [containerIndex, windows] of containerWindows.entries()) {\n for (const [start, row] of windows.windowKeysByStart.entries()) {\n for (const [length, windowKey] of row.entries()) {\n if (!repeats(windowKey, length) || !hasDistinctStatements({ containerIndex, start, length })) {\n continue;\n }\n // Dominated windows are skipped: the one-statement extension also repeats, so a larger\n // candidate covering this window exists.\n const extendedRight = windows.windowKeysByStart[start]?.[length + 1];\n const extendedLeft = windows.windowKeysByStart[start - 1]?.[length + 1];\n if (repeats(extendedRight, length + 1) || repeats(extendedLeft, length + 1)) {\n continue;\n }\n maximalWindows.push({ containerIndex, start, length });\n }\n }\n }\n\n // The rolling hash anonymizes identifiers per statement, so a window can look repeated coarsely\n // while its exact (window-consistent) fingerprints differ, and a longer window's match can\n // dominate sub-windows that other copies still need (three copies where only two extend one\n // statement further). Every emitted window therefore exposes its repeating, unvisited\n // sub-windows; `visited` bounds the worklist and lengths strictly decrease, so it terminates.\n const visited = new Set(maximalWindows.map(windowId));\n let frontier = maximalWindows;\n while (frontier.length > 0) {\n const emitted: SequenceWindow[] = [];\n for (const window of frontier) {\n const statements = containers[window.containerIndex];\n const first = statements?.[window.start];\n const last = statements?.[window.start + window.length - 1];\n if (!first || !last) {\n continue;\n }\n const fingerprint = `s:${fingerprintKey(tokens, literalCountPrefix, first.startTokenIndex, last.endTokenIndex)}`;\n candidates.push(toCandidate(fingerprint, first.startTokenIndex, last.endTokenIndex, first.node, last.node));\n emitted.push(window);\n }\n frontier = [];\n for (const window of emitted) {\n for (const start of [window.start, window.start + 1]) {\n const subWindow = { containerIndex: window.containerIndex, start, length: window.length - 1 };\n const subWindowKey = containerWindows[window.containerIndex]?.windowKeysByStart[start]?.[subWindow.length];\n if (\n visited.has(windowId(subWindow)) ||\n !repeats(subWindowKey, subWindow.length) ||\n !hasDistinctStatements(subWindow)\n ) {\n continue;\n }\n visited.add(windowId(subWindow));\n frontier.push(subWindow);\n }\n }\n }\n return candidates;\n}\n\nfunction windowId(window: SequenceWindow): string {\n return `${window.containerIndex}:${window.start}:${window.length}`;\n}\n\ninterface ContainerWindows {\n /** windowKeysByStart[start][length] is the rolling-hash key of the window, or undefined if it is below the size thresholds. */\n windowKeysByStart: (number | undefined)[][];\n /** Per-statement fingerprint hashes, for the distinct-shape requirement on windows. */\n statementHashes: number[];\n}\n\nfunction enumerateContainerWindows(tokens: Token[], statements: TokenRange[], minTokens: number): ContainerWindows {\n const statementHashes = statements.map((statement) =>\n fingerprintHash(tokens, statement.startTokenIndex, statement.endTokenIndex)\n );\n const windowKeysByStart: (number | undefined)[][] = [];\n for (let start = 0; start < statements.length; start += 1) {\n const row: (number | undefined)[] = [];\n let hash = 5381;\n let tokenCount = 0;\n const maxEnd = Math.min(statements.length, start + maxSequenceStatementCount);\n for (let end = start; end < maxEnd; end += 1) {\n const statement = statements[end];\n const statementHash = statementHashes[end];\n if (!statement || statementHash === undefined) {\n break;\n }\n hash = combineHashes(hash, statementHash);\n tokenCount += statement.endTokenIndex - statement.startTokenIndex;\n const statementCount = end - start + 1;\n row[statementCount] =\n statementCount >= minSequenceStatementCount && tokenCount >= minTokens\n ? combineHashes(hash, statementCount)\n : undefined;\n }\n windowKeysByStart.push(row);\n }\n return { windowKeysByStart, statementHashes };\n}\n\nfunction toCandidate(\n fingerprint: string,\n startTokenIndex: number,\n endTokenIndex: number,\n firstNode: Parser.SyntaxNode,\n lastNode: Parser.SyntaxNode\n): DuplicateCandidate {\n return {\n fingerprint,\n tokenCount: endTokenIndex - startTokenIndex,\n startTokenIndex,\n endTokenIndex,\n startIndex: firstNode.startIndex,\n endIndex: lastNode.endIndex,\n startLine: firstNode.startPosition.row + 1,\n endLine: lastNode.endPosition.row + 1,\n };\n}\n\n/** Caches of hashText/hashText2 over '$0', '$1', ... so anonymized identifiers hash without allocating. */\nconst anonymizedIndexHashes: number[] = [];\nconst anonymizedIndexHashes2: number[] = [];\n\nfunction anonymizedIndexHash(index: number): number {\n let hash = anonymizedIndexHashes[index];\n if (hash === undefined) {\n hash = hashText(`$${index}`);\n anonymizedIndexHashes[index] = hash;\n }\n return hash;\n}\n\nfunction anonymizedIndexHash2(index: number): number {\n let hash = anonymizedIndexHashes2[index];\n if (hash === undefined) {\n hash = hashText2(`$${index}`);\n anonymizedIndexHashes2[index] = hash;\n }\n return hash;\n}\n\n/**\n * Content key of a token range: two independent 32-bit hashes over the normalized token sequence\n * (identifiers anonymized consistently by first-occurrence order) plus the token count. Regions\n * with equal keys are treated as equal content; a collision would need both 32-bit hashes and the\n * length to coincide, which is negligible for a metrics report. Hashing per-token instead of\n * serializing the whole range to a string keeps fingerprinting allocation-free for nested regions.\n */\nfunction fingerprintKey(\n tokens: Token[],\n literalCountPrefix: Int32Array,\n startTokenIndex: number,\n endTokenIndex: number\n): string {\n const literalCount = (literalCountPrefix[endTokenIndex] ?? 0) - (literalCountPrefix[startTokenIndex] ?? 0);\n const literalDense = isLiteralDense(literalCount, endTokenIndex - startTokenIndex);\n const [primary, secondary] = fingerprintHashPair(tokens, startTokenIndex, endTokenIndex, literalDense);\n return `${primary}:${secondary}:${endTokenIndex - startTokenIndex}`;\n}\n\n/**\n * A single 32-bit summary of a range for the coarse rolling-hash phase. Deliberately\n * density-agnostic: density is a property of the final candidate REGION, and folding literal\n * values into per-statement hashes would make a dense statement inside a logic-heavy window\n * (`const weights = [1, 2, 3];`) block the window from ever being enumerated. The coarse phase\n * over-approximates on shape alone; the exact region fingerprint still applies the density rule.\n */\nfunction fingerprintHash(tokens: Token[], startTokenIndex: number, endTokenIndex: number): number {\n const [primary, secondary] = fingerprintHashPair(tokens, startTokenIndex, endTokenIndex, false);\n // XOR already coerces to int32, matching the native backend's i32 arithmetic.\n return primary ^ Math.imul(secondary, 31);\n}\n\nfunction fingerprintHashPair(\n tokens: Token[],\n startTokenIndex: number,\n endTokenIndex: number,\n foldLiteralValues: boolean\n): [number, number] {\n const indexByIdentifier = new Map<string, number>();\n let primary = 5381;\n let secondary = 52_711;\n for (let index = startTokenIndex; index < endTokenIndex; index += 1) {\n const token = tokens[index];\n if (!token) {\n continue;\n }\n // Each accumulator consumes its own independent per-token hash: sharing one would collapse\n // the key to 32 effective bits (a single djb2 collision would equate whole regions).\n let part: number;\n let part2: number;\n if (token.kind === 'id') {\n let identifierIndex = indexByIdentifier.get(token.text);\n if (identifierIndex === undefined) {\n identifierIndex = indexByIdentifier.size;\n indexByIdentifier.set(token.text, identifierIndex);\n }\n part = anonymizedIndexHash(identifierIndex);\n part2 = anonymizedIndexHash2(identifierIndex);\n } else {\n part = token.textHash;\n part2 = token.textHash2;\n }\n // oxlint-disable-next-line unicorn/prefer-math-trunc -- `| 0` wraps the sum to int32 (Math.trunc does not), which must match the native backend's wrapping i32 arithmetic.\n primary = (Math.imul(primary, 31) + part) | 0;\n secondary = Math.imul(secondary, 37) ^ part2;\n if (foldLiteralValues && token.literalHash !== undefined && token.literalHash2 !== undefined) {\n // oxlint-disable-next-line unicorn/prefer-math-trunc -- `| 0` wraps the sum to int32 (Math.trunc does not), which must match the native backend's wrapping i32 arithmetic.\n primary = (Math.imul(primary, 31) + token.literalHash) | 0;\n secondary = Math.imul(secondary, 37) ^ token.literalHash2;\n }\n }\n return [primary, secondary];\n}\n\n/** djb2-style hash; XOR keeps the value in signed 32-bit range, which is fine for a grouping key. */\nfunction hashText(text: string): number {\n let hash = 5381;\n for (let index = 0; index < text.length; index += 1) {\n // oxlint-disable-next-line unicorn/prefer-code-point -- djb2 hashes UTF-16 code units; codePointAt would hash surrogate pairs twice (full code point, then the lone low surrogate).\n hash = Math.imul(hash, 33) ^ text.charCodeAt(index);\n }\n return hash;\n}\n\n/** FNV-1a over UTF-16 code units: independent of hashText so the two accumulators never share input. */\nfunction hashText2(text: string): number {\n let hash = -2_128_831_035; // 2166136261 as int32 (the FNV-1a offset basis)\n for (let index = 0; index < text.length; index += 1) {\n // oxlint-disable-next-line unicorn/prefer-code-point -- hashes UTF-16 code units like hashText.\n hash = Math.imul(hash ^ text.charCodeAt(index), 16_777_619);\n }\n return hash;\n}\n\nfunction combineHashes(hash: number, value: number): number {\n return Math.imul(hash, 31) + value;\n}\n\nfunction toCountedGroups(counted: Map<string, DuplicateCandidate[]>): CountedOccurrence[][] {\n const groups: CountedOccurrence[][] = [];\n for (const group of counted.values()) {\n const occurrences = group.map((candidate) => ({\n segments: [{ startTokenIndex: candidate.startTokenIndex, endTokenIndex: candidate.endTokenIndex }],\n tokenCount: candidate.tokenCount,\n startTokenIndex: candidate.startTokenIndex,\n endTokenIndex: candidate.endTokenIndex,\n startIndex: candidate.startIndex,\n endIndex: candidate.endIndex,\n startLine: candidate.startLine,\n endLine: candidate.endLine,\n }));\n occurrences.sort(\n (left, right) => left.startTokenIndex - right.startTokenIndex || left.endTokenIndex - right.endTokenIndex\n );\n groups.push(occurrences);\n }\n return groups;\n}\n\n/**\n * Merges duplicate groups separated by a small token gap into one gapped (Type-3) clone group: a\n * copy edited in one spot splits into two exact groups whose occurrences sit side by side in the\n * same order. Two groups merge when they have the same number of occurrences and, pairing\n * occurrences in source order, every pair is gap-adjacent without crossing into the next pair.\n * Merging repeats to a fixpoint so a clone edited in several spots still reassembles. Gap tokens\n * are not matched content: line coverage and sizes count only the matched segments.\n */\nfunction mergeAdjacentGroups(groups: CountedOccurrence[][], maxGapTokens: number): CountedOccurrence[][] {\n if (maxGapTokens <= 0 || groups.length < 2) {\n return groups;\n }\n // Deterministic processing order (mirrored by the native backend): by first occurrence position.\n groups.sort(compareGroups);\n for (let restart = true; restart;) {\n restart = false;\n for (let leftIndex = 0; leftIndex < groups.length && !restart; leftIndex += 1) {\n for (let rightIndex = leftIndex + 1; rightIndex < groups.length; rightIndex += 1) {\n const left = groups[leftIndex];\n const right = groups[rightIndex];\n if (!left || !right) {\n continue;\n }\n const merged = mergeGroups(left, right, maxGapTokens) ?? mergeGroups(right, left, maxGapTokens);\n if (merged) {\n groups[leftIndex] = merged;\n groups.splice(rightIndex, 1);\n groups.sort(compareGroups);\n restart = true;\n break;\n }\n }\n }\n }\n return groups;\n}\n\nfunction compareGroups(left: CountedOccurrence[], right: CountedOccurrence[]): number {\n const leftFirst = left[0];\n const rightFirst = right[0];\n return (\n (leftFirst?.startTokenIndex ?? 0) - (rightFirst?.startTokenIndex ?? 0) ||\n (leftFirst?.endTokenIndex ?? 0) - (rightFirst?.endTokenIndex ?? 0)\n );\n}\n\n/** The merged group when every `second` occurrence gap-follows its `first` counterpart, else undefined. */\nfunction mergeGroups(\n first: CountedOccurrence[],\n second: CountedOccurrence[],\n maxGapTokens: number\n): CountedOccurrence[] | undefined {\n if (first.length !== second.length) {\n return undefined;\n }\n for (const [index, leading] of first.entries()) {\n const trailing = second[index];\n if (!trailing) {\n return undefined;\n }\n const gap = trailing.startTokenIndex - leading.endTokenIndex;\n if (gap < 0 || gap > maxGapTokens) {\n return undefined;\n }\n // The merged span must stay clear of the next pair, or spans would overlap.\n const next = first[index + 1];\n if (next && trailing.endTokenIndex > next.startTokenIndex) {\n return undefined;\n }\n }\n return first.map((leading, index) => {\n const trailing = second[index];\n if (!trailing) {\n return leading;\n }\n return {\n segments: [...leading.segments, ...trailing.segments],\n tokenCount: leading.tokenCount + trailing.tokenCount,\n startTokenIndex: leading.startTokenIndex,\n endTokenIndex: trailing.endTokenIndex,\n startIndex: leading.startIndex,\n endIndex: trailing.endIndex,\n startLine: leading.startLine,\n endLine: trailing.endLine,\n };\n });\n}\n\nfunction summarizeDuplicates(\n groups: CountedOccurrence[][],\n codeLineNumbers: Set<number>,\n tokens: Token[]\n): DuplicationMetrics {\n let duplicateBlockCount = 0;\n let maxDuplicateBlockSize = 0;\n const duplicateBlockGroups: { startLine: number; endLine: number }[][] = [];\n const duplicatedLines = new Set<number>();\n for (const group of groups) {\n // Each redundant occurrence contributes one count per matched fragment, so merging a gapped\n // clone's fragments into one group does not halve the count a `duplicateBlock` threshold sees:\n // an edited two-fragment pair still counts 2, exactly as its unmerged fragments did.\n duplicateBlockCount += (group.length - 1) * (group[0]?.segments.length ?? 1);\n for (const occurrence of group) {\n maxDuplicateBlockSize = Math.max(maxDuplicateBlockSize, occurrence.tokenCount);\n // Only CODE lines carrying matched tokens count: comments and blank gaps inside an\n // occurrence's bounding range — the unmatched gap of a merged clone, and blank rows inside a\n // multi-row token (heredocs, template literals) — are not duplicated content and would push\n // the ratio past 1.\n for (const segment of occurrence.segments) {\n for (let index = segment.startTokenIndex; index < segment.endTokenIndex; index += 1) {\n const token = tokens[index];\n for (let row = token?.startRow ?? 0; row <= (token?.endRow ?? -1); row += 1) {\n if (codeLineNumbers.has(row + 1)) {\n duplicatedLines.add(row + 1);\n }\n }\n }\n }\n }\n duplicateBlockGroups.push(\n group\n .map(({ startLine, endLine }) => ({ startLine, endLine }))\n .toSorted((left, right) => left.startLine - right.startLine)\n );\n }\n duplicateBlockGroups.sort((left, right) => (left[0]?.startLine ?? 0) - (right[0]?.startLine ?? 0));\n\n return {\n duplicateBlockCount,\n duplicateBlockGroupCount: groups.length,\n duplicateBlockGroups,\n duplicateLineCount: duplicatedLines.size,\n duplicationRatio: codeLineNumbers.size === 0 ? 0 : duplicatedLines.size / codeLineNumbers.size,\n maxDuplicateBlockSize,\n };\n}\n"],"mappings":"kFASA,MAAM,EAAsB,IAAI,IAAI,irBAmDpC,CAAC,EAGK,EAA0B,IAAI,IAAI,CACtC,UACA,cACA,mBACA,SACA,kBACA,QACA,qBACA,iBACA,mBACA,aACA,aACA,WAEA,KACA,SACA,OACA,OAEA,iBACA,+BACA,cACA,kBACA,YACA,qBACA,cACF,CAAC,EAOK,EAA4B,IAAI,IAAI,CACxC,aACA,WACA,oBACA,iBACA,iBACF,CAAC,EAOK,EAAyB,IAAI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A,EAAqB,KACnB,EACG,KAAK,CAAE,YAAW,cAAe,CAAE,YAAW,SAAQ,EAAE,CAAC,CACzD,UAAU,EAAM,IAAU,EAAK,UAAY,EAAM,SAAS,CAC/D,CACF,CAGA,OAFA,EAAqB,MAAM,EAAM,KAAW,EAAK,EAAE,EAAE,WAAa,IAAM,EAAM,EAAE,EAAE,WAAa,EAAE,EAE1F,CACL,sBACA,yBAA0B,EAAO,OACjC,uBACA,mBAAoB,EAAgB,KACpC,iBAAkB,EAAgB,OAAS,EAAI,EAAI,EAAgB,KAAO,EAAgB,KAC1F,uBACF,CACF"}
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./languages.cjs"),t=require("./nativeMetrics.cjs"),n=require("./metrics.cjs");exports.TreeMeasurer=n.TreeMeasurer,exports.defaultLanguages=e.defaultLanguages,exports.defaultMeasurer=n.defaultMeasurer,exports.isNativeBackendAvailable=t.isNativeBackendAvailable,exports.measureCode=n.measureCode,exports.supportedLanguages=e.supportedLanguages;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./crossFileDuplication.cjs"),t=require("./languages.cjs"),n=require("./nativeMetrics.cjs"),r=require("./metrics.cjs");exports.TreeMeasurer=r.TreeMeasurer,exports.collectDuplicationCandidates=r.collectDuplicationCandidates,exports.defaultLanguages=t.defaultLanguages,exports.defaultMeasurer=r.defaultMeasurer,exports.isNativeBackendAvailable=n.isNativeBackendAvailable,exports.measureCode=r.measureCode,exports.measureCrossFileDuplication=e.measureCrossFileDuplication,exports.supportedLanguages=t.supportedLanguages;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,7 @@
1
+ export { measureCrossFileDuplication } from './crossFileDuplication.js';
2
+ export type { CrossFileDuplicateBlockGroup, CrossFileDuplicateOccurrence, CrossFileDuplicationMetrics, CrossFileDuplicationSourceFile, } from './crossFileDuplication.js';
3
+ export type { CrossFileDuplicateCandidate } from './duplication.js';
1
4
  export { defaultLanguages, supportedLanguages } from './languages.js';
2
- export { TreeMeasurer, defaultMeasurer, measureCode } from './metrics.js';
5
+ export { TreeMeasurer, collectDuplicationCandidates, defaultMeasurer, measureCode } from './metrics.js';
3
6
  export { isNativeBackendAvailable } from './nativeMetrics.js';
4
- export type { CallGraphMetrics, CodeMetrics, CohesionMetrics, CouplingMetrics, DeclarationMetrics, DuplicationMetrics, FunctionMetrics, HalsteadMetrics, LanguageDefinition, LanguageName, LineMetrics, MeasureOptions, ModuleMetrics, SupportedLanguage, SyntaxFeatureMetrics, TypeComplexityMetrics, } from './types.js';
7
+ export type { CallGraphMetrics, CodeMetrics, CohesionMetrics, CouplingMetrics, DeclarationMetrics, DuplicationMetrics, DuplicationOptions, FunctionMetrics, HalsteadMetrics, LanguageDefinition, LanguageName, LineMetrics, MeasureOptions, ModuleMetrics, SupportedLanguage, SyntaxFeatureMetrics, TypeComplexityMetrics, } from './types.js';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{defaultLanguages as e,supportedLanguages as t}from"./languages.js";import{isNativeBackendAvailable as n}from"./nativeMetrics.js";import{TreeMeasurer as r,defaultMeasurer as i,measureCode as a}from"./metrics.js";export{r as TreeMeasurer,e as defaultLanguages,i as defaultMeasurer,n as isNativeBackendAvailable,a as measureCode,t as supportedLanguages};
1
+ import{measureCrossFileDuplication as e}from"./crossFileDuplication.js";import{defaultLanguages as t,supportedLanguages as n}from"./languages.js";import{isNativeBackendAvailable as r}from"./nativeMetrics.js";import{TreeMeasurer as i,collectDuplicationCandidates as a,defaultMeasurer as o,measureCode as s}from"./metrics.js";export{i as TreeMeasurer,a as collectDuplicationCandidates,t as defaultLanguages,o as defaultMeasurer,r as isNativeBackendAvailable,s as measureCode,e as measureCrossFileDuplication,n as supportedLanguages};
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("./_virtual/_rolldown/runtime.cjs");let t=require("tree-sitter-c");t=e.__toESM(t,1);let n=require("tree-sitter-cpp");n=e.__toESM(n,1);let r=require("tree-sitter-go");r=e.__toESM(r,1);let i=require("tree-sitter-java");i=e.__toESM(i,1);let a=require("tree-sitter-javascript");a=e.__toESM(a,1);let o=require("tree-sitter-python");o=e.__toESM(o,1);let s=require("tree-sitter-ruby");s=e.__toESM(s,1);let c=require("tree-sitter-rust");c=e.__toESM(c,1);let l=require("tree-sitter-typescript");l=e.__toESM(l,1);const u=[`function`,`function_declaration`,`function_definition`,`function_expression`,`function_item`,`function_signature_item`,`function_declarator`,`func_literal`,`method_declaration`,`method_definition`,`method_spec`,`arrow_function`,`generator_function`,`generator_function_declaration`,`lambda`,`lambda_expression`,`closure_expression`],d=[`class`,`class_declaration`,`class_definition`,`interface_declaration`,`trait_item`,`struct_item`,`enum_item`,`union_item`],f=[`if_statement`,`elif_clause`,`else_if_clause`,`for_statement`,`for_in_statement`,`while_statement`,`do_statement`,`catch_clause`,`except_clause`,`case_clause`,`switch_case`,`match_arm`,`conditional_expression`,`ternary_expression`,`if_expression`,`while_expression`,`for_expression`,`loop_expression`],p=[...f,`expression_case`,`type_case`,`communication_case`],m=[...u,`constructor_declaration`,`compact_constructor_declaration`],h=[...d,`enum_declaration`,`record_declaration`,`annotation_type_declaration`,`object_creation_expression`,`enum_constant`],g=[...f,`enhanced_for_statement`,`switch_block_statement_group`,`switch_rule`],_=[`method`,`singleton_method`,`lambda`,`block`,`do_block`],v=[`class`,`module`],y=[`if`,`elsif`,`unless`,`while`,`until`,`for`,`when`,`in_clause`,`rescue`,`conditional`,`if_modifier`,`unless_modifier`,`while_modifier`,`until_modifier`,`rescue_modifier`],b=[`function_definition`,`lambda_expression`],x=[`struct_specifier`,`enum_specifier`,`union_specifier`],S=[...f,`case_statement`],C=[...x,`class_specifier`],w=[...S,`for_range_loop`];function T(e){return D(e,`default`)?e.default:e}function E(e){return l.default[e]}function D(e,t){return typeof e!=`object`||!e||!(t in e)?!1:!!e[t]}const O=[{name:`javascript`,aliases:[`js`,`mjs`,`cjs`],parserLanguage:T(a.default)},{name:`jsx`,parserLanguage:T(a.default)},{name:`typescript`,aliases:[`ts`],parserLanguage:E(`typescript`)},{name:`tsx`,parserLanguage:E(`tsx`)},{name:`python`,aliases:[`py`],parserLanguage:T(o.default)},{name:`go`,parserLanguage:T(r.default),decisionNodeTypes:p,nestingNodeTypes:p},{name:`rust`,aliases:[`rs`],parserLanguage:T(c.default)},{name:`java`,parserLanguage:T(i.default),functionNodeTypes:m,classNodeTypes:h,decisionNodeTypes:g,nestingNodeTypes:g},{name:`ruby`,aliases:[`rb`],parserLanguage:T(s.default),functionNodeTypes:_,classNodeTypes:v,decisionNodeTypes:y,nestingNodeTypes:y},{name:`c`,parserLanguage:T(t.default),functionNodeTypes:b,classNodeTypes:x,decisionNodeTypes:S,nestingNodeTypes:S},{name:`cpp`,aliases:[`c++`,`cxx`],parserLanguage:T(n.default),functionNodeTypes:b,classNodeTypes:C,decisionNodeTypes:w,nestingNodeTypes:w}].map(e=>({functionNodeTypes:u,classNodeTypes:d,decisionNodeTypes:f,nestingNodeTypes:f,...e}));function k(e=O){let t=new Map;for(let n of e){t.set(n.name,n);for(let e of n.aliases??[])t.set(e,n)}return t}const A=O.map(e=>e.name);exports.createLanguageRegistry=k,exports.defaultLanguages=O,exports.supportedLanguages=A;
1
+ "use strict";const e=require("./_virtual/_rolldown/runtime.cjs");let t=require("tree-sitter-c");t=e.__toESM(t,1);let n=require("tree-sitter-cpp");n=e.__toESM(n,1);let r=require("tree-sitter-go");r=e.__toESM(r,1);let i=require("tree-sitter-java");i=e.__toESM(i,1);let a=require("tree-sitter-javascript");a=e.__toESM(a,1);let o=require("tree-sitter-python");o=e.__toESM(o,1);let s=require("tree-sitter-ruby");s=e.__toESM(s,1);let c=require("tree-sitter-rust");c=e.__toESM(c,1);let l=require("tree-sitter-typescript");l=e.__toESM(l,1);const u=[`function`,`function_declaration`,`function_definition`,`function_expression`,`function_item`,`function_signature_item`,`function_declarator`,`func_literal`,`method_declaration`,`method_definition`,`method_spec`,`arrow_function`,`generator_function`,`generator_function_declaration`,`lambda`,`lambda_expression`,`closure_expression`],d=[`class`,`class_declaration`,`class_definition`,`interface_declaration`,`trait_item`,`struct_item`,`enum_item`,`union_item`],f=[`if_statement`,`elif_clause`,`else_if_clause`,`for_statement`,`for_in_statement`,`while_statement`,`do_statement`,`catch_clause`,`except_clause`,`case_clause`,`switch_case`,`match_arm`,`conditional_expression`,`ternary_expression`,`if_expression`,`while_expression`,`for_expression`,`loop_expression`],p=[...f,`expression_case`,`type_case`,`communication_case`],m=[...f,`switch_default`],h=[...p,`default_case`],g=[...u,`constructor_declaration`,`compact_constructor_declaration`],_=[...d,`enum_declaration`,`record_declaration`,`annotation_type_declaration`,`object_creation_expression`,`enum_constant`],v=[...f,`enhanced_for_statement`,`switch_block_statement_group`,`switch_rule`],y=[...v,`throw_statement`],b=[`method`,`singleton_method`,`lambda`,`block`,`do_block`],x=[`class`,`module`],S=[`if`,`elsif`,`unless`,`while`,`until`,`for`,`when`,`in_clause`,`rescue`,`conditional`,`if_modifier`,`unless_modifier`,`while_modifier`,`until_modifier`,`rescue_modifier`],C=[`function_definition`,`lambda_expression`],w=[`struct_specifier`,`enum_specifier`,`union_specifier`],T=[...f,`case_statement`],E=[...w,`class_specifier`],D=[...T,`for_range_loop`],O=`import_statement.export_statement.lexical_declaration.variable_declaration.function_declaration.function_signature.generator_function_declaration.class_declaration.abstract_class_declaration.module.method_definition.abstract_method_signature.class_static_block.field_definition.public_field_definition.type_alias_declaration.interface_declaration.enum_declaration.expression_statement.if_statement.else_clause.switch_statement.switch_case.switch_default.for_statement.for_in_statement.while_statement.do_statement.catch_clause.finally_clause.labeled_statement.return_statement.break_statement.continue_statement.throw_statement.debugger_statement.with_statement`.split(`.`),k=`import_statement.import_from_statement.future_import_statement.print_statement.exec_statement.assert_statement.expression_statement.return_statement.delete_statement.raise_statement.pass_statement.break_statement.continue_statement.global_statement.nonlocal_statement.if_statement.elif_clause.else_clause.for_statement.while_statement.except_clause.except_group_clause.finally_clause.with_statement.match_statement.case_clause.function_definition.class_definition.type_alias_statement`.split(`.`),A=`package_clause.import_spec.type_spec.type_alias.const_spec.var_spec.function_declaration.method_declaration.short_var_declaration.expression_statement.send_statement.inc_statement.dec_statement.assignment_statement.if_statement.for_statement.expression_switch_statement.type_switch_statement.select_statement.expression_case.type_case.communication_case.default_case.return_statement.break_statement.continue_statement.goto_statement.fallthrough_statement.defer_statement.go_statement.labeled_statement`.split(`.`),j=[`use_declaration`,`extern_crate_declaration`,`foreign_mod_item`,`mod_item`,`const_item`,`static_item`,`struct_item`,`enum_item`,`union_item`,`trait_item`,`impl_item`,`function_item`,`function_signature_item`,`type_item`,`associated_type`,`macro_definition`,`field_declaration`,`let_declaration`,`expression_statement`,`else_clause`,`match_arm`],M=`package_declaration.import_declaration.module_declaration.requires_module_directive.exports_module_directive.opens_module_directive.uses_module_directive.provides_module_directive.class_declaration.interface_declaration.enum_declaration.annotation_type_declaration.annotation_type_element_declaration.record_declaration.field_declaration.constant_declaration.method_declaration.constructor_declaration.compact_constructor_declaration.static_initializer.explicit_constructor_invocation.local_variable_declaration.expression_statement.if_statement.while_statement.do_statement.for_statement.enhanced_for_statement.switch_statement.switch_expression.switch_label.break_statement.continue_statement.return_statement.throw_statement.assert_statement.synchronized_statement.labeled_statement.yield_statement.resource.catch_clause.finally_clause`.split(`.`),N=[`elsif`,`else`,`when`,`in_clause`,`rescue`,`ensure`],P=[`program`,`body_statement`,`then`,`else`,`do`,`block_body`,`begin`,`ensure`],F=[`preproc_include`,`preproc_def`,`preproc_function_def`,`declaration`,`type_definition`,`field_declaration`,`function_definition`,`struct_specifier`,`enum_specifier`,`union_specifier`,`expression_statement`,`if_statement`,`else_clause`,`switch_statement`,`case_statement`,`for_statement`,`while_statement`,`do_statement`,`return_statement`,`break_statement`,`continue_statement`,`goto_statement`,`labeled_statement`],I=[...F,`class_specifier`,`namespace_definition`,`using_declaration`,`alias_declaration`,`namespace_alias_definition`,`concept_definition`,`static_assert_declaration`,`for_range_loop`,`catch_clause`,`throw_statement`,`co_return_statement`,`co_yield_statement`];function L(e){return z(e,`default`)?e.default:e}function R(e){return l.default[e]}function z(e,t){return typeof e!=`object`||!e||!(t in e)?!1:!!e[t]}const B=[{name:`javascript`,aliases:[`js`,`mjs`,`cjs`],parserLanguage:L(a.default)},{name:`jsx`,parserLanguage:L(a.default)},{name:`typescript`,aliases:[`ts`],parserLanguage:R(`typescript`)},{name:`tsx`,parserLanguage:R(`tsx`)},{name:`python`,aliases:[`py`],parserLanguage:L(o.default),ncssNodeTypes:k},{name:`go`,parserLanguage:L(r.default),decisionNodeTypes:p,nestingNodeTypes:h,ncssNodeTypes:A},{name:`rust`,aliases:[`rs`],parserLanguage:L(c.default),ncssNodeTypes:j,ncssContainerNodeTypes:[`block`,`else_clause`]},{name:`java`,parserLanguage:L(i.default),functionNodeTypes:g,classNodeTypes:_,decisionNodeTypes:y,nestingNodeTypes:v,ncssNodeTypes:M},{name:`ruby`,aliases:[`rb`],parserLanguage:L(s.default),functionNodeTypes:b,classNodeTypes:x,decisionNodeTypes:S,nestingNodeTypes:S,ncssNodeTypes:N,ncssContainerNodeTypes:P},{name:`c`,parserLanguage:L(t.default),functionNodeTypes:C,classNodeTypes:w,decisionNodeTypes:T,nestingNodeTypes:T,ncssNodeTypes:F},{name:`cpp`,aliases:[`c++`,`cxx`],parserLanguage:L(n.default),functionNodeTypes:C,classNodeTypes:E,decisionNodeTypes:D,nestingNodeTypes:D,ncssNodeTypes:I}].map(e=>({functionNodeTypes:u,classNodeTypes:d,decisionNodeTypes:f,nestingNodeTypes:m,ncssNodeTypes:O,...e}));function V(e=B){let t=new Map;for(let n of e){t.set(n.name,n);for(let e of n.aliases??[])t.set(e,n)}return t}const H=B.map(e=>e.name);exports.createLanguageRegistry=V,exports.defaultLanguages=B,exports.supportedLanguages=H;
2
2
  //# sourceMappingURL=languages.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"languages.cjs","names":["grammars","JavaScript","Python","Go","Rust","Java","Ruby","C","Cpp"],"sources":["../src/languages.ts"],"sourcesContent":["import C from 'tree-sitter-c';\nimport Cpp from 'tree-sitter-cpp';\nimport Go from 'tree-sitter-go';\nimport Java from 'tree-sitter-java';\nimport JavaScript from 'tree-sitter-javascript';\nimport Python from 'tree-sitter-python';\nimport Ruby from 'tree-sitter-ruby';\nimport Rust from 'tree-sitter-rust';\nimport TypeScript from 'tree-sitter-typescript';\nimport type { LanguageDefinition, LanguageName, ParserLanguage } from './types.js';\n\ntype GrammarModule = unknown;\n\nconst commonFunctionNodes = [\n 'function',\n 'function_declaration',\n 'function_definition',\n 'function_expression',\n 'function_item',\n 'function_signature_item',\n 'function_declarator',\n 'func_literal',\n 'method_declaration',\n 'method_definition',\n 'method_spec',\n 'arrow_function',\n 'generator_function',\n 'generator_function_declaration',\n 'lambda',\n 'lambda_expression',\n 'closure_expression',\n] as const;\n\nconst commonClassNodes = [\n 'class',\n 'class_declaration',\n 'class_definition',\n 'interface_declaration',\n 'trait_item',\n 'struct_item',\n 'enum_item',\n 'union_item',\n] as const;\n\nconst commonDecisionNodes = [\n 'if_statement',\n 'elif_clause',\n 'else_if_clause',\n 'for_statement',\n 'for_in_statement',\n 'while_statement',\n 'do_statement',\n 'catch_clause',\n 'except_clause',\n 'case_clause',\n 'switch_case',\n 'match_arm',\n 'conditional_expression',\n 'ternary_expression',\n 'if_expression',\n 'while_expression',\n 'for_expression',\n 'loop_expression',\n] as const;\n\n// Go `switch`/`select` branches are `*_case` nodes, not the `case_clause`/`switch_case` of other grammars.\nconst goDecisionNodes = [...commonDecisionNodes, 'expression_case', 'type_case', 'communication_case'] as const;\n\nconst javaFunctionNodes = [\n ...commonFunctionNodes,\n 'constructor_declaration',\n 'compact_constructor_declaration',\n] as const;\nconst javaClassNodes = [\n ...commonClassNodes,\n 'enum_declaration',\n 'record_declaration',\n 'annotation_type_declaration',\n // Counted only when they carry a `class_body` (anonymous classes, JLS 15.9.5).\n 'object_creation_expression',\n 'enum_constant',\n] as const;\nconst javaDecisionNodes = [\n ...commonDecisionNodes,\n 'enhanced_for_statement',\n 'switch_block_statement_group',\n 'switch_rule',\n] as const;\n\n// Ruby node types are keyword-like (`if`, `while`, ...), so they must stay Ruby-specific: the same\n// strings appear as anonymous keyword tokens in other grammars and would be double-counted there.\n// `block`/`do_block` are Ruby's closures (`items.map { ... }`), the analog of JS callbacks.\nconst rubyFunctionNodes = ['method', 'singleton_method', 'lambda', 'block', 'do_block'] as const;\n// `singleton_class` (`class << self`) opens an eigenclass scope, not a new type declaration.\nconst rubyClassNodes = ['class', 'module'] as const;\nconst rubyDecisionNodes = [\n 'if',\n 'elsif',\n 'unless',\n 'while',\n 'until',\n 'for',\n 'when',\n 'in_clause',\n 'rescue',\n 'conditional',\n 'if_modifier',\n 'unless_modifier',\n 'while_modifier',\n 'until_modifier',\n 'rescue_modifier',\n] as const;\n\n// `function_declarator` must stay out: it is nested inside every `function_definition` (which\n// would double-count) and also appears in body-less prototypes.\nconst cFunctionNodes = ['function_definition', 'lambda_expression'] as const;\nconst cClassNodes = ['struct_specifier', 'enum_specifier', 'union_specifier'] as const;\nconst cDecisionNodes = [...commonDecisionNodes, 'case_statement'] as const;\nconst cppClassNodes = [...cClassNodes, 'class_specifier'] as const;\nconst cppDecisionNodes = [...cDecisionNodes, 'for_range_loop'] as const;\n\nfunction normalizeGrammar(module: GrammarModule): ParserLanguage {\n if (isGrammarWrapper(module, 'default')) {\n return module.default;\n }\n\n return module;\n}\n\nfunction getTypeScriptGrammar(name: 'typescript' | 'tsx'): ParserLanguage {\n const grammars = TypeScript as unknown as Record<string, GrammarModule>;\n return grammars[name];\n}\n\nfunction isGrammarWrapper(value: GrammarModule, key: 'default'): value is Record<typeof key, ParserLanguage> {\n if (typeof value !== 'object' || value === null || !(key in value)) {\n return false;\n }\n\n return Boolean((value as Record<string, ParserLanguage>)[key]);\n}\n\nexport const defaultLanguages: readonly LanguageDefinition[] = [\n {\n name: 'javascript',\n aliases: ['js', 'mjs', 'cjs'],\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'jsx',\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'typescript',\n aliases: ['ts'],\n parserLanguage: getTypeScriptGrammar('typescript'),\n },\n {\n name: 'tsx',\n parserLanguage: getTypeScriptGrammar('tsx'),\n },\n {\n name: 'python',\n aliases: ['py'],\n parserLanguage: normalizeGrammar(Python as unknown as GrammarModule),\n },\n {\n name: 'go',\n parserLanguage: normalizeGrammar(Go as unknown as GrammarModule),\n decisionNodeTypes: goDecisionNodes,\n nestingNodeTypes: goDecisionNodes,\n },\n {\n name: 'rust',\n aliases: ['rs'],\n parserLanguage: normalizeGrammar(Rust as unknown as GrammarModule),\n },\n {\n name: 'java',\n parserLanguage: normalizeGrammar(Java as unknown as GrammarModule),\n functionNodeTypes: javaFunctionNodes,\n classNodeTypes: javaClassNodes,\n decisionNodeTypes: javaDecisionNodes,\n nestingNodeTypes: javaDecisionNodes,\n },\n {\n name: 'ruby',\n aliases: ['rb'],\n parserLanguage: normalizeGrammar(Ruby as unknown as GrammarModule),\n functionNodeTypes: rubyFunctionNodes,\n classNodeTypes: rubyClassNodes,\n decisionNodeTypes: rubyDecisionNodes,\n nestingNodeTypes: rubyDecisionNodes,\n },\n {\n name: 'c',\n parserLanguage: normalizeGrammar(C as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cClassNodes,\n decisionNodeTypes: cDecisionNodes,\n nestingNodeTypes: cDecisionNodes,\n },\n {\n name: 'cpp',\n aliases: ['c++', 'cxx'],\n parserLanguage: normalizeGrammar(Cpp as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cppClassNodes,\n decisionNodeTypes: cppDecisionNodes,\n nestingNodeTypes: cppDecisionNodes,\n },\n].map((language) => ({\n functionNodeTypes: commonFunctionNodes,\n classNodeTypes: commonClassNodes,\n decisionNodeTypes: commonDecisionNodes,\n nestingNodeTypes: commonDecisionNodes,\n ...language,\n}));\n\nexport function createLanguageRegistry(\n languages: readonly LanguageDefinition[] = defaultLanguages\n): Map<LanguageName, LanguageDefinition> {\n const registry = new Map<LanguageName, LanguageDefinition>();\n\n for (const language of languages) {\n registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n registry.set(alias, language);\n }\n }\n\n return registry;\n}\n\nexport const supportedLanguages = defaultLanguages.map((language) => language.name);\n"],"mappings":"ohBAaA,MAAM,EAAsB,CAC1B,WACA,uBACA,sBACA,sBACA,gBACA,0BACA,sBACA,eACA,qBACA,oBACA,cACA,iBACA,qBACA,iCACA,SACA,oBACA,oBACF,EAEM,EAAmB,CACvB,QACA,oBACA,mBACA,wBACA,aACA,cACA,YACA,YACF,EAEM,EAAsB,CAC1B,eACA,cACA,iBACA,gBACA,mBACA,kBACA,eACA,eACA,gBACA,cACA,cACA,YACA,yBACA,qBACA,gBACA,mBACA,iBACA,iBACF,EAGM,EAAkB,CAAC,GAAG,EAAqB,kBAAmB,YAAa,oBAAoB,EAE/F,EAAoB,CACxB,GAAG,EACH,0BACA,iCACF,EACM,EAAiB,CACrB,GAAG,EACH,mBACA,qBACA,8BAEA,6BACA,eACF,EACM,EAAoB,CACxB,GAAG,EACH,yBACA,+BACA,aACF,EAKM,EAAoB,CAAC,SAAU,mBAAoB,SAAU,QAAS,UAAU,EAEhF,EAAiB,CAAC,QAAS,QAAQ,EACnC,EAAoB,CACxB,KACA,QACA,SACA,QACA,QACA,MACA,OACA,YACA,SACA,cACA,cACA,kBACA,iBACA,iBACA,iBACF,EAIM,EAAiB,CAAC,sBAAuB,mBAAmB,EAC5D,EAAc,CAAC,mBAAoB,iBAAkB,iBAAiB,EACtE,EAAiB,CAAC,GAAG,EAAqB,gBAAgB,EAC1D,EAAgB,CAAC,GAAG,EAAa,iBAAiB,EAClD,EAAmB,CAAC,GAAG,EAAgB,gBAAgB,EAE7D,SAAS,EAAiB,EAAuC,CAK/D,OAJI,EAAiB,EAAQ,SA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BAAkB,CACpB,CACF,CAAC,CAAC,IAAK,IAAc,CACnB,kBAAmB,EACnB,eAAgB,EAChB,kBAAmB,EACnB,iBAAkB,EAClB,GAAG,CACL,EAAE,EAEF,SAAgB,EACd,EAA2C,EACJ,CACvC,IAAM,EAAW,IAAI,IAErB,IAAK,IAAM,KAAY,EAAW,CAChC,EAAS,IAAI,EAAS,KAAM,CAAQ,EACpC,IAAK,IAAM,KAAS,EAAS,SAAW,CAAC,EACvC,EAAS,IAAI,EAAO,CAAQ,CAEhC,CAEA,OAAO,CACT,CAEA,MAAa,EAAqB,EAAiB,IAAK,GAAa,EAAS,IAAI"}
1
+ {"version":3,"file":"languages.cjs","names":["grammars","JavaScript","Python","Go","Rust","Java","Ruby","C","Cpp"],"sources":["../src/languages.ts"],"sourcesContent":["import C from 'tree-sitter-c';\nimport Cpp from 'tree-sitter-cpp';\nimport Go from 'tree-sitter-go';\nimport Java from 'tree-sitter-java';\nimport JavaScript from 'tree-sitter-javascript';\nimport Python from 'tree-sitter-python';\nimport Ruby from 'tree-sitter-ruby';\nimport Rust from 'tree-sitter-rust';\nimport TypeScript from 'tree-sitter-typescript';\nimport type { LanguageDefinition, LanguageName, ParserLanguage } from './types.js';\n\ntype GrammarModule = unknown;\n\nconst commonFunctionNodes = [\n 'function',\n 'function_declaration',\n 'function_definition',\n 'function_expression',\n 'function_item',\n 'function_signature_item',\n 'function_declarator',\n 'func_literal',\n 'method_declaration',\n 'method_definition',\n 'method_spec',\n 'arrow_function',\n 'generator_function',\n 'generator_function_declaration',\n 'lambda',\n 'lambda_expression',\n 'closure_expression',\n] as const;\n\nconst commonClassNodes = [\n 'class',\n 'class_declaration',\n 'class_definition',\n 'interface_declaration',\n 'trait_item',\n 'struct_item',\n 'enum_item',\n 'union_item',\n] as const;\n\nconst commonDecisionNodes = [\n 'if_statement',\n 'elif_clause',\n 'else_if_clause',\n 'for_statement',\n 'for_in_statement',\n 'while_statement',\n 'do_statement',\n 'catch_clause',\n 'except_clause',\n 'case_clause',\n 'switch_case',\n 'match_arm',\n 'conditional_expression',\n 'ternary_expression',\n 'if_expression',\n 'while_expression',\n 'for_expression',\n 'loop_expression',\n] as const;\n\n// Go `switch`/`select` branches are `*_case` nodes, not the `case_clause`/`switch_case` of other grammars.\nconst goDecisionNodes = [...commonDecisionNodes, 'expression_case', 'type_case', 'communication_case'] as const;\n\n// Default switch branches add no decision, but their contents are nested inside the switch like\n// any other arm, so they appear in the nesting sets only.\nconst commonNestingNodes = [...commonDecisionNodes, 'switch_default'] as const;\nconst goNestingNodes = [...goDecisionNodes, 'default_case'] as const;\n\nconst javaFunctionNodes = [\n ...commonFunctionNodes,\n 'constructor_declaration',\n 'compact_constructor_declaration',\n] as const;\nconst javaClassNodes = [\n ...commonClassNodes,\n 'enum_declaration',\n 'record_declaration',\n 'annotation_type_declaration',\n // Counted only when they carry a `class_body` (anonymous classes, JLS 15.9.5).\n 'object_creation_expression',\n 'enum_constant',\n] as const;\nconst javaDecisionNodes = [\n ...commonDecisionNodes,\n 'enhanced_for_statement',\n 'switch_block_statement_group',\n 'switch_rule',\n] as const;\n// PMD's standard cyclomatic complexity charges `throw` one path (verified against PMD 7.26.0);\n// it stays out of the nesting set (its argument expressions are not nested) and adds no\n// cognitive point (see cyclomaticOnlyNodeTypes in metrics.ts). Other languages follow their own\n// reference tools (lizard/radon), which do not count throw/raise.\nconst javaCyclomaticDecisionNodes = [...javaDecisionNodes, 'throw_statement'] as const;\n\n// Ruby node types are keyword-like (`if`, `while`, ...), so they must stay Ruby-specific: the same\n// strings appear as anonymous keyword tokens in other grammars and would be double-counted there.\n// `block`/`do_block` are Ruby's closures (`items.map { ... }`), the analog of JS callbacks.\nconst rubyFunctionNodes = ['method', 'singleton_method', 'lambda', 'block', 'do_block'] as const;\n// `singleton_class` (`class << self`) opens an eigenclass scope, not a new type declaration.\nconst rubyClassNodes = ['class', 'module'] as const;\nconst rubyDecisionNodes = [\n 'if',\n 'elsif',\n 'unless',\n 'while',\n 'until',\n 'for',\n 'when',\n 'in_clause',\n 'rescue',\n 'conditional',\n 'if_modifier',\n 'unless_modifier',\n 'while_modifier',\n 'until_modifier',\n 'rescue_modifier',\n] as const;\n\n// `function_declarator` must stay out: it is nested inside every `function_definition` (which\n// would double-count) and also appears in body-less prototypes.\nconst cFunctionNodes = ['function_definition', 'lambda_expression'] as const;\nconst cClassNodes = ['struct_specifier', 'enum_specifier', 'union_specifier'] as const;\nconst cDecisionNodes = [...commonDecisionNodes, 'case_statement'] as const;\nconst cppClassNodes = [...cClassNodes, 'class_specifier'] as const;\nconst cppDecisionNodes = [...cDecisionNodes, 'for_range_loop'] as const;\n\n// NCSS node sets: every listed type counts as one non-commenting source statement. The Java set is\n// calibrated against PMD's NcssCount rule (`try` counts 0; `else`, `case`/`default` labels,\n// `catch`, `finally`, and try-with-resources resources count 1 each); the other languages follow\n// the same conventions with their grammar's node types.\nconst jsNcssNodes = [\n 'import_statement',\n 'export_statement',\n 'lexical_declaration',\n 'variable_declaration',\n 'function_declaration',\n 'function_signature',\n 'generator_function_declaration',\n 'class_declaration',\n 'abstract_class_declaration',\n 'module',\n 'method_definition',\n 'abstract_method_signature',\n 'class_static_block',\n 'field_definition',\n 'public_field_definition',\n 'type_alias_declaration',\n 'interface_declaration',\n 'enum_declaration',\n 'expression_statement',\n 'if_statement',\n 'else_clause',\n 'switch_statement',\n 'switch_case',\n 'switch_default',\n 'for_statement',\n 'for_in_statement',\n 'while_statement',\n 'do_statement',\n 'catch_clause',\n 'finally_clause',\n 'labeled_statement',\n 'return_statement',\n 'break_statement',\n 'continue_statement',\n 'throw_statement',\n 'debugger_statement',\n 'with_statement',\n] as const;\n\nconst pythonNcssNodes = [\n 'import_statement',\n 'import_from_statement',\n 'future_import_statement',\n 'print_statement',\n 'exec_statement',\n 'assert_statement',\n 'expression_statement',\n 'return_statement',\n 'delete_statement',\n 'raise_statement',\n 'pass_statement',\n 'break_statement',\n 'continue_statement',\n 'global_statement',\n 'nonlocal_statement',\n 'if_statement',\n 'elif_clause',\n 'else_clause',\n 'for_statement',\n 'while_statement',\n 'except_clause',\n 'except_group_clause',\n 'finally_clause',\n 'with_statement',\n 'match_statement',\n 'case_clause',\n 'function_definition',\n 'class_definition',\n 'type_alias_statement',\n] as const;\n\nconst goNcssNodes = [\n 'package_clause',\n 'import_spec',\n 'type_spec',\n 'type_alias',\n 'const_spec',\n 'var_spec',\n 'function_declaration',\n 'method_declaration',\n // Struct fields and interface members count contextually (see ncss.ts): only inside a named\n // `type T struct/interface { ... }`, not in inline anonymous types, which are part of one\n // declaration.\n 'short_var_declaration',\n 'expression_statement',\n 'send_statement',\n 'inc_statement',\n 'dec_statement',\n 'assignment_statement',\n 'if_statement',\n 'for_statement',\n 'expression_switch_statement',\n 'type_switch_statement',\n 'select_statement',\n 'expression_case',\n 'type_case',\n 'communication_case',\n 'default_case',\n 'return_statement',\n 'break_statement',\n 'continue_statement',\n 'goto_statement',\n 'fallthrough_statement',\n 'defer_statement',\n 'go_statement',\n 'labeled_statement',\n] as const;\n\nconst rustNcssNodes = [\n 'use_declaration',\n 'extern_crate_declaration',\n 'foreign_mod_item',\n 'mod_item',\n 'const_item',\n 'static_item',\n 'struct_item',\n 'enum_item',\n 'union_item',\n 'trait_item',\n 'impl_item',\n 'function_item',\n 'function_signature_item',\n 'type_item',\n 'associated_type',\n 'macro_definition',\n 'field_declaration',\n 'let_declaration',\n 'expression_statement',\n 'else_clause',\n 'match_arm',\n] as const;\n\nconst javaNcssNodes = [\n 'package_declaration',\n 'import_declaration',\n 'module_declaration',\n 'requires_module_directive',\n 'exports_module_directive',\n 'opens_module_directive',\n 'uses_module_directive',\n 'provides_module_directive',\n 'class_declaration',\n 'interface_declaration',\n 'enum_declaration',\n 'annotation_type_declaration',\n 'annotation_type_element_declaration',\n 'record_declaration',\n 'field_declaration',\n 'constant_declaration',\n 'method_declaration',\n 'constructor_declaration',\n 'compact_constructor_declaration',\n 'static_initializer',\n 'explicit_constructor_invocation',\n 'local_variable_declaration',\n 'expression_statement',\n 'if_statement',\n 'while_statement',\n 'do_statement',\n 'for_statement',\n 'enhanced_for_statement',\n 'switch_statement',\n 'switch_expression',\n 'switch_label',\n 'break_statement',\n 'continue_statement',\n 'return_statement',\n 'throw_statement',\n 'assert_statement',\n 'synchronized_statement',\n 'labeled_statement',\n 'yield_statement',\n 'resource',\n 'catch_clause',\n 'finally_clause',\n] as const;\n\n// Ruby statements have no wrapper node types, so bodies are counted positionally (see\n// ncssContainerNodeTypes); only clause nodes hanging off non-container parents need listing.\nconst rubyNcssNodes = ['elsif', 'else', 'when', 'in_clause', 'rescue', 'ensure'] as const;\nconst rubyNcssContainers = [\n 'program',\n 'body_statement',\n 'then',\n 'else',\n 'do',\n 'block_body',\n 'begin',\n 'ensure',\n] as const;\n\nconst cNcssNodes = [\n 'preproc_include',\n 'preproc_def',\n 'preproc_function_def',\n 'declaration',\n 'type_definition',\n 'field_declaration',\n 'function_definition',\n // Counted only when they carry a body (see bodylessNcssSpecifierTypes in ncss.ts).\n 'struct_specifier',\n 'enum_specifier',\n 'union_specifier',\n 'expression_statement',\n 'if_statement',\n 'else_clause',\n 'switch_statement',\n 'case_statement',\n 'for_statement',\n 'while_statement',\n 'do_statement',\n 'return_statement',\n 'break_statement',\n 'continue_statement',\n 'goto_statement',\n 'labeled_statement',\n] as const;\nconst cppNcssNodes = [\n ...cNcssNodes,\n 'class_specifier',\n 'namespace_definition',\n 'using_declaration',\n 'alias_declaration',\n 'namespace_alias_definition',\n 'concept_definition',\n 'static_assert_declaration',\n 'for_range_loop',\n 'catch_clause',\n 'throw_statement',\n 'co_return_statement',\n 'co_yield_statement',\n] as const;\n\nfunction normalizeGrammar(module: GrammarModule): ParserLanguage {\n if (isGrammarWrapper(module, 'default')) {\n return module.default;\n }\n\n return module;\n}\n\nfunction getTypeScriptGrammar(name: 'typescript' | 'tsx'): ParserLanguage {\n const grammars = TypeScript as unknown as Record<string, GrammarModule>;\n return grammars[name];\n}\n\nfunction isGrammarWrapper(value: GrammarModule, key: 'default'): value is Record<typeof key, ParserLanguage> {\n if (typeof value !== 'object' || value === null || !(key in value)) {\n return false;\n }\n\n return Boolean((value as Record<string, ParserLanguage>)[key]);\n}\n\nexport const defaultLanguages: readonly LanguageDefinition[] = [\n {\n name: 'javascript',\n aliases: ['js', 'mjs', 'cjs'],\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'jsx',\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'typescript',\n aliases: ['ts'],\n parserLanguage: getTypeScriptGrammar('typescript'),\n },\n {\n name: 'tsx',\n parserLanguage: getTypeScriptGrammar('tsx'),\n },\n {\n name: 'python',\n aliases: ['py'],\n parserLanguage: normalizeGrammar(Python as unknown as GrammarModule),\n ncssNodeTypes: pythonNcssNodes,\n },\n {\n name: 'go',\n parserLanguage: normalizeGrammar(Go as unknown as GrammarModule),\n decisionNodeTypes: goDecisionNodes,\n nestingNodeTypes: goNestingNodes,\n ncssNodeTypes: goNcssNodes,\n },\n {\n name: 'rust',\n aliases: ['rs'],\n parserLanguage: normalizeGrammar(Rust as unknown as GrammarModule),\n ncssNodeTypes: rustNcssNodes,\n // `else_clause` is a container so `else if` chains count the nested if_expression; a plain\n // `else { ... }` is unaffected because its only child is a `block`, itself a container.\n ncssContainerNodeTypes: ['block', 'else_clause'],\n },\n {\n name: 'java',\n parserLanguage: normalizeGrammar(Java as unknown as GrammarModule),\n functionNodeTypes: javaFunctionNodes,\n classNodeTypes: javaClassNodes,\n decisionNodeTypes: javaCyclomaticDecisionNodes,\n nestingNodeTypes: javaDecisionNodes,\n ncssNodeTypes: javaNcssNodes,\n },\n {\n name: 'ruby',\n aliases: ['rb'],\n parserLanguage: normalizeGrammar(Ruby as unknown as GrammarModule),\n functionNodeTypes: rubyFunctionNodes,\n classNodeTypes: rubyClassNodes,\n decisionNodeTypes: rubyDecisionNodes,\n nestingNodeTypes: rubyDecisionNodes,\n ncssNodeTypes: rubyNcssNodes,\n ncssContainerNodeTypes: rubyNcssContainers,\n },\n {\n name: 'c',\n parserLanguage: normalizeGrammar(C as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cClassNodes,\n decisionNodeTypes: cDecisionNodes,\n nestingNodeTypes: cDecisionNodes,\n ncssNodeTypes: cNcssNodes,\n },\n {\n name: 'cpp',\n aliases: ['c++', 'cxx'],\n parserLanguage: normalizeGrammar(Cpp as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cppClassNodes,\n decisionNodeTypes: cppDecisionNodes,\n nestingNodeTypes: cppDecisionNodes,\n ncssNodeTypes: cppNcssNodes,\n },\n].map((language) => ({\n functionNodeTypes: commonFunctionNodes,\n classNodeTypes: commonClassNodes,\n decisionNodeTypes: commonDecisionNodes,\n nestingNodeTypes: commonNestingNodes,\n ncssNodeTypes: jsNcssNodes,\n ...language,\n}));\n\nexport function createLanguageRegistry(\n languages: readonly LanguageDefinition[] = defaultLanguages\n): Map<LanguageName, LanguageDefinition> {\n const registry = new Map<LanguageName, LanguageDefinition>();\n\n for (const language of languages) {\n registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n registry.set(alias, language);\n }\n }\n\n return registry;\n}\n\nexport const supportedLanguages = defaultLanguages.map((language) => language.name);\n"],"mappings":"ohBAaA,MAAM,EAAsB,CAC1B,WACA,uBACA,sBACA,sBACA,gBACA,0BACA,sBACA,eACA,qBACA,oBACA,cACA,iBACA,qBACA,iCACA,SACA,oBACA,oBACF,EAEM,EAAmB,CACvB,QACA,oBACA,mBACA,wBACA,aACA,cACA,YACA,YACF,EAEM,EAAsB,CAC1B,eACA,cACA,iBACA,gBACA,mBACA,kBACA,eACA,eACA,gBACA,cACA,cACA,YACA,yBACA,qBACA,gBACA,mBACA,iBACA,iBACF,EAGM,EAAkB,CAAC,GAAG,EAAqB,kBAAmB,YAAa,oBAAoB,EAI/F,EAAqB,CAAC,GAAG,EAAqB,gBAAgB,EAC9D,EAAiB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Ae,CACjB,EACA,CACE,KAAM,MACN,QAAS,CAAC,MAAO,KAAK,EACtB,eAAgB,EAAiBC,EAAAA,OAA+B,EAChE,kBAAmB,EACnB,eAAgB,EAChB,kBAAmB,EACnB,iBAAkB,EAClB,cAAe,CACjB,CACF,CAAC,CAAC,IAAK,IAAc,CACnB,kBAAmB,EACnB,eAAgB,EAChB,kBAAmB,EACnB,iBAAkB,EAClB,cAAe,EACf,GAAG,CACL,EAAE,EAEF,SAAgB,EACd,EAA2C,EACJ,CACvC,IAAM,EAAW,IAAI,IAErB,IAAK,IAAM,KAAY,EAAW,CAChC,EAAS,IAAI,EAAS,KAAM,CAAQ,EACpC,IAAK,IAAM,KAAS,EAAS,SAAW,CAAC,EACvC,EAAS,IAAI,EAAO,CAAQ,CAEhC,CAEA,OAAO,CACT,CAEA,MAAa,EAAqB,EAAiB,IAAK,GAAa,EAAS,IAAI"}
package/dist/languages.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"tree-sitter-c";import t from"tree-sitter-cpp";import n from"tree-sitter-go";import r from"tree-sitter-java";import i from"tree-sitter-javascript";import a from"tree-sitter-python";import o from"tree-sitter-ruby";import s from"tree-sitter-rust";import c from"tree-sitter-typescript";const l=[`function`,`function_declaration`,`function_definition`,`function_expression`,`function_item`,`function_signature_item`,`function_declarator`,`func_literal`,`method_declaration`,`method_definition`,`method_spec`,`arrow_function`,`generator_function`,`generator_function_declaration`,`lambda`,`lambda_expression`,`closure_expression`],u=[`class`,`class_declaration`,`class_definition`,`interface_declaration`,`trait_item`,`struct_item`,`enum_item`,`union_item`],d=[`if_statement`,`elif_clause`,`else_if_clause`,`for_statement`,`for_in_statement`,`while_statement`,`do_statement`,`catch_clause`,`except_clause`,`case_clause`,`switch_case`,`match_arm`,`conditional_expression`,`ternary_expression`,`if_expression`,`while_expression`,`for_expression`,`loop_expression`],f=[...d,`expression_case`,`type_case`,`communication_case`],p=[...l,`constructor_declaration`,`compact_constructor_declaration`],m=[...u,`enum_declaration`,`record_declaration`,`annotation_type_declaration`,`object_creation_expression`,`enum_constant`],h=[...d,`enhanced_for_statement`,`switch_block_statement_group`,`switch_rule`],g=[`method`,`singleton_method`,`lambda`,`block`,`do_block`],_=[`class`,`module`],v=[`if`,`elsif`,`unless`,`while`,`until`,`for`,`when`,`in_clause`,`rescue`,`conditional`,`if_modifier`,`unless_modifier`,`while_modifier`,`until_modifier`,`rescue_modifier`],y=[`function_definition`,`lambda_expression`],b=[`struct_specifier`,`enum_specifier`,`union_specifier`],x=[...d,`case_statement`],S=[...b,`class_specifier`],C=[...x,`for_range_loop`];function w(e){return E(e,`default`)?e.default:e}function T(e){return c[e]}function E(e,t){return typeof e!=`object`||!e||!(t in e)?!1:!!e[t]}const D=[{name:`javascript`,aliases:[`js`,`mjs`,`cjs`],parserLanguage:w(i)},{name:`jsx`,parserLanguage:w(i)},{name:`typescript`,aliases:[`ts`],parserLanguage:T(`typescript`)},{name:`tsx`,parserLanguage:T(`tsx`)},{name:`python`,aliases:[`py`],parserLanguage:w(a)},{name:`go`,parserLanguage:w(n),decisionNodeTypes:f,nestingNodeTypes:f},{name:`rust`,aliases:[`rs`],parserLanguage:w(s)},{name:`java`,parserLanguage:w(r),functionNodeTypes:p,classNodeTypes:m,decisionNodeTypes:h,nestingNodeTypes:h},{name:`ruby`,aliases:[`rb`],parserLanguage:w(o),functionNodeTypes:g,classNodeTypes:_,decisionNodeTypes:v,nestingNodeTypes:v},{name:`c`,parserLanguage:w(e),functionNodeTypes:y,classNodeTypes:b,decisionNodeTypes:x,nestingNodeTypes:x},{name:`cpp`,aliases:[`c++`,`cxx`],parserLanguage:w(t),functionNodeTypes:y,classNodeTypes:S,decisionNodeTypes:C,nestingNodeTypes:C}].map(e=>({functionNodeTypes:l,classNodeTypes:u,decisionNodeTypes:d,nestingNodeTypes:d,...e}));function O(e=D){let t=new Map;for(let n of e){t.set(n.name,n);for(let e of n.aliases??[])t.set(e,n)}return t}const k=D.map(e=>e.name);export{O as createLanguageRegistry,D as defaultLanguages,k as supportedLanguages};
1
+ import e from"tree-sitter-c";import t from"tree-sitter-cpp";import n from"tree-sitter-go";import r from"tree-sitter-java";import i from"tree-sitter-javascript";import a from"tree-sitter-python";import o from"tree-sitter-ruby";import s from"tree-sitter-rust";import c from"tree-sitter-typescript";const l=[`function`,`function_declaration`,`function_definition`,`function_expression`,`function_item`,`function_signature_item`,`function_declarator`,`func_literal`,`method_declaration`,`method_definition`,`method_spec`,`arrow_function`,`generator_function`,`generator_function_declaration`,`lambda`,`lambda_expression`,`closure_expression`],u=[`class`,`class_declaration`,`class_definition`,`interface_declaration`,`trait_item`,`struct_item`,`enum_item`,`union_item`],d=[`if_statement`,`elif_clause`,`else_if_clause`,`for_statement`,`for_in_statement`,`while_statement`,`do_statement`,`catch_clause`,`except_clause`,`case_clause`,`switch_case`,`match_arm`,`conditional_expression`,`ternary_expression`,`if_expression`,`while_expression`,`for_expression`,`loop_expression`],f=[...d,`expression_case`,`type_case`,`communication_case`],p=[...d,`switch_default`],m=[...f,`default_case`],h=[...l,`constructor_declaration`,`compact_constructor_declaration`],g=[...u,`enum_declaration`,`record_declaration`,`annotation_type_declaration`,`object_creation_expression`,`enum_constant`],_=[...d,`enhanced_for_statement`,`switch_block_statement_group`,`switch_rule`],v=[..._,`throw_statement`],y=[`method`,`singleton_method`,`lambda`,`block`,`do_block`],b=[`class`,`module`],x=[`if`,`elsif`,`unless`,`while`,`until`,`for`,`when`,`in_clause`,`rescue`,`conditional`,`if_modifier`,`unless_modifier`,`while_modifier`,`until_modifier`,`rescue_modifier`],S=[`function_definition`,`lambda_expression`],C=[`struct_specifier`,`enum_specifier`,`union_specifier`],w=[...d,`case_statement`],T=[...C,`class_specifier`],E=[...w,`for_range_loop`],D=`import_statement.export_statement.lexical_declaration.variable_declaration.function_declaration.function_signature.generator_function_declaration.class_declaration.abstract_class_declaration.module.method_definition.abstract_method_signature.class_static_block.field_definition.public_field_definition.type_alias_declaration.interface_declaration.enum_declaration.expression_statement.if_statement.else_clause.switch_statement.switch_case.switch_default.for_statement.for_in_statement.while_statement.do_statement.catch_clause.finally_clause.labeled_statement.return_statement.break_statement.continue_statement.throw_statement.debugger_statement.with_statement`.split(`.`),O=`import_statement.import_from_statement.future_import_statement.print_statement.exec_statement.assert_statement.expression_statement.return_statement.delete_statement.raise_statement.pass_statement.break_statement.continue_statement.global_statement.nonlocal_statement.if_statement.elif_clause.else_clause.for_statement.while_statement.except_clause.except_group_clause.finally_clause.with_statement.match_statement.case_clause.function_definition.class_definition.type_alias_statement`.split(`.`),k=`package_clause.import_spec.type_spec.type_alias.const_spec.var_spec.function_declaration.method_declaration.short_var_declaration.expression_statement.send_statement.inc_statement.dec_statement.assignment_statement.if_statement.for_statement.expression_switch_statement.type_switch_statement.select_statement.expression_case.type_case.communication_case.default_case.return_statement.break_statement.continue_statement.goto_statement.fallthrough_statement.defer_statement.go_statement.labeled_statement`.split(`.`),A=[`use_declaration`,`extern_crate_declaration`,`foreign_mod_item`,`mod_item`,`const_item`,`static_item`,`struct_item`,`enum_item`,`union_item`,`trait_item`,`impl_item`,`function_item`,`function_signature_item`,`type_item`,`associated_type`,`macro_definition`,`field_declaration`,`let_declaration`,`expression_statement`,`else_clause`,`match_arm`],j=`package_declaration.import_declaration.module_declaration.requires_module_directive.exports_module_directive.opens_module_directive.uses_module_directive.provides_module_directive.class_declaration.interface_declaration.enum_declaration.annotation_type_declaration.annotation_type_element_declaration.record_declaration.field_declaration.constant_declaration.method_declaration.constructor_declaration.compact_constructor_declaration.static_initializer.explicit_constructor_invocation.local_variable_declaration.expression_statement.if_statement.while_statement.do_statement.for_statement.enhanced_for_statement.switch_statement.switch_expression.switch_label.break_statement.continue_statement.return_statement.throw_statement.assert_statement.synchronized_statement.labeled_statement.yield_statement.resource.catch_clause.finally_clause`.split(`.`),M=[`elsif`,`else`,`when`,`in_clause`,`rescue`,`ensure`],N=[`program`,`body_statement`,`then`,`else`,`do`,`block_body`,`begin`,`ensure`],P=[`preproc_include`,`preproc_def`,`preproc_function_def`,`declaration`,`type_definition`,`field_declaration`,`function_definition`,`struct_specifier`,`enum_specifier`,`union_specifier`,`expression_statement`,`if_statement`,`else_clause`,`switch_statement`,`case_statement`,`for_statement`,`while_statement`,`do_statement`,`return_statement`,`break_statement`,`continue_statement`,`goto_statement`,`labeled_statement`],F=[...P,`class_specifier`,`namespace_definition`,`using_declaration`,`alias_declaration`,`namespace_alias_definition`,`concept_definition`,`static_assert_declaration`,`for_range_loop`,`catch_clause`,`throw_statement`,`co_return_statement`,`co_yield_statement`];function I(e){return R(e,`default`)?e.default:e}function L(e){return c[e]}function R(e,t){return typeof e!=`object`||!e||!(t in e)?!1:!!e[t]}const z=[{name:`javascript`,aliases:[`js`,`mjs`,`cjs`],parserLanguage:I(i)},{name:`jsx`,parserLanguage:I(i)},{name:`typescript`,aliases:[`ts`],parserLanguage:L(`typescript`)},{name:`tsx`,parserLanguage:L(`tsx`)},{name:`python`,aliases:[`py`],parserLanguage:I(a),ncssNodeTypes:O},{name:`go`,parserLanguage:I(n),decisionNodeTypes:f,nestingNodeTypes:m,ncssNodeTypes:k},{name:`rust`,aliases:[`rs`],parserLanguage:I(s),ncssNodeTypes:A,ncssContainerNodeTypes:[`block`,`else_clause`]},{name:`java`,parserLanguage:I(r),functionNodeTypes:h,classNodeTypes:g,decisionNodeTypes:v,nestingNodeTypes:_,ncssNodeTypes:j},{name:`ruby`,aliases:[`rb`],parserLanguage:I(o),functionNodeTypes:y,classNodeTypes:b,decisionNodeTypes:x,nestingNodeTypes:x,ncssNodeTypes:M,ncssContainerNodeTypes:N},{name:`c`,parserLanguage:I(e),functionNodeTypes:S,classNodeTypes:C,decisionNodeTypes:w,nestingNodeTypes:w,ncssNodeTypes:P},{name:`cpp`,aliases:[`c++`,`cxx`],parserLanguage:I(t),functionNodeTypes:S,classNodeTypes:T,decisionNodeTypes:E,nestingNodeTypes:E,ncssNodeTypes:F}].map(e=>({functionNodeTypes:l,classNodeTypes:u,decisionNodeTypes:d,nestingNodeTypes:p,ncssNodeTypes:D,...e}));function B(e=z){let t=new Map;for(let n of e){t.set(n.name,n);for(let e of n.aliases??[])t.set(e,n)}return t}const V=z.map(e=>e.name);export{B as createLanguageRegistry,z as defaultLanguages,V as supportedLanguages};
2
2
  //# sourceMappingURL=languages.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"languages.js","names":["grammars"],"sources":["../src/languages.ts"],"sourcesContent":["import C from 'tree-sitter-c';\nimport Cpp from 'tree-sitter-cpp';\nimport Go from 'tree-sitter-go';\nimport Java from 'tree-sitter-java';\nimport JavaScript from 'tree-sitter-javascript';\nimport Python from 'tree-sitter-python';\nimport Ruby from 'tree-sitter-ruby';\nimport Rust from 'tree-sitter-rust';\nimport TypeScript from 'tree-sitter-typescript';\nimport type { LanguageDefinition, LanguageName, ParserLanguage } from './types.js';\n\ntype GrammarModule = unknown;\n\nconst commonFunctionNodes = [\n 'function',\n 'function_declaration',\n 'function_definition',\n 'function_expression',\n 'function_item',\n 'function_signature_item',\n 'function_declarator',\n 'func_literal',\n 'method_declaration',\n 'method_definition',\n 'method_spec',\n 'arrow_function',\n 'generator_function',\n 'generator_function_declaration',\n 'lambda',\n 'lambda_expression',\n 'closure_expression',\n] as const;\n\nconst commonClassNodes = [\n 'class',\n 'class_declaration',\n 'class_definition',\n 'interface_declaration',\n 'trait_item',\n 'struct_item',\n 'enum_item',\n 'union_item',\n] as const;\n\nconst commonDecisionNodes = [\n 'if_statement',\n 'elif_clause',\n 'else_if_clause',\n 'for_statement',\n 'for_in_statement',\n 'while_statement',\n 'do_statement',\n 'catch_clause',\n 'except_clause',\n 'case_clause',\n 'switch_case',\n 'match_arm',\n 'conditional_expression',\n 'ternary_expression',\n 'if_expression',\n 'while_expression',\n 'for_expression',\n 'loop_expression',\n] as const;\n\n// Go `switch`/`select` branches are `*_case` nodes, not the `case_clause`/`switch_case` of other grammars.\nconst goDecisionNodes = [...commonDecisionNodes, 'expression_case', 'type_case', 'communication_case'] as const;\n\nconst javaFunctionNodes = [\n ...commonFunctionNodes,\n 'constructor_declaration',\n 'compact_constructor_declaration',\n] as const;\nconst javaClassNodes = [\n ...commonClassNodes,\n 'enum_declaration',\n 'record_declaration',\n 'annotation_type_declaration',\n // Counted only when they carry a `class_body` (anonymous classes, JLS 15.9.5).\n 'object_creation_expression',\n 'enum_constant',\n] as const;\nconst javaDecisionNodes = [\n ...commonDecisionNodes,\n 'enhanced_for_statement',\n 'switch_block_statement_group',\n 'switch_rule',\n] as const;\n\n// Ruby node types are keyword-like (`if`, `while`, ...), so they must stay Ruby-specific: the same\n// strings appear as anonymous keyword tokens in other grammars and would be double-counted there.\n// `block`/`do_block` are Ruby's closures (`items.map { ... }`), the analog of JS callbacks.\nconst rubyFunctionNodes = ['method', 'singleton_method', 'lambda', 'block', 'do_block'] as const;\n// `singleton_class` (`class << self`) opens an eigenclass scope, not a new type declaration.\nconst rubyClassNodes = ['class', 'module'] as const;\nconst rubyDecisionNodes = [\n 'if',\n 'elsif',\n 'unless',\n 'while',\n 'until',\n 'for',\n 'when',\n 'in_clause',\n 'rescue',\n 'conditional',\n 'if_modifier',\n 'unless_modifier',\n 'while_modifier',\n 'until_modifier',\n 'rescue_modifier',\n] as const;\n\n// `function_declarator` must stay out: it is nested inside every `function_definition` (which\n// would double-count) and also appears in body-less prototypes.\nconst cFunctionNodes = ['function_definition', 'lambda_expression'] as const;\nconst cClassNodes = ['struct_specifier', 'enum_specifier', 'union_specifier'] as const;\nconst cDecisionNodes = [...commonDecisionNodes, 'case_statement'] as const;\nconst cppClassNodes = [...cClassNodes, 'class_specifier'] as const;\nconst cppDecisionNodes = [...cDecisionNodes, 'for_range_loop'] as const;\n\nfunction normalizeGrammar(module: GrammarModule): ParserLanguage {\n if (isGrammarWrapper(module, 'default')) {\n return module.default;\n }\n\n return module;\n}\n\nfunction getTypeScriptGrammar(name: 'typescript' | 'tsx'): ParserLanguage {\n const grammars = TypeScript as unknown as Record<string, GrammarModule>;\n return grammars[name];\n}\n\nfunction isGrammarWrapper(value: GrammarModule, key: 'default'): value is Record<typeof key, ParserLanguage> {\n if (typeof value !== 'object' || value === null || !(key in value)) {\n return false;\n }\n\n return Boolean((value as Record<string, ParserLanguage>)[key]);\n}\n\nexport const defaultLanguages: readonly LanguageDefinition[] = [\n {\n name: 'javascript',\n aliases: ['js', 'mjs', 'cjs'],\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'jsx',\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'typescript',\n aliases: ['ts'],\n parserLanguage: getTypeScriptGrammar('typescript'),\n },\n {\n name: 'tsx',\n parserLanguage: getTypeScriptGrammar('tsx'),\n },\n {\n name: 'python',\n aliases: ['py'],\n parserLanguage: normalizeGrammar(Python as unknown as GrammarModule),\n },\n {\n name: 'go',\n parserLanguage: normalizeGrammar(Go as unknown as GrammarModule),\n decisionNodeTypes: goDecisionNodes,\n nestingNodeTypes: goDecisionNodes,\n },\n {\n name: 'rust',\n aliases: ['rs'],\n parserLanguage: normalizeGrammar(Rust as unknown as GrammarModule),\n },\n {\n name: 'java',\n parserLanguage: normalizeGrammar(Java as unknown as GrammarModule),\n functionNodeTypes: javaFunctionNodes,\n classNodeTypes: javaClassNodes,\n decisionNodeTypes: javaDecisionNodes,\n nestingNodeTypes: javaDecisionNodes,\n },\n {\n name: 'ruby',\n aliases: ['rb'],\n parserLanguage: normalizeGrammar(Ruby as unknown as GrammarModule),\n functionNodeTypes: rubyFunctionNodes,\n classNodeTypes: rubyClassNodes,\n decisionNodeTypes: rubyDecisionNodes,\n nestingNodeTypes: rubyDecisionNodes,\n },\n {\n name: 'c',\n parserLanguage: normalizeGrammar(C as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cClassNodes,\n decisionNodeTypes: cDecisionNodes,\n nestingNodeTypes: cDecisionNodes,\n },\n {\n name: 'cpp',\n aliases: ['c++', 'cxx'],\n parserLanguage: normalizeGrammar(Cpp as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cppClassNodes,\n decisionNodeTypes: cppDecisionNodes,\n nestingNodeTypes: cppDecisionNodes,\n },\n].map((language) => ({\n functionNodeTypes: commonFunctionNodes,\n classNodeTypes: commonClassNodes,\n decisionNodeTypes: commonDecisionNodes,\n nestingNodeTypes: commonDecisionNodes,\n ...language,\n}));\n\nexport function createLanguageRegistry(\n languages: readonly LanguageDefinition[] = defaultLanguages\n): Map<LanguageName, LanguageDefinition> {\n const registry = new Map<LanguageName, LanguageDefinition>();\n\n for (const language of languages) {\n registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n registry.set(alias, language);\n }\n }\n\n return registry;\n}\n\nexport const supportedLanguages = defaultLanguages.map((language) => language.name);\n"],"mappings":"wSAaA,MAAM,EAAsB,CAC1B,WACA,uBACA,sBACA,sBACA,gBACA,0BACA,sBACA,eACA,qBACA,oBACA,cACA,iBACA,qBACA,iCACA,SACA,oBACA,oBACF,EAEM,EAAmB,CACvB,QACA,oBACA,mBACA,wBACA,aACA,cACA,YACA,YACF,EAEM,EAAsB,CAC1B,eACA,cACA,iBACA,gBACA,mBACA,kBACA,eACA,eACA,gBACA,cACA,cACA,YACA,yBACA,qBACA,gBACA,mBACA,iBACA,iBACF,EAGM,EAAkB,CAAC,GAAG,EAAqB,kBAAmB,YAAa,oBAAoB,EAE/F,EAAoB,CACxB,GAAG,EACH,0BACA,iCACF,EACM,EAAiB,CACrB,GAAG,EACH,mBACA,qBACA,8BAEA,6BACA,eACF,EACM,EAAoB,CACxB,GAAG,EACH,yBACA,+BACA,aACF,EAKM,EAAoB,CAAC,SAAU,mBAAoB,SAAU,QAAS,UAAU,EAEhF,EAAiB,CAAC,QAAS,QAAQ,EACnC,EAAoB,CACxB,KACA,QACA,SACA,QACA,QACA,MACA,OACA,YACA,SACA,cACA,cACA,kBACA,iBACA,iBACA,iBACF,EAIM,EAAiB,CAAC,sBAAuB,mBAAmB,EAC5D,EAAc,CAAC,m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EACA,CACE,KAAM,MACN,QAAS,CAAC,MAAO,KAAK,EACtB,eAAgB,EAAiB,CAA+B,EAChE,kBAAmB,EACnB,eAAgB,EAChB,kBAAmB,EACnB,iBAAkB,CACpB,CACF,CAAC,CAAC,IAAK,IAAc,CACnB,kBAAmB,EACnB,eAAgB,EAChB,kBAAmB,EACnB,iBAAkB,EAClB,GAAG,CACL,EAAE,EAEF,SAAgB,EACd,EAA2C,EACJ,CACvC,IAAM,EAAW,IAAI,IAErB,IAAK,IAAM,KAAY,EAAW,CAChC,EAAS,IAAI,EAAS,KAAM,CAAQ,EACpC,IAAK,IAAM,KAAS,EAAS,SAAW,CAAC,EACvC,EAAS,IAAI,EAAO,CAAQ,CAEhC,CAEA,OAAO,CACT,CAEA,MAAa,EAAqB,EAAiB,IAAK,GAAa,EAAS,IAAI"}
1
+ {"version":3,"file":"languages.js","names":["grammars"],"sources":["../src/languages.ts"],"sourcesContent":["import C from 'tree-sitter-c';\nimport Cpp from 'tree-sitter-cpp';\nimport Go from 'tree-sitter-go';\nimport Java from 'tree-sitter-java';\nimport JavaScript from 'tree-sitter-javascript';\nimport Python from 'tree-sitter-python';\nimport Ruby from 'tree-sitter-ruby';\nimport Rust from 'tree-sitter-rust';\nimport TypeScript from 'tree-sitter-typescript';\nimport type { LanguageDefinition, LanguageName, ParserLanguage } from './types.js';\n\ntype GrammarModule = unknown;\n\nconst commonFunctionNodes = [\n 'function',\n 'function_declaration',\n 'function_definition',\n 'function_expression',\n 'function_item',\n 'function_signature_item',\n 'function_declarator',\n 'func_literal',\n 'method_declaration',\n 'method_definition',\n 'method_spec',\n 'arrow_function',\n 'generator_function',\n 'generator_function_declaration',\n 'lambda',\n 'lambda_expression',\n 'closure_expression',\n] as const;\n\nconst commonClassNodes = [\n 'class',\n 'class_declaration',\n 'class_definition',\n 'interface_declaration',\n 'trait_item',\n 'struct_item',\n 'enum_item',\n 'union_item',\n] as const;\n\nconst commonDecisionNodes = [\n 'if_statement',\n 'elif_clause',\n 'else_if_clause',\n 'for_statement',\n 'for_in_statement',\n 'while_statement',\n 'do_statement',\n 'catch_clause',\n 'except_clause',\n 'case_clause',\n 'switch_case',\n 'match_arm',\n 'conditional_expression',\n 'ternary_expression',\n 'if_expression',\n 'while_expression',\n 'for_expression',\n 'loop_expression',\n] as const;\n\n// Go `switch`/`select` branches are `*_case` nodes, not the `case_clause`/`switch_case` of other grammars.\nconst goDecisionNodes = [...commonDecisionNodes, 'expression_case', 'type_case', 'communication_case'] as const;\n\n// Default switch branches add no decision, but their contents are nested inside the switch like\n// any other arm, so they appear in the nesting sets only.\nconst commonNestingNodes = [...commonDecisionNodes, 'switch_default'] as const;\nconst goNestingNodes = [...goDecisionNodes, 'default_case'] as const;\n\nconst javaFunctionNodes = [\n ...commonFunctionNodes,\n 'constructor_declaration',\n 'compact_constructor_declaration',\n] as const;\nconst javaClassNodes = [\n ...commonClassNodes,\n 'enum_declaration',\n 'record_declaration',\n 'annotation_type_declaration',\n // Counted only when they carry a `class_body` (anonymous classes, JLS 15.9.5).\n 'object_creation_expression',\n 'enum_constant',\n] as const;\nconst javaDecisionNodes = [\n ...commonDecisionNodes,\n 'enhanced_for_statement',\n 'switch_block_statement_group',\n 'switch_rule',\n] as const;\n// PMD's standard cyclomatic complexity charges `throw` one path (verified against PMD 7.26.0);\n// it stays out of the nesting set (its argument expressions are not nested) and adds no\n// cognitive point (see cyclomaticOnlyNodeTypes in metrics.ts). Other languages follow their own\n// reference tools (lizard/radon), which do not count throw/raise.\nconst javaCyclomaticDecisionNodes = [...javaDecisionNodes, 'throw_statement'] as const;\n\n// Ruby node types are keyword-like (`if`, `while`, ...), so they must stay Ruby-specific: the same\n// strings appear as anonymous keyword tokens in other grammars and would be double-counted there.\n// `block`/`do_block` are Ruby's closures (`items.map { ... }`), the analog of JS callbacks.\nconst rubyFunctionNodes = ['method', 'singleton_method', 'lambda', 'block', 'do_block'] as const;\n// `singleton_class` (`class << self`) opens an eigenclass scope, not a new type declaration.\nconst rubyClassNodes = ['class', 'module'] as const;\nconst rubyDecisionNodes = [\n 'if',\n 'elsif',\n 'unless',\n 'while',\n 'until',\n 'for',\n 'when',\n 'in_clause',\n 'rescue',\n 'conditional',\n 'if_modifier',\n 'unless_modifier',\n 'while_modifier',\n 'until_modifier',\n 'rescue_modifier',\n] as const;\n\n// `function_declarator` must stay out: it is nested inside every `function_definition` (which\n// would double-count) and also appears in body-less prototypes.\nconst cFunctionNodes = ['function_definition', 'lambda_expression'] as const;\nconst cClassNodes = ['struct_specifier', 'enum_specifier', 'union_specifier'] as const;\nconst cDecisionNodes = [...commonDecisionNodes, 'case_statement'] as const;\nconst cppClassNodes = [...cClassNodes, 'class_specifier'] as const;\nconst cppDecisionNodes = [...cDecisionNodes, 'for_range_loop'] as const;\n\n// NCSS node sets: every listed type counts as one non-commenting source statement. The Java set is\n// calibrated against PMD's NcssCount rule (`try` counts 0; `else`, `case`/`default` labels,\n// `catch`, `finally`, and try-with-resources resources count 1 each); the other languages follow\n// the same conventions with their grammar's node types.\nconst jsNcssNodes = [\n 'import_statement',\n 'export_statement',\n 'lexical_declaration',\n 'variable_declaration',\n 'function_declaration',\n 'function_signature',\n 'generator_function_declaration',\n 'class_declaration',\n 'abstract_class_declaration',\n 'module',\n 'method_definition',\n 'abstract_method_signature',\n 'class_static_block',\n 'field_definition',\n 'public_field_definition',\n 'type_alias_declaration',\n 'interface_declaration',\n 'enum_declaration',\n 'expression_statement',\n 'if_statement',\n 'else_clause',\n 'switch_statement',\n 'switch_case',\n 'switch_default',\n 'for_statement',\n 'for_in_statement',\n 'while_statement',\n 'do_statement',\n 'catch_clause',\n 'finally_clause',\n 'labeled_statement',\n 'return_statement',\n 'break_statement',\n 'continue_statement',\n 'throw_statement',\n 'debugger_statement',\n 'with_statement',\n] as const;\n\nconst pythonNcssNodes = [\n 'import_statement',\n 'import_from_statement',\n 'future_import_statement',\n 'print_statement',\n 'exec_statement',\n 'assert_statement',\n 'expression_statement',\n 'return_statement',\n 'delete_statement',\n 'raise_statement',\n 'pass_statement',\n 'break_statement',\n 'continue_statement',\n 'global_statement',\n 'nonlocal_statement',\n 'if_statement',\n 'elif_clause',\n 'else_clause',\n 'for_statement',\n 'while_statement',\n 'except_clause',\n 'except_group_clause',\n 'finally_clause',\n 'with_statement',\n 'match_statement',\n 'case_clause',\n 'function_definition',\n 'class_definition',\n 'type_alias_statement',\n] as const;\n\nconst goNcssNodes = [\n 'package_clause',\n 'import_spec',\n 'type_spec',\n 'type_alias',\n 'const_spec',\n 'var_spec',\n 'function_declaration',\n 'method_declaration',\n // Struct fields and interface members count contextually (see ncss.ts): only inside a named\n // `type T struct/interface { ... }`, not in inline anonymous types, which are part of one\n // declaration.\n 'short_var_declaration',\n 'expression_statement',\n 'send_statement',\n 'inc_statement',\n 'dec_statement',\n 'assignment_statement',\n 'if_statement',\n 'for_statement',\n 'expression_switch_statement',\n 'type_switch_statement',\n 'select_statement',\n 'expression_case',\n 'type_case',\n 'communication_case',\n 'default_case',\n 'return_statement',\n 'break_statement',\n 'continue_statement',\n 'goto_statement',\n 'fallthrough_statement',\n 'defer_statement',\n 'go_statement',\n 'labeled_statement',\n] as const;\n\nconst rustNcssNodes = [\n 'use_declaration',\n 'extern_crate_declaration',\n 'foreign_mod_item',\n 'mod_item',\n 'const_item',\n 'static_item',\n 'struct_item',\n 'enum_item',\n 'union_item',\n 'trait_item',\n 'impl_item',\n 'function_item',\n 'function_signature_item',\n 'type_item',\n 'associated_type',\n 'macro_definition',\n 'field_declaration',\n 'let_declaration',\n 'expression_statement',\n 'else_clause',\n 'match_arm',\n] as const;\n\nconst javaNcssNodes = [\n 'package_declaration',\n 'import_declaration',\n 'module_declaration',\n 'requires_module_directive',\n 'exports_module_directive',\n 'opens_module_directive',\n 'uses_module_directive',\n 'provides_module_directive',\n 'class_declaration',\n 'interface_declaration',\n 'enum_declaration',\n 'annotation_type_declaration',\n 'annotation_type_element_declaration',\n 'record_declaration',\n 'field_declaration',\n 'constant_declaration',\n 'method_declaration',\n 'constructor_declaration',\n 'compact_constructor_declaration',\n 'static_initializer',\n 'explicit_constructor_invocation',\n 'local_variable_declaration',\n 'expression_statement',\n 'if_statement',\n 'while_statement',\n 'do_statement',\n 'for_statement',\n 'enhanced_for_statement',\n 'switch_statement',\n 'switch_expression',\n 'switch_label',\n 'break_statement',\n 'continue_statement',\n 'return_statement',\n 'throw_statement',\n 'assert_statement',\n 'synchronized_statement',\n 'labeled_statement',\n 'yield_statement',\n 'resource',\n 'catch_clause',\n 'finally_clause',\n] as const;\n\n// Ruby statements have no wrapper node types, so bodies are counted positionally (see\n// ncssContainerNodeTypes); only clause nodes hanging off non-container parents need listing.\nconst rubyNcssNodes = ['elsif', 'else', 'when', 'in_clause', 'rescue', 'ensure'] as const;\nconst rubyNcssContainers = [\n 'program',\n 'body_statement',\n 'then',\n 'else',\n 'do',\n 'block_body',\n 'begin',\n 'ensure',\n] as const;\n\nconst cNcssNodes = [\n 'preproc_include',\n 'preproc_def',\n 'preproc_function_def',\n 'declaration',\n 'type_definition',\n 'field_declaration',\n 'function_definition',\n // Counted only when they carry a body (see bodylessNcssSpecifierTypes in ncss.ts).\n 'struct_specifier',\n 'enum_specifier',\n 'union_specifier',\n 'expression_statement',\n 'if_statement',\n 'else_clause',\n 'switch_statement',\n 'case_statement',\n 'for_statement',\n 'while_statement',\n 'do_statement',\n 'return_statement',\n 'break_statement',\n 'continue_statement',\n 'goto_statement',\n 'labeled_statement',\n] as const;\nconst cppNcssNodes = [\n ...cNcssNodes,\n 'class_specifier',\n 'namespace_definition',\n 'using_declaration',\n 'alias_declaration',\n 'namespace_alias_definition',\n 'concept_definition',\n 'static_assert_declaration',\n 'for_range_loop',\n 'catch_clause',\n 'throw_statement',\n 'co_return_statement',\n 'co_yield_statement',\n] as const;\n\nfunction normalizeGrammar(module: GrammarModule): ParserLanguage {\n if (isGrammarWrapper(module, 'default')) {\n return module.default;\n }\n\n return module;\n}\n\nfunction getTypeScriptGrammar(name: 'typescript' | 'tsx'): ParserLanguage {\n const grammars = TypeScript as unknown as Record<string, GrammarModule>;\n return grammars[name];\n}\n\nfunction isGrammarWrapper(value: GrammarModule, key: 'default'): value is Record<typeof key, ParserLanguage> {\n if (typeof value !== 'object' || value === null || !(key in value)) {\n return false;\n }\n\n return Boolean((value as Record<string, ParserLanguage>)[key]);\n}\n\nexport const defaultLanguages: readonly LanguageDefinition[] = [\n {\n name: 'javascript',\n aliases: ['js', 'mjs', 'cjs'],\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'jsx',\n parserLanguage: normalizeGrammar(JavaScript as unknown as GrammarModule),\n },\n {\n name: 'typescript',\n aliases: ['ts'],\n parserLanguage: getTypeScriptGrammar('typescript'),\n },\n {\n name: 'tsx',\n parserLanguage: getTypeScriptGrammar('tsx'),\n },\n {\n name: 'python',\n aliases: ['py'],\n parserLanguage: normalizeGrammar(Python as unknown as GrammarModule),\n ncssNodeTypes: pythonNcssNodes,\n },\n {\n name: 'go',\n parserLanguage: normalizeGrammar(Go as unknown as GrammarModule),\n decisionNodeTypes: goDecisionNodes,\n nestingNodeTypes: goNestingNodes,\n ncssNodeTypes: goNcssNodes,\n },\n {\n name: 'rust',\n aliases: ['rs'],\n parserLanguage: normalizeGrammar(Rust as unknown as GrammarModule),\n ncssNodeTypes: rustNcssNodes,\n // `else_clause` is a container so `else if` chains count the nested if_expression; a plain\n // `else { ... }` is unaffected because its only child is a `block`, itself a container.\n ncssContainerNodeTypes: ['block', 'else_clause'],\n },\n {\n name: 'java',\n parserLanguage: normalizeGrammar(Java as unknown as GrammarModule),\n functionNodeTypes: javaFunctionNodes,\n classNodeTypes: javaClassNodes,\n decisionNodeTypes: javaCyclomaticDecisionNodes,\n nestingNodeTypes: javaDecisionNodes,\n ncssNodeTypes: javaNcssNodes,\n },\n {\n name: 'ruby',\n aliases: ['rb'],\n parserLanguage: normalizeGrammar(Ruby as unknown as GrammarModule),\n functionNodeTypes: rubyFunctionNodes,\n classNodeTypes: rubyClassNodes,\n decisionNodeTypes: rubyDecisionNodes,\n nestingNodeTypes: rubyDecisionNodes,\n ncssNodeTypes: rubyNcssNodes,\n ncssContainerNodeTypes: rubyNcssContainers,\n },\n {\n name: 'c',\n parserLanguage: normalizeGrammar(C as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cClassNodes,\n decisionNodeTypes: cDecisionNodes,\n nestingNodeTypes: cDecisionNodes,\n ncssNodeTypes: cNcssNodes,\n },\n {\n name: 'cpp',\n aliases: ['c++', 'cxx'],\n parserLanguage: normalizeGrammar(Cpp as unknown as GrammarModule),\n functionNodeTypes: cFunctionNodes,\n classNodeTypes: cppClassNodes,\n decisionNodeTypes: cppDecisionNodes,\n nestingNodeTypes: cppDecisionNodes,\n ncssNodeTypes: cppNcssNodes,\n },\n].map((language) => ({\n functionNodeTypes: commonFunctionNodes,\n classNodeTypes: commonClassNodes,\n decisionNodeTypes: commonDecisionNodes,\n nestingNodeTypes: commonNestingNodes,\n ncssNodeTypes: jsNcssNodes,\n ...language,\n}));\n\nexport function createLanguageRegistry(\n languages: readonly LanguageDefinition[] = defaultLanguages\n): Map<LanguageName, LanguageDefinition> {\n const registry = new Map<LanguageName, LanguageDefinition>();\n\n for (const language of languages) {\n registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n registry.set(alias, language);\n }\n }\n\n return registry;\n}\n\nexport const supportedLanguages = defaultLanguages.map((language) => language.name);\n"],"mappings":"wSAaA,MAAM,EAAsB,CAC1B,WACA,uBACA,sBACA,sBACA,gBACA,0BACA,sBACA,eACA,qBACA,oBACA,cACA,iBACA,qBACA,iCACA,SACA,oBACA,oBACF,EAEM,EAAmB,CACvB,QACA,oBACA,mBACA,wBACA,aACA,cACA,YACA,YACF,EAEM,EAAsB,CAC1B,eACA,cACA,iBACA,gBACA,mBACA,kBACA,eACA,eACA,gBACA,cACA,cACA,YACA,yBACA,qBACA,gBACA,mBACA,iBACA,iBACF,EAGM,EAAkB,CAAC,GAAG,EAAq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