feat(resolution): mixed iOS / React Native / Expo cross-language bridging (#430)
Implements the design from `docs/design/mixed-ios-and-react-native-bridging.md`.
Closes the cross-language flow gap so `trace` / `callers` / `callees` / `impact` connect end-to-end across language boundaries in real iOS, React Native, and Expo codebases.
## Bridges shipped
| Boundary | Mechanism | Real-codebase validation |
|---|---|---|
| **Swift ↔ Objective-C** | Resolver applying Apple's @objc auto-bridging name math + Cocoa preposition prefixes | Charts (S, 269) · realm-swift (M, 369) · wikipedia-ios (L, 1734) |
| **React Native legacy bridge** | Resolver parsing `RCT_EXPORT_MODULE` / `RCT_EXPORT_METHOD` / `RCT_REMAP_METHOD` (ObjC) + `@ReactMethod` (Java/Kotlin) | AsyncStorage (S, ~60) · react-native-svg (M, ~700) · react-native-firebase (L, ~1100) |
| **React Native TurboModules** | Resolver treating `Native<X>.ts` spec interface as ground truth | via RNSvg + RNFirebase subsets |
| **Native → JS events** | Synthesizer matching native `sendEventWithName:`/`emit(...)` to JS `addListener('e', handler)` keyed by literal event name; falls back to enclosing constant/variable for wrapper-API parameter handlers | RNGeolocation (S) · RNFirebase (L) |
| **Expo Modules** | Framework extract synthesizes `method` nodes from Swift/Kotlin `Module { Name("X"); Function("y") { ... } }` DSL | expo-haptics (S, 14) · expo-camera (M, 72) · ExpoSweep (L, 332, 7 packages) |
| **Fabric + legacy Paper view components** | Extract `component` + `property` nodes from Codegen `codegenNativeComponent<Props>('Name', ...)` specs AND legacy `RCT_EXPORT_VIEW_PROPERTY` / `@ReactProp` macros, then synthesize component → native class by name+suffix convention | react-native-segmented-control (S, legacy) · react-native-screens (M, Codegen) · react-native-skia (L, hybrid monorepo) |
## Bug fixes surfaced along the way
- `tree-sitter.ts` message_expression — multi-keyword ObjC call sites now reconstruct `a🅱️` selectors so they resolve to multi-part method definitions (gap discovered post-#165; 0 → 84 call edges to `GET:parameters:...` style methods on AFNetworking).
- `src/index.ts` resolver lifecycle — `indexAll()` now re-initializes the resolver after extraction so framework `detect()` sees the populated index. Pre-existing latent bug that affected UIKit and SwiftUI resolvers too.
- `src/extraction/index.ts` `buildDetectionContext` — added `listDirectories` so framework detect() can probe monorepo subpackages uniformly (fix needed for react-native-skia detection).
## Regression check on 5 control repos
| Repo | Result |
|---|---|
| Express (small JS) | ✅ unchanged — 266 routes, express framework detected |
| Excalidraw (medium TS/React) | ✅ 9284 nodes (CLAUDE.md baseline ~9290); canonical `trace(mutateElement, renderStaticScene)` returns the flow |
| Django realworld (Python) | ✅ django framework detected, 16 routes |
| Spring petclinic (Java) | ✅ spring framework detected, 17 routes |
| Texture (pure ObjC, large) | ✅ exactly matches #165 baseline: 4702 methods, 894 classes, 808/808 file coverage, 913 multi-keyword selectors, 55 protocols, 1036 properties |
## Tests
928 passing (+87 net new bridge tests across the 5 channels); 2 pre-existing skips. The mcp-staleness-banner / watcher parallel flakiness is unchanged by this work (different test fails each run, all pass in isolation; pre-existing on main).
## Documentation
- README: new 'Mixed iOS / React Native / Expo bridging' section with the per-boundary table and validation-corpus links.
- CHANGELOG `[Unreleased]`: full entry per bridge with measurements.
- `docs/design/mixed-ios-and-react-native-bridging.md`: the design doc (§8 measurements filled in across §8a-§8g).
- `docs/design/dynamic-dispatch-coverage-playbook.md` §6 coverage matrix: six new rows.
- `.claude/skills/agent-eval/corpus.json`: four new sections covering 15 real GitHub repos for the eval harness.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import * as os from 'node:os';
|
||||
import { CodeGraph } from '../src';
|
||||
import { expoModulesResolver } from '../src/resolution/frameworks/expo-modules';
|
||||
|
||||
describe('Expo Modules framework extractor', () => {
|
||||
it('extracts AsyncFunction / Function / Property literals as method nodes', () => {
|
||||
const source = `
|
||||
import ExpoModulesCore
|
||||
|
||||
public class HapticsModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("ExpoHaptics")
|
||||
|
||||
AsyncFunction("notificationAsync") { (notificationType: NotificationType) in
|
||||
// body
|
||||
}
|
||||
|
||||
AsyncFunction("impactAsync") { (style: ImpactStyle) in
|
||||
// body
|
||||
}
|
||||
|
||||
Function("synchronousThing") {
|
||||
return 1
|
||||
}
|
||||
|
||||
Property("isAvailable") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
const result = expoModulesResolver.extract?.('ios/HapticsModule.swift', source);
|
||||
expect(result).toBeDefined();
|
||||
const names = result!.nodes.map((n) => n.name);
|
||||
expect(names).toEqual(
|
||||
expect.arrayContaining(['notificationAsync', 'impactAsync', 'synchronousThing', 'isAvailable'])
|
||||
);
|
||||
expect(result!.nodes.every((n) => n.kind === 'method')).toBe(true);
|
||||
expect(result!.nodes.every((n) => n.qualifiedName.includes('ExpoHaptics.'))).toBe(true);
|
||||
});
|
||||
|
||||
it('falls back to the class name when the Module has no Name("X") literal', () => {
|
||||
const source = `
|
||||
public class BareModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Function("doX") { return 1 }
|
||||
}
|
||||
}
|
||||
`;
|
||||
const result = expoModulesResolver.extract?.('ios/BareModule.swift', source);
|
||||
// BareModule is used as the qualifier since there's no Name() literal.
|
||||
expect(result!.nodes[0]?.qualifiedName).toContain('BareModule.doX');
|
||||
});
|
||||
|
||||
it('returns no nodes for a Swift file that is not an Expo Module', () => {
|
||||
const source = `
|
||||
class Helper {
|
||||
func doX() { }
|
||||
}
|
||||
`;
|
||||
const result = expoModulesResolver.extract?.('Helper.swift', source);
|
||||
expect(result?.nodes).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('also extracts from Kotlin module files', () => {
|
||||
const source = `
|
||||
class FooModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("ExpoFoo")
|
||||
AsyncFunction("doAsync") { name: String -> name.uppercase() }
|
||||
Function("doSync") { 42 }
|
||||
}
|
||||
}
|
||||
`;
|
||||
const result = expoModulesResolver.extract?.('FooModule.kt', source);
|
||||
expect(result?.nodes.length).toBe(2);
|
||||
expect(result?.nodes.map((n) => n.name).sort()).toEqual(['doAsync', 'doSync']);
|
||||
expect(result?.nodes.every((n) => n.language === 'kotlin')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Expo Modules end-to-end — JS caller → native AsyncFunction', () => {
|
||||
let dir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'expo-modules-fixture-'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('JS callsite of a literal AsyncFunction("name") resolves to the native impl node', async () => {
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'package.json'),
|
||||
'{"dependencies":{"expo-modules-core":"^1.0.0"}}'
|
||||
);
|
||||
fs.mkdirSync(path.join(dir, 'ios'));
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'ios', 'HapticsModule.swift'),
|
||||
`
|
||||
import ExpoModulesCore
|
||||
public class HapticsModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("ExpoHaptics")
|
||||
AsyncFunction("uniqueExpoHapticCall") { in /* … */ }
|
||||
}
|
||||
}
|
||||
`
|
||||
);
|
||||
fs.mkdirSync(path.join(dir, 'src'));
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'src', 'index.ts'),
|
||||
`
|
||||
import { requireNativeModule } from 'expo-modules-core';
|
||||
const Haptics = requireNativeModule('ExpoHaptics');
|
||||
export async function impactAsync() {
|
||||
return await Haptics.uniqueExpoHapticCall();
|
||||
}
|
||||
`
|
||||
);
|
||||
|
||||
const cg = await CodeGraph.init(dir, { silent: true });
|
||||
await cg.indexAll();
|
||||
const db = (cg as any).db.db;
|
||||
|
||||
// The native method node should exist.
|
||||
const native = db
|
||||
.prepare(
|
||||
"SELECT * FROM nodes WHERE kind='method' AND name='uniqueExpoHapticCall' AND id LIKE 'expo-module:%'"
|
||||
)
|
||||
.all();
|
||||
expect(native).toHaveLength(1);
|
||||
|
||||
// And the JS callsite should produce a call edge targeting it.
|
||||
const callEdge = db
|
||||
.prepare(
|
||||
`SELECT t.name target, t.id target_id
|
||||
FROM edges e
|
||||
JOIN nodes s ON s.id = e.source
|
||||
JOIN nodes t ON t.id = e.target
|
||||
WHERE e.kind = 'calls'
|
||||
AND s.file_path LIKE '%index.ts'
|
||||
AND t.name = 'uniqueExpoHapticCall'`
|
||||
)
|
||||
.all();
|
||||
cg.close?.();
|
||||
expect(callEdge.length).toBeGreaterThanOrEqual(1);
|
||||
expect(callEdge[0].target_id.startsWith('expo-module:')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -3987,6 +3987,35 @@ void helperFunction(int count) {
|
||||
expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
|
||||
});
|
||||
|
||||
it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
|
||||
// Regression for the gap discovered post-#165: message_expression's
|
||||
// multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
|
||||
// so calls never resolved to multi-part method definitions like
|
||||
// `GET:parameters:headers:progress:success:failure:`. The call-site name
|
||||
// must match the method-definition name with full keywords + trailing colons.
|
||||
const code = `
|
||||
@implementation Caller
|
||||
- (void)demo {
|
||||
NSMutableDictionary *d = [NSMutableDictionary new];
|
||||
[d setObject:@"v" forKey:@"k"];
|
||||
[d setObject:@"v2" forKey:@"k2" withRetry:@YES];
|
||||
[self touchesBegan:nil withEvent:nil];
|
||||
}
|
||||
@end
|
||||
`;
|
||||
const result = extractFromSource('Caller.m', code);
|
||||
const calls = result.unresolvedReferences
|
||||
.filter((r) => r.referenceKind === 'calls')
|
||||
.map((r) => r.referenceName);
|
||||
expect(calls).toEqual(
|
||||
expect.arrayContaining([
|
||||
'd.setObject:forKey:',
|
||||
'd.setObject:forKey:withRetry:',
|
||||
'touchesBegan:withEvent:',
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('should not classify pure C headers with @end in comments as objc', () => {
|
||||
const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
|
||||
expect(detectLanguage('stdio.h', cHeader)).toBe('c');
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import * as os from 'node:os';
|
||||
import { CodeGraph } from '../src';
|
||||
import { fabricViewResolver } from '../src/resolution/frameworks/fabric';
|
||||
|
||||
describe('Fabric view component extractor (codegenNativeComponent specs)', () => {
|
||||
it('extracts a component node + prop nodes from a Native*.ts spec', () => {
|
||||
const source = `
|
||||
'use client';
|
||||
import { codegenNativeComponent } from 'react-native';
|
||||
import type { ViewProps, CodegenTypes as CT, ColorValue } from 'react-native';
|
||||
|
||||
type TapEvent = Readonly<{ x: number; y: number }>;
|
||||
|
||||
export interface NativeProps extends ViewProps {
|
||||
color?: ColorValue;
|
||||
onTap?: CT.DirectEventHandler<TapEvent>;
|
||||
caption?: string;
|
||||
}
|
||||
|
||||
export default codegenNativeComponent<NativeProps>('MyView', {});
|
||||
`;
|
||||
const result = fabricViewResolver.extract?.('src/MyViewNativeComponent.ts', source);
|
||||
expect(result).toBeDefined();
|
||||
const componentNodes = result!.nodes.filter((n) => n.kind === 'component');
|
||||
const propNodes = result!.nodes.filter((n) => n.kind === 'property');
|
||||
expect(componentNodes).toHaveLength(1);
|
||||
expect(componentNodes[0]?.name).toBe('MyView');
|
||||
expect(propNodes.map((n) => n.name).sort()).toEqual(['caption', 'color', 'onTap']);
|
||||
});
|
||||
|
||||
it('returns nothing for a file without codegenNativeComponent', () => {
|
||||
const source = `export const x = 1;`;
|
||||
const result = fabricViewResolver.extract?.('plain.ts', source);
|
||||
expect(result?.nodes).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('handles a spec with no NativeProps interface (rare but valid)', () => {
|
||||
const source = `
|
||||
import { codegenNativeComponent } from 'react-native';
|
||||
export default codegenNativeComponent('BareComponent');
|
||||
`;
|
||||
const result = fabricViewResolver.extract?.('Bare.ts', source);
|
||||
// Component node exists; no prop nodes.
|
||||
const components = result!.nodes.filter((n) => n.kind === 'component');
|
||||
const props = result!.nodes.filter((n) => n.kind === 'property');
|
||||
expect(components).toHaveLength(1);
|
||||
expect(components[0]?.name).toBe('BareComponent');
|
||||
expect(props).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Fabric end-to-end: JSX consumer → Fabric component → native class', () => {
|
||||
let dir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fabric-fixture-'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('connects <MyView/> JSX to the native ObjC class via Fabric synthesizer', async () => {
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'package.json'),
|
||||
'{"dependencies":{"react-native":"^0.73"}}'
|
||||
);
|
||||
// Fabric spec.
|
||||
fs.mkdirSync(path.join(dir, 'spec'));
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'spec', 'MyViewNativeComponent.ts'),
|
||||
`import { codegenNativeComponent } from 'react-native';
|
||||
import type { ViewProps } from 'react-native';
|
||||
export interface NativeProps extends ViewProps { color?: string; }
|
||||
export default codegenNativeComponent<NativeProps>('MyView');`
|
||||
);
|
||||
// Native iOS implementation — class named with the `View` suffix
|
||||
// convention.
|
||||
fs.mkdirSync(path.join(dir, 'ios'));
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'ios', 'MyView.mm'),
|
||||
`@interface MyViewView : UIView
|
||||
@end
|
||||
@implementation MyViewView
|
||||
- (void)setColor:(NSString *)c { /* … */ }
|
||||
@end`
|
||||
);
|
||||
// JSX consumer.
|
||||
fs.mkdirSync(path.join(dir, 'src'));
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'src', 'App.tsx'),
|
||||
`import React from 'react';
|
||||
import MyView from '../spec/MyViewNativeComponent';
|
||||
export function App() {
|
||||
return <MyView color="red"/>;
|
||||
}`
|
||||
);
|
||||
|
||||
const cg = await CodeGraph.init(dir, { silent: true });
|
||||
await cg.indexAll();
|
||||
const db = (cg as any).db.db;
|
||||
|
||||
// 1. The Fabric component node exists.
|
||||
const componentRows = db
|
||||
.prepare("SELECT id, name, kind FROM nodes WHERE id LIKE 'fabric-component:%' AND name='MyView'")
|
||||
.all();
|
||||
expect(componentRows).toHaveLength(1);
|
||||
|
||||
// 2. The native class node exists.
|
||||
const nativeRows = db
|
||||
.prepare("SELECT id, name FROM nodes WHERE kind='class' AND language='objc' AND name='MyViewView'")
|
||||
.all();
|
||||
expect(nativeRows).toHaveLength(1);
|
||||
|
||||
// 3. Fabric synthesizer bridges component → native class.
|
||||
const bridgeRows = db
|
||||
.prepare(
|
||||
`SELECT s.name comp, t.name native FROM edges e
|
||||
JOIN nodes s ON s.id=e.source JOIN nodes t ON t.id=e.target
|
||||
WHERE json_extract(e.metadata,'$.synthesizedBy')='fabric-native-impl'
|
||||
AND s.name='MyView' AND t.name='MyViewView'`
|
||||
)
|
||||
.all();
|
||||
expect(bridgeRows).toHaveLength(1);
|
||||
|
||||
// 4. JSX synthesizer links the App function → the Fabric component
|
||||
// (jsx-render edge keyed on the tag name 'MyView').
|
||||
const jsxRows = db
|
||||
.prepare(
|
||||
`SELECT s.name caller, t.name comp FROM edges e
|
||||
JOIN nodes s ON s.id=e.source JOIN nodes t ON t.id=e.target
|
||||
WHERE json_extract(e.metadata,'$.synthesizedBy')='jsx-render'
|
||||
AND t.id LIKE 'fabric-component:%' AND t.name='MyView'`
|
||||
)
|
||||
.all();
|
||||
cg.close?.();
|
||||
expect(jsxRows.length).toBeGreaterThanOrEqual(1);
|
||||
expect(jsxRows[0].caller).toBe('App');
|
||||
// The full flow: App (TSX) → MyView (fabric-component) → MyViewView (ObjC native class)
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,294 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import type { Node, Language } from '../src/types';
|
||||
import type { ResolutionContext, UnresolvedRef } from '../src/resolution/types';
|
||||
import { reactNativeBridgeResolver } from '../src/resolution/frameworks/react-native';
|
||||
|
||||
/**
|
||||
* Mock ResolutionContext for the React Native bridge resolver.
|
||||
*/
|
||||
function makeContext(nodes: Node[], fileContents: Record<string, string> = {}): ResolutionContext {
|
||||
const byName = new Map<string, Node[]>();
|
||||
for (const n of nodes) {
|
||||
const arr = byName.get(n.name);
|
||||
if (arr) arr.push(n);
|
||||
else byName.set(n.name, [n]);
|
||||
}
|
||||
// Files = union of node files + any extra fileContents keys (for files that
|
||||
// have content like .mm bridge declarations but no extracted nodes yet).
|
||||
const allFiles = new Set<string>(
|
||||
[...nodes.map((n) => n.filePath), ...Object.keys(fileContents)]
|
||||
);
|
||||
return {
|
||||
getNodesInFile: (fp) => nodes.filter((n) => n.filePath === fp),
|
||||
getNodesByName: (name) => byName.get(name) ?? [],
|
||||
getNodesByQualifiedName: () => { throw new Error('not used'); },
|
||||
getNodesByKind: (kind) => nodes.filter((n) => n.kind === kind),
|
||||
getNodesByLowerName: () => { throw new Error('not used'); },
|
||||
fileExists: (fp) => allFiles.has(fp),
|
||||
readFile: (fp) => fileContents[fp] ?? null,
|
||||
getProjectRoot: () => '/test',
|
||||
getAllFiles: () => Array.from(allFiles),
|
||||
getImportMappings: () => [],
|
||||
};
|
||||
}
|
||||
|
||||
function method(
|
||||
name: string,
|
||||
language: Language,
|
||||
filePath: string,
|
||||
startLine = 10
|
||||
): Node {
|
||||
return {
|
||||
id: `${language}:${filePath}:${name}:${startLine}`,
|
||||
kind: 'method',
|
||||
name,
|
||||
qualifiedName: `${filePath}::${name}`,
|
||||
filePath,
|
||||
language,
|
||||
startLine,
|
||||
endLine: startLine + 5,
|
||||
startColumn: 0,
|
||||
endColumn: 0,
|
||||
updatedAt: Date.now(),
|
||||
} as Node;
|
||||
}
|
||||
|
||||
function ref(name: string, language: Language, filePath: string): UnresolvedRef {
|
||||
return {
|
||||
fromNodeId: `caller:${filePath}`,
|
||||
referenceName: name,
|
||||
referenceKind: 'calls',
|
||||
line: 1,
|
||||
column: 0,
|
||||
filePath,
|
||||
language,
|
||||
};
|
||||
}
|
||||
|
||||
describe('React Native bridge resolver', () => {
|
||||
describe('detect()', () => {
|
||||
it('returns true when package.json declares react-native', () => {
|
||||
const ctx = makeContext([], {
|
||||
'package.json':
|
||||
'{"name":"x","dependencies":{"react-native":"^0.73.0"}}',
|
||||
});
|
||||
expect(reactNativeBridgeResolver.detect(ctx)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true when an ObjC file uses RCT_EXPORT_MODULE', () => {
|
||||
const ctx = makeContext([], {
|
||||
'NativeFoo.mm': '@implementation Foo\nRCT_EXPORT_MODULE()\n@end',
|
||||
});
|
||||
expect(reactNativeBridgeResolver.detect(ctx)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true when a TS file uses TurboModuleRegistry', () => {
|
||||
const ctx = makeContext([], {
|
||||
'NativeFoo.ts':
|
||||
"import { TurboModuleRegistry } from 'react-native';\n" +
|
||||
"export default TurboModuleRegistry.getEnforcing<Spec>('Foo');",
|
||||
});
|
||||
expect(reactNativeBridgeResolver.detect(ctx)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when none of the RN signals are present', () => {
|
||||
const ctx = makeContext([method('hi', 'objc', 'X.m')]);
|
||||
expect(reactNativeBridgeResolver.detect(ctx)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('legacy bridge — ObjC side', () => {
|
||||
it('resolves JS callsite via RCT_EXPORT_METHOD with default module name', () => {
|
||||
// RCTGeolocation → module name 'Geolocation' (RCT prefix stripped).
|
||||
const native = method('getCurrentPosition:', 'objc', 'RCTGeolocation.m');
|
||||
const ctx = makeContext([native], {
|
||||
'package.json': '{"dependencies":{"react-native":"^0.73"}}',
|
||||
'RCTGeolocation.m':
|
||||
'@implementation RCTGeolocation\n' +
|
||||
'RCT_EXPORT_MODULE()\n' +
|
||||
'RCT_EXPORT_METHOD(getCurrentPosition:(RCTResponseSenderBlock)cb) {}\n' +
|
||||
'@end',
|
||||
});
|
||||
const result = reactNativeBridgeResolver.resolve(
|
||||
ref('getCurrentPosition', 'javascript', 'App.js'),
|
||||
ctx
|
||||
);
|
||||
expect(result?.targetNodeId).toBe(native.id);
|
||||
expect(result?.resolvedBy).toBe('framework');
|
||||
});
|
||||
|
||||
it('resolves via explicit module name in RCT_EXPORT_MODULE(name)', () => {
|
||||
const native = method('startScan:', 'objc', 'Bluetooth.m');
|
||||
const ctx = makeContext([native], {
|
||||
'package.json': '{"dependencies":{"react-native":"^0.73"}}',
|
||||
'Bluetooth.m':
|
||||
'@implementation BluetoothImpl\n' +
|
||||
'RCT_EXPORT_MODULE(BluetoothManager)\n' +
|
||||
'RCT_EXPORT_METHOD(startScan:(RCTResponseSenderBlock)cb) {}\n' +
|
||||
'@end',
|
||||
});
|
||||
const result = reactNativeBridgeResolver.resolve(
|
||||
ref('startScan', 'javascript', 'App.js'),
|
||||
ctx
|
||||
);
|
||||
expect(result?.targetNodeId).toBe(native.id);
|
||||
});
|
||||
|
||||
it('resolves RCT_REMAP_METHOD with JS-name override', () => {
|
||||
const native = method('doInternalCompute:', 'objc', 'Computer.m');
|
||||
const ctx = makeContext([native], {
|
||||
'package.json': '{"dependencies":{"react-native":"^0.73"}}',
|
||||
'Computer.m':
|
||||
'@implementation Computer\n' +
|
||||
'RCT_EXPORT_MODULE()\n' +
|
||||
'RCT_REMAP_METHOD(compute, doInternalCompute:(NSDictionary *)opts) {}\n' +
|
||||
'@end',
|
||||
});
|
||||
const result = reactNativeBridgeResolver.resolve(
|
||||
ref('compute', 'javascript', 'App.js'),
|
||||
ctx
|
||||
);
|
||||
expect(result?.targetNodeId).toBe(native.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('legacy bridge — Java side', () => {
|
||||
it('resolves @ReactMethod with getName() literal', () => {
|
||||
const native = method('getCurrentPosition', 'java', 'GeolocationModule.java');
|
||||
const ctx = makeContext([native], {
|
||||
'package.json': '{"dependencies":{"react-native":"^0.73"}}',
|
||||
'GeolocationModule.java':
|
||||
'class GeolocationModule extends ReactContextBaseJavaModule {\n' +
|
||||
' @Override public String getName() { return "Geolocation"; }\n' +
|
||||
' @ReactMethod public void getCurrentPosition(Callback cb) {}\n' +
|
||||
'}',
|
||||
});
|
||||
const result = reactNativeBridgeResolver.resolve(
|
||||
ref('getCurrentPosition', 'javascript', 'App.js'),
|
||||
ctx
|
||||
);
|
||||
expect(result?.targetNodeId).toBe(native.id);
|
||||
});
|
||||
|
||||
it('resolves Kotlin @ReactMethod fun', () => {
|
||||
const native = method('startScan', 'kotlin', 'BluetoothModule.kt');
|
||||
const ctx = makeContext([native], {
|
||||
'package.json': '{"dependencies":{"react-native":"^0.73"}}',
|
||||
'BluetoothModule.kt':
|
||||
'class BluetoothModule(ctx: ReactApplicationContext) : ReactContextBaseJavaModule(ctx) {\n' +
|
||||
' override fun getName(): String = "BluetoothManager"\n' +
|
||||
' @ReactMethod fun startScan(cb: Callback) {}\n' +
|
||||
'}',
|
||||
});
|
||||
const result = reactNativeBridgeResolver.resolve(
|
||||
ref('startScan', 'javascript', 'App.js'),
|
||||
ctx
|
||||
);
|
||||
expect(result?.targetNodeId).toBe(native.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TurboModule spec resolution', () => {
|
||||
it('matches spec method to native ObjC implementation by name', () => {
|
||||
// The Spec interface lists `getTotalLength`; ObjC has a method by the
|
||||
// same first keyword. Bridge matches by name.
|
||||
const native = method('getTotalLength:', 'objc', 'RNSVGRenderableManager.mm');
|
||||
const ctx = makeContext([native], {
|
||||
'package.json': '{"dependencies":{"react-native":"^0.73"}}',
|
||||
'NativeSvgRenderableModule.ts':
|
||||
"import { TurboModuleRegistry } from 'react-native';\n" +
|
||||
'export interface Spec extends TurboModule {\n' +
|
||||
' getTotalLength(tag: number): number;\n' +
|
||||
' isPointInFill(tag: number, options?: object): boolean;\n' +
|
||||
'}\n' +
|
||||
"export default TurboModuleRegistry.getEnforcing<Spec>('RNSVGRenderableModule');",
|
||||
});
|
||||
const result = reactNativeBridgeResolver.resolve(
|
||||
ref('getTotalLength', 'tsx', 'SvgComponent.tsx'),
|
||||
ctx
|
||||
);
|
||||
expect(result?.targetNodeId).toBe(native.id);
|
||||
});
|
||||
|
||||
it('returns null when spec method has no matching native impl', () => {
|
||||
const ctx = makeContext([], {
|
||||
'package.json': '{"dependencies":{"react-native":"^0.73"}}',
|
||||
'NativeFoo.ts':
|
||||
"import { TurboModuleRegistry } from 'react-native';\n" +
|
||||
'export interface Spec extends TurboModule {\n' +
|
||||
' thingThatDoesntExist(): void;\n' +
|
||||
'}\n' +
|
||||
"export default TurboModuleRegistry.getEnforcing<Spec>('Foo');",
|
||||
});
|
||||
const result = reactNativeBridgeResolver.resolve(
|
||||
ref('thingThatDoesntExist', 'tsx', 'Caller.tsx'),
|
||||
ctx
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('qualified vs bare callsite names', () => {
|
||||
it('handles bare method name (post receiver-strip)', () => {
|
||||
const native = method('compute:', 'objc', 'Mod.m');
|
||||
const ctx = makeContext([native], {
|
||||
'package.json': '{"dependencies":{"react-native":"^0.73"}}',
|
||||
'Mod.m':
|
||||
'@implementation Mod\nRCT_EXPORT_MODULE()\nRCT_EXPORT_METHOD(compute:(NSDictionary *)x) {}\n@end',
|
||||
});
|
||||
expect(
|
||||
reactNativeBridgeResolver.resolve(ref('compute', 'javascript', 'App.js'), ctx)
|
||||
).not.toBeNull();
|
||||
});
|
||||
|
||||
it('strips dot prefix on receiver-qualified callsite (NativeModules.Mod.compute → compute)', () => {
|
||||
const native = method('compute:', 'objc', 'Mod.m');
|
||||
const ctx = makeContext([native], {
|
||||
'package.json': '{"dependencies":{"react-native":"^0.73"}}',
|
||||
'Mod.m':
|
||||
'@implementation Mod\nRCT_EXPORT_MODULE()\nRCT_EXPORT_METHOD(compute:(NSDictionary *)x) {}\n@end',
|
||||
});
|
||||
expect(
|
||||
reactNativeBridgeResolver.resolve(
|
||||
ref('NativeModules.Mod.compute', 'javascript', 'App.js'),
|
||||
ctx
|
||||
)
|
||||
).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('does not resolve native-language callers (resolver is JS-side only)', () => {
|
||||
const native = method('compute:', 'objc', 'Mod.m');
|
||||
const ctx = makeContext([native]);
|
||||
expect(
|
||||
reactNativeBridgeResolver.resolve(ref('compute', 'objc', 'OtherMod.m'), ctx)
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
describe('RCTEventEmitter built-ins blocklist', () => {
|
||||
it('skips addListener / remove (every emitter exposes these — bridging them creates noise)', () => {
|
||||
// A repo with RCTEventEmitter subclass: defines `addListener:` and
|
||||
// `remove:` because that's what `[RCTEventEmitter addListener:]`
|
||||
// requires. JS callers of `.addListener(...)` should NOT resolve
|
||||
// here — they're hitting the JS-side `NativeEventEmitter`
|
||||
// abstraction, not the native emitter directly.
|
||||
const native1 = method('addListener:', 'objc', 'EventEmitter.m');
|
||||
const native2 = method('remove:', 'objc', 'EventEmitter.m');
|
||||
const ctx = makeContext([native1, native2], {
|
||||
'package.json': '{"dependencies":{"react-native":"^0.73"}}',
|
||||
'EventEmitter.m':
|
||||
'@implementation EventEmitter\n' +
|
||||
'RCT_EXPORT_MODULE()\n' +
|
||||
'RCT_EXPORT_METHOD(addListener:(NSString *)eventName) {}\n' +
|
||||
'RCT_EXPORT_METHOD(remove:(double)id) {}\n' +
|
||||
'@end',
|
||||
});
|
||||
expect(
|
||||
reactNativeBridgeResolver.resolve(ref('addListener', 'javascript', 'App.js'), ctx)
|
||||
).toBeNull();
|
||||
expect(
|
||||
reactNativeBridgeResolver.resolve(ref('remove', 'typescript', 'App.ts'), ctx)
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import * as os from 'node:os';
|
||||
import { CodeGraph } from '../src';
|
||||
|
||||
/**
|
||||
* End-to-end synthesizer test: write a fixture project with a native ObjC
|
||||
* `sendEventWithName:` site and a JS `addListener('x', fn)` subscriber,
|
||||
* index it, and verify the synthesized cross-language event edge.
|
||||
*/
|
||||
describe('RN event channel synthesizer', () => {
|
||||
let dir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rn-event-fixture-'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('synthesizes an edge from ObjC sendEventWithName: to JS addListener handler', async () => {
|
||||
// package.json so the RN detector / general resolver sees the project as RN.
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'package.json'),
|
||||
'{"name":"x","dependencies":{"react-native":"^0.73"}}'
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'Emitter.m'),
|
||||
`
|
||||
@implementation Emitter
|
||||
- (void)reportLocation {
|
||||
[self sendEventWithName:@"locationUpdate" body:@{}];
|
||||
}
|
||||
@end
|
||||
`
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'App.js'),
|
||||
`
|
||||
function onLocation(payload) {
|
||||
console.log(payload);
|
||||
}
|
||||
emitter.addListener('locationUpdate', onLocation);
|
||||
`
|
||||
);
|
||||
|
||||
const cg = await CodeGraph.init(dir, { silent: true });
|
||||
await cg.indexAll();
|
||||
|
||||
const db = (cg as any).db.db;
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT s.name source_name, s.language sl, t.name target_name, t.language tl,
|
||||
json_extract(e.metadata,'$.event') event
|
||||
FROM edges e
|
||||
JOIN nodes s ON s.id = e.source
|
||||
JOIN nodes t ON t.id = e.target
|
||||
WHERE json_extract(e.metadata,'$.synthesizedBy') = 'rn-event-channel'`
|
||||
)
|
||||
.all();
|
||||
cg.close?.();
|
||||
expect(rows.length).toBeGreaterThanOrEqual(1);
|
||||
// The edge should point from the ObjC method that emits to the JS handler.
|
||||
const edge = rows.find((r: any) => r.event === 'locationUpdate');
|
||||
expect(edge).toBeDefined();
|
||||
expect(edge.sl).toBe('objc');
|
||||
expect(edge.tl).toBe('javascript');
|
||||
expect(edge.target_name).toBe('onLocation');
|
||||
});
|
||||
|
||||
it('falls back to enclosing JS function when addListener handler is a parameter (wrapper-API pattern)', async () => {
|
||||
// Matches the real RNFirebase shape: `messaging().onMessage(listener)`
|
||||
// is a subscribe-wrapper whose body does
|
||||
// `addListener('messaging_message_received', listener)` where `listener`
|
||||
// is the parameter — not a globally-named symbol. Synthesizer should
|
||||
// still produce an edge, attributed to the enclosing wrapper function.
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'package.json'),
|
||||
'{"dependencies":{"react-native":"^0.73"}}'
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'Native.m'),
|
||||
`
|
||||
@implementation MyEmitter
|
||||
- (void)pushMessage {
|
||||
[[Shared shared] sendEventWithName:@"messaging_message_received" body:@{}];
|
||||
}
|
||||
@end
|
||||
`
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'messaging.ts'),
|
||||
`
|
||||
import { NativeEventEmitter } from 'react-native';
|
||||
const emitter = new NativeEventEmitter();
|
||||
export function onMessage(listener: (m: any) => void) {
|
||||
return emitter.addListener('messaging_message_received', listener);
|
||||
}
|
||||
`
|
||||
);
|
||||
|
||||
const cg = await CodeGraph.init(dir, { silent: true });
|
||||
await cg.indexAll();
|
||||
|
||||
const db = (cg as any).db.db;
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT s.name source_name, t.name target_name, t.kind target_kind, t.language tl,
|
||||
json_extract(e.metadata,'$.event') event
|
||||
FROM edges e
|
||||
JOIN nodes s ON s.id = e.source
|
||||
JOIN nodes t ON t.id = e.target
|
||||
WHERE json_extract(e.metadata,'$.synthesizedBy') = 'rn-event-channel'`
|
||||
)
|
||||
.all();
|
||||
cg.close?.();
|
||||
const edge = rows.find((r: any) => r.event === 'messaging_message_received');
|
||||
expect(edge).toBeDefined();
|
||||
// Target should be the wrapper function `onMessage` — the enclosing
|
||||
// function of the addListener call, not a bareword named handler.
|
||||
expect(edge.target_name).toBe('onMessage');
|
||||
expect(['function', 'method']).toContain(edge.target_kind);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,205 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import type { Node } from '../src/types';
|
||||
import type { ResolutionContext, UnresolvedRef } from '../src/resolution/types';
|
||||
import { swiftObjcBridgeResolver } from '../src/resolution/frameworks/swift-objc';
|
||||
|
||||
/**
|
||||
* Lightweight ResolutionContext mock — implements only the methods the
|
||||
* bridge resolver actually calls. Anything else throws so a leaked call
|
||||
* surfaces loudly in tests.
|
||||
*/
|
||||
function makeContext(nodes: Node[], fileContents: Record<string, string> = {}): ResolutionContext {
|
||||
const byName = new Map<string, Node[]>();
|
||||
for (const n of nodes) {
|
||||
const arr = byName.get(n.name);
|
||||
if (arr) arr.push(n);
|
||||
else byName.set(n.name, [n]);
|
||||
}
|
||||
const allFiles = new Set(nodes.map((n) => n.filePath));
|
||||
return {
|
||||
getNodesInFile: (fp) => nodes.filter((n) => n.filePath === fp),
|
||||
getNodesByName: (name) => byName.get(name) ?? [],
|
||||
getNodesByQualifiedName: () => { throw new Error('not used'); },
|
||||
getNodesByKind: (kind) => nodes.filter((n) => n.kind === kind),
|
||||
getNodesByLowerName: () => { throw new Error('not used'); },
|
||||
fileExists: (fp) => allFiles.has(fp),
|
||||
readFile: (fp) => fileContents[fp] ?? null,
|
||||
getProjectRoot: () => '/test',
|
||||
getAllFiles: () => Array.from(allFiles),
|
||||
getImportMappings: () => [],
|
||||
};
|
||||
}
|
||||
|
||||
function method(name: string, language: 'swift' | 'objc', filePath: string, startLine = 10): Node {
|
||||
return {
|
||||
id: `${language}:${filePath}:${name}:${startLine}`,
|
||||
kind: 'method',
|
||||
name,
|
||||
qualifiedName: `${filePath}::${name}`,
|
||||
filePath,
|
||||
language,
|
||||
startLine,
|
||||
endLine: startLine + 5,
|
||||
startColumn: 0,
|
||||
endColumn: 0,
|
||||
updatedAt: Date.now(),
|
||||
} as Node;
|
||||
}
|
||||
|
||||
function ref(name: string, language: 'swift' | 'objc', filePath: string): UnresolvedRef {
|
||||
return {
|
||||
fromNodeId: `caller:${filePath}`,
|
||||
referenceName: name,
|
||||
referenceKind: 'calls',
|
||||
line: 1,
|
||||
column: 0,
|
||||
filePath,
|
||||
language,
|
||||
};
|
||||
}
|
||||
|
||||
describe('swiftObjcBridgeResolver integration', () => {
|
||||
describe('detect()', () => {
|
||||
it('returns true when both .swift and .m files exist', () => {
|
||||
const ctx = makeContext([
|
||||
method('foo', 'swift', 'A.swift'),
|
||||
method('bar', 'objc', 'B.m'),
|
||||
]);
|
||||
expect(swiftObjcBridgeResolver.detect(ctx)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when only .swift files exist', () => {
|
||||
const ctx = makeContext([method('foo', 'swift', 'A.swift')]);
|
||||
expect(swiftObjcBridgeResolver.detect(ctx)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true when .swift and .mm exist (ObjC++)', () => {
|
||||
const ctx = makeContext([
|
||||
method('foo', 'swift', 'A.swift'),
|
||||
method('bar', 'objc', 'B.mm'),
|
||||
]);
|
||||
expect(swiftObjcBridgeResolver.detect(ctx)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('claimsReference()', () => {
|
||||
it('claims selector-shape names (contain :)', () => {
|
||||
expect(swiftObjcBridgeResolver.claimsReference?.('fooWithBar:')).toBe(true);
|
||||
expect(swiftObjcBridgeResolver.claimsReference?.('tableView:didSelectRowAtIndexPath:')).toBe(true);
|
||||
expect(swiftObjcBridgeResolver.claimsReference?.('setName:')).toBe(true);
|
||||
});
|
||||
|
||||
it('does not claim bare names (handled by normal name-matcher)', () => {
|
||||
expect(swiftObjcBridgeResolver.claimsReference?.('foo')).toBe(false);
|
||||
expect(swiftObjcBridgeResolver.claimsReference?.('init')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolve() — Swift → ObjC direction', () => {
|
||||
it('resolves Swift call to Cocoa-style ObjC method (fetchEntry → fetchEntryForKey:)', () => {
|
||||
// Swift writes `cache.fetchEntry(forKey: "x")` → ref name `fetchEntry`.
|
||||
// ObjC method is `fetchEntryForKey:` (preposition-prefix shape).
|
||||
// `fetchEntry` is project-specific (not in the generic-names blocklist
|
||||
// that filters init/count/description/etc. to avoid Cocoa noise).
|
||||
const objcTarget = method('fetchEntryForKey:', 'objc', 'Cache.m');
|
||||
const ctx = makeContext([objcTarget]);
|
||||
const result = swiftObjcBridgeResolver.resolve(
|
||||
ref('fetchEntry', 'swift', 'Caller.swift'),
|
||||
ctx
|
||||
);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.targetNodeId).toBe(objcTarget.id);
|
||||
expect(result?.resolvedBy).toBe('framework');
|
||||
expect(result?.confidence).toBe(0.6);
|
||||
});
|
||||
|
||||
it('does NOT bridge generic Cocoa names like "init" or "description"', () => {
|
||||
// Bridging Swift `init()` calls to arbitrary ObjC `init*:` methods is
|
||||
// noise — every NSObject subclass has them. The regular name-matcher
|
||||
// handles `init` on its own.
|
||||
const objcInit = method('initWithFrame:', 'objc', 'View.m');
|
||||
const ctx = makeContext([objcInit]);
|
||||
const result = swiftObjcBridgeResolver.resolve(
|
||||
ref('init', 'swift', 'Caller.swift'),
|
||||
ctx
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('resolves bridged "With" form: Swift `play(song:)` → ObjC `playWithSong:`', () => {
|
||||
const objcTarget = method('playWithSong:', 'objc', 'Player.m');
|
||||
const ctx = makeContext([objcTarget]);
|
||||
const result = swiftObjcBridgeResolver.resolve(
|
||||
ref('play', 'swift', 'Caller.swift'),
|
||||
ctx
|
||||
);
|
||||
expect(result?.targetNodeId).toBe(objcTarget.id);
|
||||
});
|
||||
|
||||
it('returns null when no matching ObjC method exists', () => {
|
||||
const ctx = makeContext([method('unrelated:thing:', 'objc', 'X.m')]);
|
||||
const result = swiftObjcBridgeResolver.resolve(
|
||||
ref('completelyDifferent', 'swift', 'Caller.swift'),
|
||||
ctx
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolve() — ObjC → Swift direction', () => {
|
||||
it('resolves ObjC selector to @objc-exposed Swift method (exporter form)', () => {
|
||||
// Swift @objc export of `func animate(xAxisDuration:, yAxisDuration:)`
|
||||
// produces ObjC selector `animateWithXAxisDuration:yAxisDuration:`
|
||||
// (always "With" insertion on first explicit label).
|
||||
const swiftTarget = method('animate', 'swift', 'Chart.swift', 10);
|
||||
const ctx = makeContext([swiftTarget], {
|
||||
'Chart.swift':
|
||||
'\n'.repeat(8) +
|
||||
'@objc open func animate(xAxisDuration: Double, yAxisDuration: Double) {}\n',
|
||||
});
|
||||
const result = swiftObjcBridgeResolver.resolve(
|
||||
ref('animateWithXAxisDuration:yAxisDuration:', 'objc', 'Caller.m'),
|
||||
ctx
|
||||
);
|
||||
expect(result?.targetNodeId).toBe(swiftTarget.id);
|
||||
expect(result?.resolvedBy).toBe('framework');
|
||||
});
|
||||
|
||||
it('does NOT resolve if the Swift method is not @objc-exposed', () => {
|
||||
const swiftTarget = method('animate', 'swift', 'Chart.swift', 10);
|
||||
const ctx = makeContext([swiftTarget], {
|
||||
// Plain `func` without @objc — bridge correctly skips it
|
||||
'Chart.swift':
|
||||
'\n'.repeat(8) +
|
||||
'func animate(xAxisDuration: Double, yAxisDuration: Double) {}\n',
|
||||
});
|
||||
const result = swiftObjcBridgeResolver.resolve(
|
||||
ref('animateWithXAxisDuration:yAxisDuration:', 'objc', 'Caller.m'),
|
||||
ctx
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('resolves init selectors to Swift init', () => {
|
||||
const swiftTarget = method('init', 'swift', 'MyClass.swift', 10);
|
||||
const ctx = makeContext([swiftTarget], {
|
||||
'MyClass.swift':
|
||||
'\n'.repeat(8) + '@objc init(name: String, age: Int) {}\n',
|
||||
});
|
||||
const result = swiftObjcBridgeResolver.resolve(
|
||||
ref('initWithName:age:', 'objc', 'Caller.m'),
|
||||
ctx
|
||||
);
|
||||
expect(result?.targetNodeId).toBe(swiftTarget.id);
|
||||
});
|
||||
|
||||
it('returns null for selectors with no derivable Swift candidates that exist', () => {
|
||||
const ctx = makeContext([]);
|
||||
const result = swiftObjcBridgeResolver.resolve(
|
||||
ref('someUnknownThing:', 'objc', 'Caller.m'),
|
||||
ctx
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,189 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
objcSelectorForSwiftMethod,
|
||||
objcSelectorForSwiftInit,
|
||||
objcAccessorsForSwiftProperty,
|
||||
swiftBaseNamesForObjcSelector,
|
||||
detectExplicitObjcName,
|
||||
isObjcExposed,
|
||||
} from '../src/resolution/swift-objc-bridge';
|
||||
|
||||
describe('Swift → ObjC selector bridging (auto-name rules)', () => {
|
||||
describe('objcSelectorForSwiftMethod', () => {
|
||||
it('no parameters → bare base name', () => {
|
||||
expect(objcSelectorForSwiftMethod('play', [])).toBe('play');
|
||||
});
|
||||
|
||||
it('single _ param → base + ":"', () => {
|
||||
expect(objcSelectorForSwiftMethod('play', ['_'])).toBe('play:');
|
||||
expect(objcSelectorForSwiftMethod('play', [null])).toBe('play:');
|
||||
});
|
||||
|
||||
it('single labeled param → "baseWithLabel:"', () => {
|
||||
expect(objcSelectorForSwiftMethod('play', ['song'])).toBe('playWithSong:');
|
||||
});
|
||||
|
||||
it('multi-param with leading _ → "base:label2:..."', () => {
|
||||
expect(objcSelectorForSwiftMethod('play', ['_', 'by'])).toBe('play:by:');
|
||||
expect(
|
||||
objcSelectorForSwiftMethod('tableView', ['_', 'didSelectRowAtIndexPath'])
|
||||
).toBe('tableView:didSelectRowAtIndexPath:');
|
||||
});
|
||||
|
||||
it('multi-param with leading explicit label → "baseWithFirst:rest:"', () => {
|
||||
expect(objcSelectorForSwiftMethod('play', ['song', 'by'])).toBe(
|
||||
'playWithSong:by:'
|
||||
);
|
||||
});
|
||||
|
||||
it('@objc(custom:) overrides the rule literally', () => {
|
||||
expect(
|
||||
objcSelectorForSwiftMethod('whateverName', ['ignored'], 'custom:')
|
||||
).toBe('custom:');
|
||||
});
|
||||
|
||||
it('returns null on empty base name', () => {
|
||||
expect(objcSelectorForSwiftMethod('', [])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('objcSelectorForSwiftInit', () => {
|
||||
it('init() → "init"', () => {
|
||||
expect(objcSelectorForSwiftInit([], [])).toBe('init');
|
||||
});
|
||||
|
||||
it('init(name:) → "initWithName:"', () => {
|
||||
expect(objcSelectorForSwiftInit(['name'], ['name'])).toBe('initWithName:');
|
||||
});
|
||||
|
||||
it('init(name:, age:) → "initWithName:age:"', () => {
|
||||
expect(objcSelectorForSwiftInit(['name', 'age'], ['name', 'age'])).toBe(
|
||||
'initWithName:age:'
|
||||
);
|
||||
});
|
||||
|
||||
it('init(_ name:) uses internal name → "initWithName:"', () => {
|
||||
expect(objcSelectorForSwiftInit(['_'], ['name'])).toBe('initWithName:');
|
||||
});
|
||||
|
||||
it('@objc(custom) override on init', () => {
|
||||
expect(objcSelectorForSwiftInit(['name'], ['name'], 'custom:')).toBe(
|
||||
'custom:'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('objcAccessorsForSwiftProperty', () => {
|
||||
it('getter = name, setter = setName:', () => {
|
||||
expect(objcAccessorsForSwiftProperty('name')).toEqual({
|
||||
getter: 'name',
|
||||
setter: 'setName:',
|
||||
});
|
||||
});
|
||||
|
||||
it('camelCase → set capitalizes first', () => {
|
||||
expect(objcAccessorsForSwiftProperty('isReady')).toEqual({
|
||||
getter: 'isReady',
|
||||
setter: 'setIsReady:',
|
||||
});
|
||||
});
|
||||
|
||||
it('explicit @objc(custom) overrides getter name', () => {
|
||||
expect(objcAccessorsForSwiftProperty('name', 'displayName')).toEqual({
|
||||
getter: 'displayName',
|
||||
setter: 'setDisplayName:',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('ObjC selector → Swift base name candidates (reverse map)', () => {
|
||||
it('bare no-colon selector → itself', () => {
|
||||
expect(swiftBaseNamesForObjcSelector('play')).toEqual(['play']);
|
||||
});
|
||||
|
||||
it('"play:" → ["play"]', () => {
|
||||
expect(swiftBaseNamesForObjcSelector('play:')).toEqual(['play']);
|
||||
});
|
||||
|
||||
it('"playWithSong:" → ["playWithSong", "play"]', () => {
|
||||
expect(swiftBaseNamesForObjcSelector('playWithSong:').sort()).toEqual(
|
||||
['play', 'playWithSong'].sort()
|
||||
);
|
||||
});
|
||||
|
||||
it('Cocoa-style "objectForKey:" → includes "object"', () => {
|
||||
expect(swiftBaseNamesForObjcSelector('objectForKey:')).toContain('object');
|
||||
});
|
||||
|
||||
it('Cocoa-style "stringWithFormat:" → includes "string"', () => {
|
||||
expect(swiftBaseNamesForObjcSelector('stringWithFormat:')).toContain('string');
|
||||
});
|
||||
|
||||
it('Cocoa-style "imageNamed:inBundle:" → first keyword has no preposition, falls through', () => {
|
||||
// First keyword is `imageNamed` — no With/For/By in it, so candidates is
|
||||
// just the raw keyword. (`Named` is not in our preposition list — keep
|
||||
// it that way, otherwise we over-match on perfectly normal verbs.)
|
||||
expect(swiftBaseNamesForObjcSelector('imageNamed:inBundle:')).toEqual(['imageNamed']);
|
||||
});
|
||||
|
||||
it('"play:by:" → ["play"]', () => {
|
||||
expect(swiftBaseNamesForObjcSelector('play:by:')).toEqual(['play']);
|
||||
});
|
||||
|
||||
it('"playWithSong:by:" → ["playWithSong", "play"]', () => {
|
||||
expect(swiftBaseNamesForObjcSelector('playWithSong:by:').sort()).toEqual(
|
||||
['play', 'playWithSong'].sort()
|
||||
);
|
||||
});
|
||||
|
||||
it('"initWithName:" → includes "init"', () => {
|
||||
expect(swiftBaseNamesForObjcSelector('initWithName:')).toContain('init');
|
||||
});
|
||||
|
||||
it('"initWithName:age:" → includes "init"', () => {
|
||||
expect(swiftBaseNamesForObjcSelector('initWithName:age:')).toContain('init');
|
||||
});
|
||||
|
||||
it('"setName:" → includes the property name "name"', () => {
|
||||
expect(swiftBaseNamesForObjcSelector('setName:')).toContain('name');
|
||||
});
|
||||
|
||||
it('"tableView:didSelectRowAtIndexPath:" → ["tableView"]', () => {
|
||||
expect(
|
||||
swiftBaseNamesForObjcSelector('tableView:didSelectRowAtIndexPath:')
|
||||
).toEqual(['tableView']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Source-window attribute detection', () => {
|
||||
it('detects literal @objc(custom)', () => {
|
||||
expect(detectExplicitObjcName(' @objc(custom:)\n func foo() {}')).toBe(
|
||||
'custom:'
|
||||
);
|
||||
});
|
||||
|
||||
it('returns null for plain @objc', () => {
|
||||
expect(detectExplicitObjcName('@objc func foo() {}')).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when no @objc at all', () => {
|
||||
expect(detectExplicitObjcName('public func foo() {}')).toBeNull();
|
||||
});
|
||||
|
||||
it('isObjcExposed true for @objc', () => {
|
||||
expect(isObjcExposed('@objc func foo() {}')).toBe(true);
|
||||
});
|
||||
|
||||
it('isObjcExposed true for @objc(custom)', () => {
|
||||
expect(isObjcExposed('@objc(custom:) func foo() {}')).toBe(true);
|
||||
});
|
||||
|
||||
it('isObjcExposed false for no annotation', () => {
|
||||
expect(isObjcExposed('public func foo() {}')).toBe(false);
|
||||
});
|
||||
|
||||
it('@nonobjc opts out even if @objc also present (e.g. inside @objcMembers class)', () => {
|
||||
expect(isObjcExposed('@nonobjc @objc func foo() {}')).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user