Skip to content

[ffigen] Add protocol methods to interfaces #1567

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion pkgs/ffigen/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
## 14.1.0-wip
## 15.0.0-wip

- Dedupe `ObjCBlock` trampolines to reduce generated ObjC code.
- ObjC objects now include the methods from the protocols they implement. Both
required and optional methods are included. Optional methods will throw an
exception if the method isn't implemented.

## 14.0.1

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class ObjCBuiltInFunctions {
static const msgSendFpretPointer = ObjCImport('msgSendFpretPointer');
static const msgSendStretPointer = ObjCImport('msgSendStretPointer');
static const useMsgSendVariants = ObjCImport('useMsgSendVariants');
static const respondsToSelector = ObjCImport('respondsToSelector');
static const newPointerBlock = ObjCImport('newPointerBlock');
static const newClosureBlock = ObjCImport('newClosureBlock');
static const getBlockClosure = ObjCImport('getBlockClosure');
Expand All @@ -37,6 +38,8 @@ class ObjCBuiltInFunctions {
ObjCImport('ObjCProtocolListenableMethod');
static const protocolBuilder = ObjCImport('ObjCProtocolBuilder');
static const dartProxy = ObjCImport('DartProxy');
static const unimplementedOptionalMethodException =
ObjCImport('UnimplementedOptionalMethodException');

// Keep in sync with pkgs/objective_c/ffigen_objc.yaml.
static const builtInInterfaces = {
Expand Down
24 changes: 21 additions & 3 deletions pkgs/ffigen/lib/src/code_generator/objc_interface.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class ObjCInterface extends BindingType with ObjCMethods {
late final ObjCInternalGlobal _classObject;
late final ObjCInternalGlobal _isKindOfClass;
late final ObjCMsgSendFunc _isKindOfClassMsgSend;
final _protocols = <ObjCProtocol>[];

@override
final ObjCBuiltInFunctions builtInFunctions;
Expand All @@ -55,6 +56,7 @@ class ObjCInterface extends BindingType with ObjCMethods {
}) : lookupName = lookupName ?? originalName,
super(name: name ?? originalName);

void addProtocol(ObjCProtocol proto) => _protocols.add(proto);
bool get _isBuiltIn => builtInFunctions.isBuiltInInterface(originalName);

@override
Expand Down Expand Up @@ -185,6 +187,15 @@ class ObjCInterface extends BindingType with ObjCMethods {
s.write(' {\n');

// Implementation.
final sel = m.selObject!.name;
if (m.isOptional) {
s.write('''
if (!${ObjCBuiltInFunctions.respondsToSelector.gen(w)}(ref.pointer, $sel)) {
throw ${ObjCBuiltInFunctions.unimplementedOptionalMethodException.gen(w)}(
'$originalName', '${m.originalName}');
}
''');
}
final convertReturn = m.kind != ObjCMethodKind.propertySetter &&
!returnType.sameDartAndFfiDartType;

Expand All @@ -201,7 +212,7 @@ class ObjCInterface extends BindingType with ObjCMethods {
objCRetain: m.consumesSelf,
objCAutorelease: false,
),
m.selObject!.name,
sel,
m.params.map((p) => p.type.convertDartTypeToFfiDartType(
w,
p.name,
Expand Down Expand Up @@ -252,10 +263,17 @@ class ObjCInterface extends BindingType with ObjCMethods {
superType!.addDependencies(dependencies);
_copyMethodsFromSuperType();
_fixNullabilityOfOverriddenMethods();
}

// Add dependencies for any methods that were added.
addMethodDependencies(dependencies, needMsgSend: true);
for (final proto in _protocols) {
proto.addDependencies(dependencies);
for (final m in proto.methods) {
addMethod(m);
}
}

// Add dependencies for any methods that were added.
addMethodDependencies(dependencies, needMsgSend: true);
}

void _copyMethodsFromSuperType() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import '../data.dart';
import '../includer.dart';
import '../utils.dart';
import 'api_availability.dart';
import 'objcprotocoldecl_parser.dart';

final _logger = Logger('ffigen.header_parser.objcinterfacedecl_parser');

Expand Down Expand Up @@ -76,6 +77,9 @@ void _fillInterface(ObjCInterface itf, clang_types.CXCursor cursor) {
case clang_types.CXCursorKind.CXCursor_ObjCSuperClassRef:
_parseSuperType(child, itf);
break;
case clang_types.CXCursorKind.CXCursor_ObjCProtocolRef:
_parseProtocol(child, itf);
break;
case clang_types.CXCursorKind.CXCursor_ObjCPropertyDecl:
_parseProperty(child, itf, itfDecl);
break;
Expand Down Expand Up @@ -112,6 +116,14 @@ void _parseSuperType(clang_types.CXCursor cursor, ObjCInterface itf) {
}
}

void _parseProtocol(clang_types.CXCursor cursor, ObjCInterface itf) {
final protoCursor = clang.clang_getCursorDefinition(cursor);
final proto = parseObjCProtocolDeclaration(protoCursor);
if (proto != null) {
itf.addProtocol(proto);
}
}

void _parseProperty(
clang_types.CXCursor cursor, ObjCInterface itf, Declaration itfDecl) {
final fieldName = cursor.spelling();
Expand Down
2 changes: 1 addition & 1 deletion pkgs/ffigen/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# BSD-style license that can be found in the LICENSE file.

name: ffigen
version: 14.1.0-wip
version: 15.0.0-wip
description: >
Generator for FFI bindings, using LibClang to parse C, Objective-C, and Swift
files.
Expand Down
10 changes: 6 additions & 4 deletions pkgs/ffigen/test/large_integration_tests/large_objc_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
@TestOn('mac-os')

// This is a slow test.
@Timeout(Duration(minutes: 2))
@Timeout(Duration(minutes: 5))
library;

import 'dart:async';
Expand All @@ -28,7 +28,7 @@ Future<int> run(String exe, List<String> args) async {

void main() {
test('Large ObjC integration test', () async {
// Reducing the bindings to a random subset to that the test completes in a
// Reducing the bindings to a random subset so that the test completes in a
// reasonable amount of time.
// TODO(https://github.com/dart-lang/sdk/issues/56247): Remove this.
const inclusionRatio = 0.1;
Expand All @@ -41,10 +41,12 @@ void main() {

// TODO(https://github.com/dart-lang/native/issues/1220): Allow these.
const disallowedMethods = {
'cachePolicy',
'accessKey',
'allowsConstrainedNetworkAccess',
'tag',
'attributedString',
'cachePolicy',
'hyphenationFactor',
'tag',
};
final interfaceFilter = DeclarationFilters(
shouldInclude: randInclude,
Expand Down
2 changes: 1 addition & 1 deletion pkgs/ffigen/test/native_objc_test/protocol_config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ objc-protocols:
- SecondaryProtocol
headers:
entry-points:
- 'protocol_test.m'
- 'protocol_test.h'
preamble: |
// ignore_for_file: camel_case_types, non_constant_identifier_names, unnecessary_non_null_assertion, unused_element, unused_field
34 changes: 34 additions & 0 deletions pkgs/ffigen/test/native_objc_test/protocol_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'dart:async';
import 'dart:ffi';
import 'dart:io';

import 'package:ffi/ffi.dart';
import 'package:objective_c/objective_c.dart';
import 'package:test/test.dart';

Expand Down Expand Up @@ -50,6 +51,27 @@ void main() {
expect(otherIntResult, 10);
});

test('Method implementation, invoke from Dart', () {
final protocolImpl = ObjCProtocolImpl.new1();

// Required instance method.
final result =
protocolImpl.instanceMethod_withDouble_("abc".toNSString(), 123);
expect(result.toString(), 'ObjCProtocolImpl: abc: 123.00');

// Optional instance method.
final structPtr = calloc<SomeStruct>();
structPtr.ref.x = 12;
structPtr.ref.y = 34;
final intResult = protocolImpl.optionalMethod_(structPtr.ref);
expect(intResult, 46);
calloc.free(structPtr);

// Required instance method from secondary protocol.
final otherIntResult = protocolImpl.otherMethod_b_c_d_(2, 4, 6, 8);
expect(otherIntResult, 20);
});

test('Unimplemented method', () {
final protocolImpl = ObjCProtocolImplMissingMethod.new1();
final consumer = ProtocolConsumer.new1();
Expand All @@ -58,6 +80,18 @@ void main() {
final intResult = consumer.callOptionalMethod_(protocolImpl);
expect(intResult, -999);
});

test('Unimplemented method, invoke from Dart', () {
final protocolImpl = ObjCProtocolImplMissingMethod.new1();

// Optional instance method, not implemented.
final structPtr = calloc<SomeStruct>();
structPtr.ref.x = 12;
structPtr.ref.y = 34;
expect(() => protocolImpl.optionalMethod_(structPtr.ref),
throwsA(isA<UnimplementedOptionalMethodException>()));
calloc.free(structPtr);
});
});

group('Dart implementation using helpers', () {
Expand Down
60 changes: 60 additions & 0 deletions pkgs/ffigen/test/native_objc_test/protocol_test.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>

#include "util.h"

typedef struct {
int32_t x;
int32_t y;
} SomeStruct;

@protocol SuperProtocol<NSObject>

@required
- (NSString*)instanceMethod:(NSString*)s withDouble:(double)x;

@end

@protocol MyProtocol<SuperProtocol>

@optional
- (int32_t)optionalMethod:(SomeStruct)s;

@optional
- (void)voidMethod:(int32_t)x;

@end


@protocol SecondaryProtocol<NSObject>

@required
- (int32_t)otherMethod:(int32_t)a b:(int32_t)b c:(int32_t)c d:(int32_t)d;

@optional
- (nullable instancetype)returnsInstanceType;

@end

@protocol EmptyProtocol
@end


@interface ProtocolConsumer : NSObject
- (NSString*)callInstanceMethod:(id<MyProtocol>)protocol;
- (int32_t)callOptionalMethod:(id<MyProtocol>)protocol;
- (int32_t)callOtherMethod:(id<SecondaryProtocol>)protocol;
- (void)callMethodOnRandomThread:(id<SecondaryProtocol>)protocol;
@end


@interface ObjCProtocolImpl : NSObject<MyProtocol, SecondaryProtocol>
@end


@interface ObjCProtocolImplMissingMethod : NSObject<MyProtocol>
@end
53 changes: 1 addition & 52 deletions pkgs/ffigen/test/native_objc_test/protocol_test.m
Original file line number Diff line number Diff line change
Expand Up @@ -3,55 +3,10 @@
// BSD-style license that can be found in the LICENSE file.

#import <dispatch/dispatch.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>

#include "protocol_test.h"
#include "util.h"

typedef struct {
int32_t x;
int32_t y;
} SomeStruct;

@protocol SuperProtocol<NSObject>

@required
- (NSString*)instanceMethod:(NSString*)s withDouble:(double)x;

@end

@protocol MyProtocol<SuperProtocol>

@optional
- (int32_t)optionalMethod:(SomeStruct)s;

@optional
- (void)voidMethod:(int32_t)x;

@end


@protocol SecondaryProtocol<NSObject>

@required
- (int32_t)otherMethod:(int32_t)a b:(int32_t)b c:(int32_t)c d:(int32_t)d;

@optional
- (nullable instancetype)returnsInstanceType;

@end

@protocol EmptyProtocol
@end


@interface ProtocolConsumer : NSObject
- (NSString*)callInstanceMethod:(id<MyProtocol>)protocol;
- (int32_t)callOptionalMethod:(id<MyProtocol>)protocol;
- (int32_t)callOtherMethod:(id<SecondaryProtocol>)protocol;
- (void)callMethodOnRandomThread:(id<SecondaryProtocol>)protocol;
@end

@implementation ProtocolConsumer : NSObject
- (NSString*)callInstanceMethod:(id<MyProtocol>)protocol {
return [protocol instanceMethod:@"Hello from ObjC" withDouble:3.14];
Expand All @@ -78,9 +33,6 @@ - (void)callMethodOnRandomThread:(id<MyProtocol>)protocol {
@end


@interface ObjCProtocolImpl : NSObject<MyProtocol, SecondaryProtocol>
@end

@implementation ObjCProtocolImpl
- (NSString *)instanceMethod:(NSString *)s withDouble:(double)x {
return [NSString stringWithFormat:@"ObjCProtocolImpl: %@: %.2f", s, x];
Expand All @@ -97,9 +49,6 @@ - (int32_t)otherMethod:(int32_t)a b:(int32_t)b c:(int32_t)c d:(int32_t)d {
@end


@interface ObjCProtocolImplMissingMethod : NSObject<MyProtocol>
@end

@implementation ObjCProtocolImplMissingMethod
- (NSString *)instanceMethod:(NSString *)s withDouble:(double)x {
return @"ObjCProtocolImplMissingMethod";
Expand Down
6 changes: 6 additions & 0 deletions pkgs/objective_c/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## 2.1.0-wip

- Add `UnimplementedOptionalMethodException`, which is thrown by the ObjC
bindings if an optional method is invoked, and the instance doesn't implement
the method.

## 2.0.0

- Drop API methods that are deprecated in the oldest versions of iOS and macOS
Expand Down
Loading
Loading