Skip to content

[swift2objc] Support Protocols #1832

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

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
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
28 changes: 28 additions & 0 deletions pkgs/swift2objc/lib/src/ast/_core/shared/referred_type.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// BSD-style license that can be found in the LICENSE file.

import '../../ast_node.dart';
import '../../declarations/compounds/protocol_declaration.dart';
import '../interfaces/declaration.dart';
import '../interfaces/nestable_declaration.dart';
import '../interfaces/objc_annotatable.dart';
Expand Down Expand Up @@ -97,6 +98,33 @@ class GenericType extends AstNode implements ReferredType {
void visit(Visitation visitation) => visitation.visitGenericType(this);
}

/// Associated Types are similar to Generics, but in the context of protocols.
/// They are declared with an `associatedType` keyword inside a protocol.
///
/// For more information: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/generics/#Associated-Types
class AssociatedType extends AstNode implements ReferredType {
final String id;

final String name;

@override
bool get isObjCRepresentable => false;

@override
String get swiftType => name;

List<DeclaredType<ProtocolDeclaration>> conformedProtocols;

@override
bool sameAs(ReferredType other) => other is AssociatedType && other.id == id;

AssociatedType(
{required this.id, required this.name, required this.conformedProtocols});

@override
String toString() => name;
}

/// An optional type, like Dart's nullable types. Eg `String?`.
class OptionalType extends AstNode implements ReferredType {
final ReferredType child;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import '../../../_core/interfaces/declaration.dart';
import '../../../_core/shared/referred_type.dart';
import '../../../ast_node.dart';
import '../protocol_declaration.dart';

class AssociatedTypeDeclaration extends AstNode implements Declaration {
@override
String id;

@override
String name;

List<DeclaredType<ProtocolDeclaration>> conformedProtocols;

AssociatedTypeDeclaration(
{required this.id, required this.name, required this.conformedProtocols});
}

extension AsAssociatedType<T extends AssociatedTypeDeclaration> on T {
AssociatedType asType() => AssociatedType(
id: id, name: name, conformedProtocols: conformedProtocols);
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import '../../../_core/shared/parameter.dart';
import '../../../ast_node.dart';

/// Describes an initializer for a Swift compound entity (e.g, class, structs)
/// TODO(https://github.com/dart-lang/native/issues/2048): Convenience and Required Initializers
class InitializerDeclaration extends AstNode
implements
Declaration,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import '../../../ast_node.dart';

/// Describes a method declaration for a Swift compound entity
/// (e.g, class, structs)
/// TODO(https://github.com/dart-lang/native/issues/2049): Add support for private(set) functions
class MethodDeclaration extends AstNode
implements FunctionDeclaration, ObjCAnnotatable, Overridable {
@override
Expand Down Expand Up @@ -45,13 +46,16 @@ class MethodDeclaration extends AstNode

bool isStatic;

bool public;

bool mutating;

String get fullName => [
name,
for (final p in params) p.name,
].join(':');


MethodDeclaration(
{required this.id,
required this.name,
Expand All @@ -64,6 +68,7 @@ class MethodDeclaration extends AstNode
this.isOverriding = false,
this.throws = false,
this.async = false,
this.public = false,
this.mutating = false})
: assert(!isStatic || !isOverriding);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@

import '../../_core/interfaces/compound_declaration.dart';
import '../../_core/interfaces/nestable_declaration.dart';
import '../../_core/interfaces/objc_annotatable.dart';
import '../../_core/shared/referred_type.dart';
import '../../ast_node.dart';
import 'members/initializer_declaration.dart';
import 'members/method_declaration.dart';
import 'members/property_declaration.dart';

/// Describes the declaration of a Swift protocol.
class ProtocolDeclaration extends AstNode implements CompoundDeclaration {
class ProtocolDeclaration extends AstNode
implements CompoundDeclaration, ObjCAnnotatable {
@override
String id;

Expand All @@ -24,11 +26,21 @@ class ProtocolDeclaration extends AstNode implements CompoundDeclaration {
@override
covariant List<MethodDeclaration> methods;

/// Only present if indicated with `@objc`
List<PropertyDeclaration> optionalProperties;

/// Only present if indicated with `@objc`
List<MethodDeclaration> optionalMethods;

/// Associated types used with this declaration. They are similar to generic
/// types, but only designated for protocol declarations.
List<AssociatedType> associatedTypes;

@override
List<DeclaredType<ProtocolDeclaration>> conformedProtocols;

@override
List<GenericType> typeParams;
bool hasObjCAnnotation;

@override
List<InitializerDeclaration> initializers;
Expand All @@ -46,10 +58,12 @@ class ProtocolDeclaration extends AstNode implements CompoundDeclaration {
required this.methods,
required this.initializers,
required this.conformedProtocols,
required this.typeParams,
this.hasObjCAnnotation = false,
this.nestingParent,
this.nestedDeclarations = const [],
});
}) : associatedTypes = [],
nestedDeclarations = [],
optionalMethods = [],
optionalProperties = [];

@override
void visit(Visitation visitation) =>
Expand All @@ -61,9 +75,13 @@ class ProtocolDeclaration extends AstNode implements CompoundDeclaration {
visitor.visitAll(properties);
visitor.visitAll(methods);
visitor.visitAll(conformedProtocols);
visitor.visitAll(typeParams);
visitor.visitAll(initializers);
visitor.visit(nestingParent);
visitor.visitAll(nestedDeclarations);
}

@override
List<GenericType> get typeParams =>
throw Exception('Protocols do not have type params: '
'Did you mean to use `associatedTypes` instead?');
}
3 changes: 3 additions & 0 deletions pkgs/swift2objc/lib/src/generator/generator.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import '../ast/_core/interfaces/declaration.dart';
import '../ast/declarations/compounds/class_declaration.dart';
import '../ast/declarations/compounds/protocol_declaration.dart';
import 'generators/class_generator.dart';
import 'generators/protocol_generator.dart';

String generate(
List<Declaration> declarations, {
Expand All @@ -19,6 +21,7 @@ String generate(
List<String> generateDeclaration(Declaration declaration) {
return switch (declaration) {
ClassDeclaration() => generateClass(declaration),
ProtocolDeclaration() => generateProtocol(declaration),
_ => throw UnimplementedError(
"$declaration generation isn't implemented yet",
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ List<String> _generateClassProperties(ClassDeclaration declaration) => [
..._generateClassProperty(property),
];

// TODO(https://github.com/dart-lang/native/pull/2056): Generate Class properties for constants (i.e let)
List<String> _generateClassProperty(PropertyDeclaration property) {
final header = StringBuffer();

Expand Down
123 changes: 123 additions & 0 deletions pkgs/swift2objc/lib/src/generator/generators/protocol_generator.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import '../../ast/declarations/built_in/built_in_declaration.dart';
import '../../ast/declarations/compounds/members/initializer_declaration.dart';
import '../../ast/declarations/compounds/members/method_declaration.dart';
import '../../ast/declarations/compounds/members/property_declaration.dart';
import '../../ast/declarations/compounds/protocol_declaration.dart';
import '../_core/utils.dart';

List<String> generateProtocol(ProtocolDeclaration declaration) {
return [
'${_generateProtocolHeader(declaration)} {',
...<String>[
..._generateProtocolProperties(declaration),
..._generateInitializers(declaration),
..._generateProtocolMethods(declaration)
].nonNulls.indent(),
'}\n',
];
}

String _generateProtocolHeader(ProtocolDeclaration declaration) {
final header = StringBuffer();

if (declaration.hasObjCAnnotation) {
header.write('@objc ');
}

header.write('public protocol ${declaration.name}');

final superClassAndProtocols = [
...declaration.conformedProtocols
.map((protocol) => protocol.declaration.name),
].nonNulls;

if (superClassAndProtocols.isNotEmpty) {
header.write(': ${superClassAndProtocols.join(", ")}');
}

return header.toString();
}

List<String> _generateProtocolMethods(ProtocolDeclaration declaration) => [
for (final method in declaration.methods)
..._generateProtocolMethod(method)
];

List<String> _generateProtocolMethod(MethodDeclaration method) {
final header = StringBuffer();

if (method.hasObjCAnnotation) {
header.write('@objc ');
}

if (method.isStatic) {
header.write('static ');
}

header.write(
'func ${method.name}(${generateParameters(method.params)}) ',
);

header.write(generateAnnotations(method));

if (!method.returnType.sameAs(voidType)) {
header.write('-> ${method.returnType.swiftType} ');
}

return ['$header'];
}

List<String> _generateProtocolProperties(ProtocolDeclaration declaration) => [
for (final property in declaration.properties)
..._generateProtocolProperty(property),
];

List<String> _generateProtocolProperty(PropertyDeclaration property) {
final header = StringBuffer();

if (property.hasObjCAnnotation) {
header.write('@objc ');
}

if (property.isStatic) {
header.write('static ');
}

header.write(property.isConstant ? 'let' : 'var');
header.write(' ${property.name}: ${property.type.swiftType}');
header.write(' { ${[
if (property.getter != null) 'get',
if (property.setter != null) 'set'
].join(' ')} }');

return [
header.toString(),
];
}

List<String> _generateInitializers(ProtocolDeclaration declaration) {
final initializers = [
...declaration.initializers,
].nonNulls;
return [for (final init in initializers) ..._generateInitializer(init)];
}

List<String> _generateInitializer(InitializerDeclaration initializer) {
final header = StringBuffer();

if (initializer.hasObjCAnnotation) {
header.write('@objc ');
}

header.write('init');

if (initializer.isFailable) {
header.write('?');
}

header.write('(${generateParameters(initializer.params)})');

return [
'$header ${generateAnnotations(initializer)}',
];
}
4 changes: 4 additions & 0 deletions pkgs/swift2objc/lib/src/parser/_core/parsed_symbolgraph.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ class ParsedRelation {
}

enum ParsedRelationKind {
requirementOf,
defaultImplementationOf,
optionalRequirementOf,
conformsTo,
memberOf;

static final _supportedRelationKindsMap = {
Expand Down
Loading
Loading