@mduenas/codegraph 0.6.10 → 0.7.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.
@@ -268,6 +268,50 @@ function isSwiftConstant(node) {
268
268
  }
269
269
  return false;
270
270
  }
271
+ // =============================================================================
272
+ // Objective-C-specific Helper Functions
273
+ // =============================================================================
274
+ /**
275
+ * Lines that consist only of a nullability/audit region macro
276
+ * (NS_ASSUME_NONNULL_BEGIN, NS_HEADER_AUDIT_END(...), ...). tree-sitter-objc
277
+ * mis-parses the declaration that follows such a line, so they are blanked
278
+ * out (length-preserving) before parsing.
279
+ */
280
+ const OBJC_REGION_MACRO_LINE = /^[ \t]*(?:(?:NS|CF)_ASSUME_NONNULL_(?:BEGIN|END)|(?:NS|CF)_HEADER_AUDIT_(?:BEGIN|END)(?:\([^)\n]*\))?)[ \t]*(?:\/\/.*)?$/gm;
281
+ /**
282
+ * Attribute/availability macros placed in front of @interface, @protocol or
283
+ * @implementation (e.g. `NS_SWIFT_NAME(Foo)`, `API_AVAILABLE(ios(13.0))`,
284
+ * `__attribute__((objc_subclassing_restricted))`). Blanked before parsing.
285
+ */
286
+ const OBJC_DECL_PREFIX_MACROS = /^[ \t]*(?:(?:[A-Z][A-Z0-9_]*|__attribute__)[ \t]*(?:\((?:[^()\n]|\((?:[^()\n]|\([^()\n]*\))*\))*\))?\s+)+(?=@(?:interface|protocol|implementation)\b)/gm;
287
+ /**
288
+ * `typedef NS_ENUM(NSInteger, Name) { ... };` (also NS_OPTIONS,
289
+ * NS_CLOSED_ENUM, NS_ERROR_ENUM). The grammar cannot parse these macro
290
+ * forms, so they are extracted with a regex and blanked before parsing.
291
+ * Group 1 is the enum name, group 2 the body.
292
+ */
293
+ const OBJC_NS_ENUM = /typedef\s+NS_(?:CLOSED_)?(?:ENUM|OPTIONS|ERROR_ENUM)\s*\(\s*[A-Za-z_][\w\s]*?,\s*([A-Za-z_]\w*)\s*\)\s*\{([^}]*)\}\s*(?:NS_[A-Z_]+(?:\([^)]*\))?\s*)*;?/g;
294
+ /** Replace every character except newlines with a space (keeps offsets and line numbers). */
295
+ function blankOut(text) {
296
+ return text.replace(/[^\r\n]/g, ' ');
297
+ }
298
+ /**
299
+ * Resolve the declared identifier of a (possibly nested) C declarator, e.g.
300
+ * `*name`, `(^handler)(int)`, `argv[]`, `helper(int x)`.
301
+ */
302
+ function getObjcDeclaratorName(node, source, depth = 0) {
303
+ if (!node || depth > 12)
304
+ return null;
305
+ if (node.type === 'identifier' || node.type === 'field_identifier') {
306
+ return getNodeText(node, source);
307
+ }
308
+ const next = node.childForFieldName('declarator') ?? node.namedChild(0);
309
+ return getObjcDeclaratorName(next, source, depth + 1);
310
+ }
311
+ /** Collapse whitespace so multi-line declarations make readable signatures. */
312
+ function tidySignature(text) {
313
+ return text.replace(/\s+/g, ' ').replace(/\s*[;{]\s*$/, '').trim();
314
+ }
271
315
  /**
272
316
  * Language-specific extractors
273
317
  */
@@ -682,6 +726,21 @@ const EXTRACTORS = {
682
726
  return 'public';
683
727
  },
684
728
  },
729
+ objc: {
730
+ // Class/category/protocol/method/property/function extraction is handled
731
+ // by visitObjcNode(); the generic tables below cover the C subset.
732
+ functionTypes: ['function_definition'],
733
+ classTypes: [],
734
+ methodTypes: [],
735
+ interfaceTypes: [],
736
+ structTypes: ['struct_specifier'],
737
+ enumTypes: ['enum_specifier'],
738
+ importTypes: ['preproc_include', 'module_import'],
739
+ callTypes: ['call_expression', 'message_expression'],
740
+ nameField: 'declarator',
741
+ bodyField: 'body',
742
+ paramsField: 'parameters',
743
+ },
685
744
  swift: {
686
745
  functionTypes: ['function_declaration'],
687
746
  classTypes: ['class_declaration'],
@@ -858,7 +917,7 @@ class TreeSitterExtractor {
858
917
  constructor(filePath, source, language) {
859
918
  this.filePath = filePath;
860
919
  this.source = source;
861
- this.language = language || (0, grammars_1.detectLanguage)(filePath);
920
+ this.language = language || (0, grammars_1.detectLanguage)(filePath, source);
862
921
  this.extractor = EXTRACTORS[this.language] || null;
863
922
  }
864
923
  /**
@@ -896,11 +955,21 @@ class TreeSitterExtractor {
896
955
  };
897
956
  }
898
957
  try {
899
- const parseResult = parser.parse(this.source);
958
+ let parseSource = this.source;
959
+ let objcEnums = [];
960
+ if (this.language === 'objc') {
961
+ const prepared = this.prepareObjcSource();
962
+ parseSource = prepared.parseSource;
963
+ objcEnums = prepared.enums;
964
+ }
965
+ const parseResult = parser.parse(parseSource);
900
966
  if (!parseResult)
901
967
  throw new Error('Parser returned null');
902
968
  this.tree = parseResult;
903
969
  this.visitNode(this.tree.rootNode);
970
+ for (const match of objcEnums) {
971
+ this.extractObjcNsEnum(match);
972
+ }
904
973
  }
905
974
  catch (error) {
906
975
  this.errors.push({
@@ -922,6 +991,9 @@ class TreeSitterExtractor {
922
991
  visitNode(node) {
923
992
  if (!this.extractor)
924
993
  return;
994
+ if (this.language === 'objc' && this.visitObjcNode(node)) {
995
+ return;
996
+ }
925
997
  const nodeType = node.type;
926
998
  let skipChildren = false;
927
999
  // Check for function declarations
@@ -1281,6 +1353,14 @@ class TreeSitterExtractor {
1281
1353
  moduleName = getNodeText(path, this.source).replace(/['"]/g, '');
1282
1354
  }
1283
1355
  }
1356
+ else if (this.language === 'objc') {
1357
+ // #import <Foundation/Foundation.h> | #import "Foo.h" | @import UIKit;
1358
+ const target = getChildByField(node, 'path') || node.namedChild(0);
1359
+ if (target) {
1360
+ const inner = target.type === 'string_literal' ? target.namedChild(0) : null;
1361
+ moduleName = getNodeText(inner || target, this.source).replace(/^[<"]|[>"]$/g, '');
1362
+ }
1363
+ }
1284
1364
  else {
1285
1365
  // Generic extraction
1286
1366
  moduleName = importText;
@@ -1307,6 +1387,10 @@ class TreeSitterExtractor {
1307
1387
  const callerId = this.nodeStack[this.nodeStack.length - 1];
1308
1388
  if (!callerId)
1309
1389
  return;
1390
+ if (node.type === 'message_expression') {
1391
+ this.extractObjcMessageSend(node, callerId);
1392
+ return;
1393
+ }
1310
1394
  // Get the function/method being called
1311
1395
  let calleeName = '';
1312
1396
  const func = getChildByField(node, 'function') || node.namedChild(0);
@@ -1401,6 +1485,364 @@ class TreeSitterExtractor {
1401
1485
  }
1402
1486
  }
1403
1487
  // =============================================================================
1488
+ // Objective-C-specific Extraction Methods
1489
+ // =============================================================================
1490
+ /**
1491
+ * Prepare Objective-C source for parsing: blank out constructs the grammar
1492
+ * cannot handle (length-preserving, so node positions still match the
1493
+ * original source) and collect NS_ENUM-style typedefs for regex extraction.
1494
+ */
1495
+ prepareObjcSource() {
1496
+ const enums = [];
1497
+ const enumRegex = new RegExp(OBJC_NS_ENUM.source, 'g');
1498
+ let match;
1499
+ while ((match = enumRegex.exec(this.source)) !== null) {
1500
+ enums.push(match);
1501
+ }
1502
+ let parseSource = this.source
1503
+ .replace(OBJC_REGION_MACRO_LINE, blankOut)
1504
+ .replace(OBJC_DECL_PREFIX_MACROS, blankOut);
1505
+ for (const m of enums) {
1506
+ parseSource =
1507
+ parseSource.slice(0, m.index) + blankOut(m[0]) + parseSource.slice(m.index + m[0].length);
1508
+ }
1509
+ return { parseSource, enums };
1510
+ }
1511
+ /** Convert a character index in the original source to a row/column. */
1512
+ positionAt(index) {
1513
+ let row = 0;
1514
+ let lineStart = 0;
1515
+ for (let i = this.source.indexOf('\n'); i !== -1 && i < index; i = this.source.indexOf('\n', i + 1)) {
1516
+ row++;
1517
+ lineStart = i + 1;
1518
+ }
1519
+ return { row, column: index - lineStart };
1520
+ }
1521
+ /**
1522
+ * Extract `typedef NS_ENUM(Type, Name) { A, B = 2 };` as an enum with members.
1523
+ */
1524
+ extractObjcNsEnum(match) {
1525
+ const name = match[1];
1526
+ if (!name)
1527
+ return;
1528
+ const start = match.index;
1529
+ const end = start + match[0].length;
1530
+ const enumNode = this.createNode('enum', name, { startPosition: this.positionAt(start), endPosition: this.positionAt(end) }, { signature: tidySignature(match[0].slice(0, match[0].indexOf('{'))) });
1531
+ const bodyStart = start + match[0].indexOf('{') + 1;
1532
+ const body = (match[2] ?? '').replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, blankOut);
1533
+ const memberRegex = /(?:^|,)\s*([A-Za-z_]\w*)/g;
1534
+ let member;
1535
+ this.nodeStack.push(enumNode.id);
1536
+ while ((member = memberRegex.exec(body)) !== null) {
1537
+ const memberName = member[1];
1538
+ if (!memberName)
1539
+ continue;
1540
+ const nameIndex = bodyStart + member.index + member[0].lastIndexOf(memberName);
1541
+ const pos = this.positionAt(nameIndex);
1542
+ this.createNode('enum_member', memberName, {
1543
+ startPosition: pos,
1544
+ endPosition: { row: pos.row, column: pos.column + memberName.length },
1545
+ });
1546
+ }
1547
+ this.nodeStack.pop();
1548
+ }
1549
+ /**
1550
+ * Dispatch Objective-C-specific node types. Returns true when the node
1551
+ * (including its children) was fully handled.
1552
+ */
1553
+ visitObjcNode(node) {
1554
+ switch (node.type) {
1555
+ case 'class_interface':
1556
+ case 'class_implementation':
1557
+ this.extractObjcClass(node);
1558
+ return true;
1559
+ case 'protocol_declaration':
1560
+ this.extractObjcProtocol(node);
1561
+ return true;
1562
+ case 'method_declaration':
1563
+ case 'method_definition':
1564
+ this.extractObjcMethod(node);
1565
+ return true;
1566
+ case 'property_declaration':
1567
+ this.extractObjcProperty(node);
1568
+ return true;
1569
+ case 'instance_variables':
1570
+ this.extractObjcInstanceVariables(node);
1571
+ return true;
1572
+ case 'function_definition':
1573
+ this.extractObjcFunction(node);
1574
+ return true;
1575
+ case 'class_declaration': // @class Foo, Bar;
1576
+ case 'protocol_forward_declaration': // @protocol Foo;
1577
+ return true;
1578
+ default:
1579
+ return false;
1580
+ }
1581
+ }
1582
+ /**
1583
+ * Extract @interface / @implementation, including categories
1584
+ * (`@interface Foo (Extras)`) and class extensions (`@interface Foo ()`).
1585
+ */
1586
+ extractObjcClass(node) {
1587
+ let baseName = null;
1588
+ let superclass = null;
1589
+ let category = null;
1590
+ let hasCategoryParens = false;
1591
+ for (let i = 0; i < node.childCount; i++) {
1592
+ const child = node.child(i);
1593
+ if (!child)
1594
+ continue;
1595
+ const field = node.fieldNameForChild(i);
1596
+ if (child.type === '(')
1597
+ hasCategoryParens = true;
1598
+ if (child.type !== 'identifier')
1599
+ continue;
1600
+ if (field === 'superclass')
1601
+ superclass = child;
1602
+ else if (field === 'category')
1603
+ category = getNodeText(child, this.source);
1604
+ else if (baseName === null)
1605
+ baseName = getNodeText(child, this.source);
1606
+ }
1607
+ if (!baseName)
1608
+ return;
1609
+ const isImplementation = node.type === 'class_implementation';
1610
+ const isCategory = category !== null || hasCategoryParens;
1611
+ const name = isCategory ? `${baseName}(${category ?? ''})` : baseName;
1612
+ const headerEnd = node.text.search(/[\n{]/);
1613
+ const classNode = this.createNode('class', name, node, {
1614
+ docstring: getPrecedingDocstring(node, this.source),
1615
+ signature: tidySignature(headerEnd === -1 ? node.text : node.text.slice(0, headerEnd)),
1616
+ });
1617
+ if (isCategory) {
1618
+ this.pushObjcRef(classNode.id, baseName, 'extends', node);
1619
+ }
1620
+ if (!isImplementation) {
1621
+ if (superclass) {
1622
+ this.pushObjcRef(classNode.id, getNodeText(superclass, this.source), 'extends', superclass);
1623
+ }
1624
+ for (let i = 0; i < node.namedChildCount; i++) {
1625
+ const child = node.namedChild(i);
1626
+ if (child?.type !== 'parameterized_arguments')
1627
+ continue;
1628
+ // `Box<ObjectType> : NSObject <P>`: a list before the superclass is
1629
+ // the lightweight-generics parameter list, not protocol conformance.
1630
+ if (superclass && child.startIndex < superclass.startIndex)
1631
+ continue;
1632
+ for (let j = 0; j < child.namedChildCount; j++) {
1633
+ const protocol = child.namedChild(j);
1634
+ if (protocol) {
1635
+ this.pushObjcRef(classNode.id, getNodeText(protocol, this.source), 'implements', protocol);
1636
+ }
1637
+ }
1638
+ }
1639
+ }
1640
+ this.nodeStack.push(classNode.id);
1641
+ for (let i = 0; i < node.namedChildCount; i++) {
1642
+ const child = node.namedChild(i);
1643
+ if (child)
1644
+ this.visitNode(child);
1645
+ }
1646
+ this.nodeStack.pop();
1647
+ }
1648
+ /**
1649
+ * Extract @protocol declarations.
1650
+ */
1651
+ extractObjcProtocol(node) {
1652
+ let name = null;
1653
+ for (let i = 0; i < node.namedChildCount; i++) {
1654
+ const child = node.namedChild(i);
1655
+ if (child?.type === 'identifier') {
1656
+ name = getNodeText(child, this.source);
1657
+ break;
1658
+ }
1659
+ }
1660
+ if (!name)
1661
+ return;
1662
+ const headerEnd = node.text.search(/[\n]/);
1663
+ const protocolNode = this.createNode('interface', name, node, {
1664
+ docstring: getPrecedingDocstring(node, this.source),
1665
+ signature: tidySignature(headerEnd === -1 ? node.text : node.text.slice(0, headerEnd)),
1666
+ });
1667
+ for (let i = 0; i < node.namedChildCount; i++) {
1668
+ const child = node.namedChild(i);
1669
+ if (child?.type !== 'protocol_reference_list')
1670
+ continue;
1671
+ for (let j = 0; j < child.namedChildCount; j++) {
1672
+ const parent = child.namedChild(j);
1673
+ if (parent) {
1674
+ this.pushObjcRef(protocolNode.id, getNodeText(parent, this.source), 'extends', parent);
1675
+ }
1676
+ }
1677
+ }
1678
+ this.nodeStack.push(protocolNode.id);
1679
+ for (let i = 0; i < node.namedChildCount; i++) {
1680
+ const child = node.namedChild(i);
1681
+ if (child)
1682
+ this.visitNode(child);
1683
+ }
1684
+ this.nodeStack.pop();
1685
+ }
1686
+ /**
1687
+ * Build the full selector of a method, e.g. `addA:toB:` or `shared`.
1688
+ * Trailing attribute macros (NS_DESIGNATED_INITIALIZER, ...) are ignored.
1689
+ */
1690
+ getObjcSelector(node) {
1691
+ let selector = '';
1692
+ let sawFirstPart = false;
1693
+ for (let i = 0; i < node.namedChildCount; i++) {
1694
+ const child = node.namedChild(i);
1695
+ if (!child)
1696
+ continue;
1697
+ if (child.type === 'identifier') {
1698
+ const hasArgument = node.namedChild(i + 1)?.type === 'method_parameter';
1699
+ if (!sawFirstPart || hasArgument) {
1700
+ selector += getNodeText(child, this.source) + (hasArgument ? ':' : '');
1701
+ sawFirstPart = true;
1702
+ }
1703
+ }
1704
+ else if (child.type === 'method_parameter' && sawFirstPart) {
1705
+ // Keyword part with an empty name (`- (void)foo:(int)a :(int)b`).
1706
+ if (node.namedChild(i - 1)?.type === 'method_parameter')
1707
+ selector += ':';
1708
+ }
1709
+ }
1710
+ return selector;
1711
+ }
1712
+ /**
1713
+ * Extract a method declaration or definition (instance `-` or class `+`).
1714
+ */
1715
+ extractObjcMethod(node) {
1716
+ const name = this.getObjcSelector(node);
1717
+ if (!name)
1718
+ return;
1719
+ const body = node.namedChildren.find((c) => c?.type === 'compound_statement') ?? null;
1720
+ const signatureEnd = body ? body.startIndex : node.endIndex;
1721
+ const methodNode = this.createNode('method', name, node, {
1722
+ docstring: getPrecedingDocstring(node, this.source),
1723
+ signature: tidySignature(this.source.slice(node.startIndex, signatureEnd)),
1724
+ isStatic: node.child(0)?.type === '+',
1725
+ });
1726
+ if (body) {
1727
+ this.nodeStack.push(methodNode.id);
1728
+ this.visitFunctionBody(body, methodNode.id);
1729
+ this.nodeStack.pop();
1730
+ }
1731
+ }
1732
+ /**
1733
+ * Extract an @property declaration.
1734
+ */
1735
+ extractObjcProperty(node) {
1736
+ const declaration = node.namedChildren.find((c) => c?.type === 'struct_declaration') ?? null;
1737
+ const declarator = declaration?.namedChildren.find((c) => c?.type === 'struct_declarator') ?? null;
1738
+ const name = getObjcDeclaratorName(declarator ?? null, this.source);
1739
+ if (!name)
1740
+ return;
1741
+ const attributes = node.namedChildren.find((c) => c?.type === 'property_attributes_declaration');
1742
+ const isClassProperty = !!attributes && /\bclass\b/.test(attributes.text);
1743
+ this.createNode('property', name, node, {
1744
+ docstring: getPrecedingDocstring(node, this.source),
1745
+ signature: tidySignature(node.text),
1746
+ isStatic: isClassProperty,
1747
+ });
1748
+ }
1749
+ /**
1750
+ * Extract instance variables declared in an `@interface Foo { ... }` or
1751
+ * `@implementation Foo { ... }` block.
1752
+ */
1753
+ extractObjcInstanceVariables(node) {
1754
+ for (let i = 0; i < node.namedChildCount; i++) {
1755
+ const variable = node.namedChild(i);
1756
+ if (variable?.type !== 'instance_variable')
1757
+ continue;
1758
+ for (let j = 0; j < variable.namedChildCount; j++) {
1759
+ const declaration = variable.namedChild(j);
1760
+ if (declaration?.type !== 'struct_declaration')
1761
+ continue;
1762
+ for (let k = 0; k < declaration.namedChildCount; k++) {
1763
+ const declarator = declaration.namedChild(k);
1764
+ if (declarator?.type !== 'struct_declarator')
1765
+ continue;
1766
+ const name = getObjcDeclaratorName(declarator, this.source);
1767
+ if (name) {
1768
+ this.createNode('field', name, declaration, {
1769
+ signature: tidySignature(declaration.text),
1770
+ });
1771
+ }
1772
+ }
1773
+ }
1774
+ }
1775
+ }
1776
+ /**
1777
+ * Extract a plain C function defined in an Objective-C file.
1778
+ */
1779
+ extractObjcFunction(node) {
1780
+ const name = getObjcDeclaratorName(node.childForFieldName('declarator'), this.source);
1781
+ if (!name) {
1782
+ // Unparseable fragment (e.g. unknown macro): still look inside it.
1783
+ for (let i = 0; i < node.namedChildCount; i++) {
1784
+ const child = node.namedChild(i);
1785
+ if (child)
1786
+ this.visitNode(child);
1787
+ }
1788
+ return;
1789
+ }
1790
+ const body = node.childForFieldName('body');
1791
+ const isStaticFunction = node.namedChildren.some((c) => c?.type === 'storage_class_specifier' && c.text === 'static');
1792
+ const funcNode = this.createNode('function', name, node, {
1793
+ docstring: getPrecedingDocstring(node, this.source),
1794
+ signature: tidySignature(this.source.slice(node.startIndex, body ? body.startIndex : node.endIndex)),
1795
+ isExported: !isStaticFunction,
1796
+ });
1797
+ if (body) {
1798
+ this.nodeStack.push(funcNode.id);
1799
+ this.visitFunctionBody(body, funcNode.id);
1800
+ this.nodeStack.pop();
1801
+ }
1802
+ }
1803
+ /**
1804
+ * Record a message send `[receiver doThing:a withB:b]` as a call to the
1805
+ * selector `doThing:withB:`, plus a reference to the receiver when it is a
1806
+ * class name (`[Foo shared]`, `[[Foo alloc] init]`).
1807
+ */
1808
+ extractObjcMessageSend(node, callerId) {
1809
+ let selector = '';
1810
+ for (let i = 0; i < node.childCount; i++) {
1811
+ if (node.fieldNameForChild(i) !== 'method')
1812
+ continue;
1813
+ const part = node.child(i);
1814
+ if (!part)
1815
+ continue;
1816
+ selector += getNodeText(part, this.source) + (node.child(i + 1)?.type === ':' ? ':' : '');
1817
+ }
1818
+ if (!selector)
1819
+ return;
1820
+ this.unresolvedReferences.push({
1821
+ fromNodeId: callerId,
1822
+ referenceName: selector,
1823
+ referenceKind: 'calls',
1824
+ line: node.startPosition.row + 1,
1825
+ column: node.startPosition.column,
1826
+ });
1827
+ const receiver = node.childForFieldName('receiver');
1828
+ if (receiver?.type === 'identifier') {
1829
+ const receiverName = getNodeText(receiver, this.source);
1830
+ if (/^[A-Z]/.test(receiverName)) {
1831
+ const creates = selector === 'alloc' || selector === 'new';
1832
+ this.pushObjcRef(callerId, receiverName, creates ? 'instantiates' : 'references', receiver);
1833
+ }
1834
+ }
1835
+ }
1836
+ pushObjcRef(fromNodeId, referenceName, referenceKind, at) {
1837
+ this.unresolvedReferences.push({
1838
+ fromNodeId,
1839
+ referenceName,
1840
+ referenceKind,
1841
+ line: at.startPosition.row + 1,
1842
+ column: at.startPosition.column,
1843
+ });
1844
+ }
1845
+ // =============================================================================
1404
1846
  // Kotlin-specific Extraction Methods
1405
1847
  // =============================================================================
1406
1848
  /**
@@ -2396,7 +2838,7 @@ exports.LiquidExtractor = LiquidExtractor;
2396
2838
  * Extract nodes and edges from source code
2397
2839
  */
2398
2840
  function extractFromSource(filePath, source, language) {
2399
- const detectedLanguage = language || (0, grammars_1.detectLanguage)(filePath);
2841
+ const detectedLanguage = language || (0, grammars_1.detectLanguage)(filePath, source);
2400
2842
  // Use custom extractor for Liquid
2401
2843
  if (detectedLanguage === 'liquid') {
2402
2844
  const extractor = new LiquidExtractor(filePath, source);