Skip to content
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

[swift2objc] Support Protocols #1832

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
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
27 changes: 27 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 @@ -71,6 +72,7 @@ class DeclaredType<T extends Declaration> extends AstNode

/// Describes a reference of a generic type
/// (e.g a method return type `T` within a generic class).
/// TODO(): Add Type Constrains and extend to support associated types
class GenericType extends AstNode implements ReferredType {
final String id;

Expand All @@ -97,6 +99,31 @@ class GenericType extends AstNode implements ReferredType {
void visit(Visitation visitation) => visitation.visitGenericType(this);
}

class AssociatedType extends AstNode implements ReferredType {
final String id;

final String name;


@override
bool get isObjCRepresentable => false;

@override
String get swiftType => name;

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

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

@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,25 @@

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;

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

extension AsAssociatedType<T extends AssociatedTypeDeclaration> on T {
AssociatedType asType() => AssociatedType(
id: id, name: name
);
}
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/associated_type_declaration.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,9 +26,25 @@ class ProtocolDeclaration extends AstNode implements CompoundDeclaration {
@override
covariant List<MethodDeclaration> methods;

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

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

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

@override
List<DeclaredType<ProtocolDeclaration>> conformedProtocols;

@override
bool hasObjCAnnotation;

@override
List<GenericType> typeParams;

Expand All @@ -47,8 +65,12 @@ class ProtocolDeclaration extends AstNode implements CompoundDeclaration {
required this.initializers,
required this.conformedProtocols,
required this.typeParams,
this.associatedTypes = const [],
this.hasObjCAnnotation = false,
this.nestingParent,
this.nestedDeclarations = const [],
this.optionalMethods = const [],
this.optionalProperties = const [],
});

@override
Expand Down
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// 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 '../../../ast/declarations/compounds/members/associated_type_declaration.dart';
import '../../_core/json.dart';
import '../../_core/parsed_symbolgraph.dart';
import '../../_core/utils.dart';

AssociatedTypeDeclaration parseAssociatedTypeDeclaration(Json symbolJson, ParsedSymbolgraph symbolGraph) {
final id = parseSymbolId(symbolJson);
final name = parseSymbolName(symbolJson);

return AssociatedTypeDeclaration(id: id, name: name);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
// BSD-style license that can be found in the LICENSE file.

import '../../../ast/_core/interfaces/compound_declaration.dart';
import '../../../ast/_core/interfaces/declaration.dart';
import '../../../ast/_core/interfaces/nestable_declaration.dart';
import '../../../ast/declarations/compounds/class_declaration.dart';
import '../../../ast/declarations/compounds/members/associated_type_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 '../../../ast/declarations/compounds/struct_declaration.dart';
import '../../_core/parsed_symbolgraph.dart';
import '../../_core/utils.dart';
Expand Down Expand Up @@ -107,3 +110,137 @@ StructDeclaration parseStructDeclaration(
symbolgraph,
);
}

// This won't work as there's more for a protocol declaration
// Placing this here as placeholder declaration
// TODO: Implement extensions before adding support for default implementations
// 5. protocol func with reimpl in extension -> requirementOf
// and defaultImplementationOf, swift.method
// 6. protocol var with reimpl in extension -> requirementOf
// and defaultImplementationOf, swift.property,
// TODO: Replace generics to associatedType and implement
ProtocolDeclaration parseProtocolDeclaration(
ParsedSymbol protocolSymbol,
ParsedSymbolgraph symbolgraph
) {
final compoundId = parseSymbolId(protocolSymbol.json);
final compoundRelations = symbolgraph.relations[compoundId] ?? [];

// construct protocol
final protocol = ProtocolDeclaration(
id: compoundId, name: parseSymbolName(protocolSymbol.json),
properties: [],
methods: [],
initializers: [],
conformedProtocols: [],
typeParams: []
);

// get optional member declarations if any
final optionalMemberDeclarations = compoundRelations.where((relation) {
final isOptionalRequirementRelation =
relation.kind == ParsedRelationKind.optionalRequirementOf;
final isMemberOfProtocol = relation.targetId == compoundId;
return isMemberOfProtocol && isOptionalRequirementRelation;
}).map((relation) {
final memberSymbol = symbolgraph.symbols[relation.sourceId];
if (memberSymbol == null) {
return null;
}
return tryParseDeclaration(memberSymbol, symbolgraph);
})
.nonNulls
.dedupeBy((decl) => decl.id)
.toList()
;

// get normal member declarations
final memberDeclarations = compoundRelations.where((relation) {
final isOptionalRequirementRelation =
relation.kind == ParsedRelationKind.requirementOf
&& relation.kind != ParsedRelationKind.optionalRequirementOf;
final isMemberOfProtocol = relation.targetId == compoundId;
return isMemberOfProtocol && isOptionalRequirementRelation;
}).map((relation) {
final memberSymbol = symbolgraph.symbols[relation.sourceId];
if (memberSymbol == null) {
return null;
}
return tryParseDeclaration(memberSymbol, symbolgraph);
})
.nonNulls
.dedupeBy((decl) => decl.id)
.toList()
;

// get conformed protocols
final conformedProtocolDeclarations = compoundRelations.where((relation) {
final isOptionalRequirementRelation =
relation.kind == ParsedRelationKind.conformsTo;
final isMemberOfProtocol = relation.targetId == compoundId;
return isMemberOfProtocol && isOptionalRequirementRelation;
}).map((relation) {
final memberSymbol = symbolgraph.symbols[relation.sourceId];
if (memberSymbol == null) {
return null;
}
var conformedDecl = tryParseDeclaration(memberSymbol, symbolgraph) as ProtocolDeclaration;
return conformedDecl.asDeclaredType;
})
.nonNulls
.dedupeBy((decl) => decl.id)
.toList()
;

// If the protocol has optional members, it must be annotated with `@objc`
if (optionalMemberDeclarations.isNotEmpty) {
protocol.hasObjCAnnotation = true;
}

protocol.associatedTypes.addAll(
memberDeclarations
.whereType<AssociatedTypeDeclaration>()
.map((decl) => decl.asType())
.dedupeBy((m) => m.name)
);

protocol.methods.addAll(
memberDeclarations
.whereType<MethodDeclaration>()
.dedupeBy((m) => m.fullName),
);

protocol.properties.addAll(
memberDeclarations.whereType<PropertyDeclaration>(),
);

protocol.optionalMethods.addAll(
optionalMemberDeclarations
.whereType<MethodDeclaration>()
.dedupeBy((m) => m.fullName),
);

protocol.optionalProperties.addAll(
optionalMemberDeclarations.whereType<PropertyDeclaration>(),
);

protocol.conformedProtocols.addAll(
conformedProtocolDeclarations
);

protocol.initializers.addAll(
memberDeclarations
.whereType<InitializerDeclaration>()
.dedupeBy((m) => m.fullName),
);

protocol.nestedDeclarations.addAll(
memberDeclarations.whereType<NestableDeclaration>(),
);

protocol.nestedDeclarations.fillNestingParents(protocol);



return protocol;
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@
import 'package:logging/logging.dart';

import '../../ast/_core/interfaces/declaration.dart';
import '../../ast/_core/shared/referred_type.dart';
import '../../ast/declarations/compounds/members/associated_type_declaration.dart';
import '../_core/json.dart';
import '../_core/parsed_symbolgraph.dart';
import '../_core/utils.dart';
import 'declaration_parsers/parse_associated_type_declaration.dart';
import 'declaration_parsers/parse_compound_declaration.dart';
import 'declaration_parsers/parse_function_declaration.dart';
import 'declaration_parsers/parse_initializer_declaration.dart';
Expand Down Expand Up @@ -56,6 +60,8 @@ Declaration parseDeclaration(
'swift.init' => parseInitializerDeclaration(symbolJson, symbolgraph),
'swift.func' => parseGlobalFunctionDeclaration(symbolJson, symbolgraph),
'swift.var' => parseGlobalVariableDeclaration(symbolJson, symbolgraph),
'swift.protocol' => parseProtocolDeclaration(parsedSymbol, symbolgraph),
'swift.associatedtype' => parseAssociatedTypeDeclaration(symbolJson, symbolgraph),
_ => throw Exception(
'Symbol of type $symbolType is not implemented yet.',
),
Expand Down
1 change: 1 addition & 0 deletions pkgs/swift2objc/lib/src/parser/parsers/parse_type.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import '../_core/parsed_symbolgraph.dart';
import '../_core/token_list.dart';
import 'parse_declarations.dart';


/// Parse a type from a list of Json fragments.
///
/// Returns the parsed type, and a Json slice of the remaining fragments that
Expand Down
Loading