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

Open
wants to merge 8 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
24 changes: 24 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,29 @@ 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;

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 @@ -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,9 +26,23 @@ 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
bool hasObjCAnnotation;

@override
List<GenericType> typeParams;

Expand All @@ -47,9 +63,12 @@ class ProtocolDeclaration extends AstNode implements CompoundDeclaration {
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 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,64 @@
// 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/_core/interfaces/declaration.dart';
import '../../../ast/_core/shared/referred_type.dart';
import '../../../ast/declarations/compounds/members/associated_type_declaration.dart';
import '../../../ast/declarations/compounds/protocol_declaration.dart';
import '../../_core/json.dart';
import '../../_core/parsed_symbolgraph.dart';
import '../../_core/utils.dart';
import '../parse_declarations.dart';

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

final conformedProtocols = _parseConformedProtocols(symbolJson, symbolGraph);

return AssociatedTypeDeclaration(
id: id, name: name, conformedProtocols: conformedProtocols);
}

List<DeclaredType<ProtocolDeclaration>> _parseConformedProtocols(
Json symbolJson, ParsedSymbolgraph symbolGraph) {
final conformDecls = <DeclaredType<ProtocolDeclaration>>[];

final identifierIndex = symbolJson['declarationFragments']
.toList()
.indexWhere((t) =>
t['kind'].get<String>() == 'identifier' &&
t['spelling'].get<String>() == 'Element');

if (symbolJson['declarationFragments'].length - 1 > identifierIndex &&
symbolJson['declarationFragments'][identifierIndex + 1]['spelling']
.get<String>()
.trim() ==
':') {
// the associated type contains
final conformList = symbolJson['declarationFragments']
.toList()
.sublist(identifierIndex + 2);
conformList.removeWhere((t) => t['spelling'].get<String>().trim() == ',');

// go through and find, then add
for (final proto in conformList) {
final protoId = proto['preciseIdentifier'].get<String>();

final protoSymbol = symbolGraph.symbols[protoId];

if (protoSymbol == null) {
// return null;
continue;
}

conformDecls.add(
(tryParseDeclaration(protoSymbol, symbolGraph) as ProtocolDeclaration)
.asDeclaredType);
}
}

return conformDecls;
}
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,128 @@ StructDeclaration parseStructDeclaration(
symbolgraph,
);
}

// TODO(https://github.com/dart-lang/native/issues/1815): Implement extensions before adding support for default implementations
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.sourceId == compoundId;
return isMemberOfProtocol && isOptionalRequirementRelation;
})
.map((relation) {
final memberSymbol = symbolgraph.symbols[relation.targetId];
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 @@ -142,6 +142,9 @@ ParsedFunctionInfo parseFunctionInfo(
);
}

// TODO(https://github.com/dart-lang/native/issues/1931): Function Return Type does not support nested types
// (e.g String.UTF8, Self.Element
// (necessary when making use of protocol associated types))
ReferredType _parseFunctionReturnType(
Json methodSymbolJson,
ParsedSymbolgraph symbolgraph,
Expand Down
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 '../../_core/utils.dart';

// TODO(https://github.com/dart-lang/native/issues/1932): Add support for parsing getters and setters in property declarations
PropertyDeclaration parsePropertyDeclaration(
Json propertySymbolJson,
ParsedSymbolgraph symbolgraph, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import 'package:logging/logging.dart';
import '../../ast/_core/interfaces/declaration.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 +57,9 @@ 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
Loading
Loading