Skip to content

[pigeon] Improve style of generated Swift code #5938

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
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
4 changes: 4 additions & 0 deletions packages/pigeon/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 16.0.4

* [swift] Improve style of Swift output.

## 16.0.3

* [kotlin] Separates message call code generation into separate methods.
Expand Down
37 changes: 19 additions & 18 deletions packages/pigeon/example/app/ios/Runner/Messages.g.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
// See also: https://pub.dev/packages/pigeon

import Foundation

#if os(iOS)
import Flutter
import Flutter
#elseif os(macOS)
import FlutterMacOS
import FlutterMacOS
#else
#error("Unsupported platform.")
#error("Unsupported platform.")
#endif

private func wrapResult(_ result: Any?) -> [Any?] {
Expand All @@ -22,13 +23,13 @@ private func wrapError(_ error: Any) -> [Any?] {
return [
flutterError.code,
flutterError.message,
flutterError.details
flutterError.details,
]
}
return [
"\(error)",
"\(type(of: error))",
"Stacktrace: \(Thread.callStackSymbols)"
"Stacktrace: \(Thread.callStackSymbols)",
]
}

Expand Down Expand Up @@ -83,10 +84,10 @@ struct MessageData {
private class ExampleHostApiCodecReader: FlutterStandardReader {
override func readValue(ofType type: UInt8) -> Any? {
switch type {
case 128:
return MessageData.fromList(self.readValue() as! [Any?])
default:
return super.readValue(ofType: type)
case 128:
return MessageData.fromList(self.readValue() as! [Any?])
default:
return super.readValue(ofType: type)
}
}
}
Expand Down Expand Up @@ -165,10 +166,10 @@ class ExampleHostApiSetup {
let messageArg = args[0] as! MessageData
api.sendMessage(message: messageArg) { result in
switch result {
case .success(let res):
reply(wrapResult(res))
case .failure(let error):
reply(wrapError(error))
case .success(let res):
reply(wrapResult(res))
case .failure(let error):
reply(wrapError(error))
}
}
}
Expand All @@ -183,23 +184,23 @@ protocol MessageFlutterApiProtocol {
}
class MessageFlutterApi: MessageFlutterApiProtocol {
private let binaryMessenger: FlutterBinaryMessenger
init(binaryMessenger: FlutterBinaryMessenger){
init(binaryMessenger: FlutterBinaryMessenger) {
self.binaryMessenger = binaryMessenger
}
func flutterMethod(aString aStringArg: String?, completion: @escaping (Result<String, FlutterError>) -> Void) {
let channelName: String = "dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod"
let channel = FlutterBasicMessageChannel(name: channelName, binaryMessenger: binaryMessenger)
channel.sendMessage([aStringArg] as [Any?]) { response in
guard let listResponse = response as? [Any?] else {
completion(.failure(createConnectionError(withChannelName:channelName)))
completion(.failure(createConnectionError(withChannelName: channelName)))
return
}
if (listResponse.count > 1) {
if listResponse.count > 1 {
let code: String = listResponse[0] as! String
let message: String? = nilOrValue(listResponse[1])
let details: String? = nilOrValue(listResponse[2])
completion(.failure(FlutterError(code: code, message: message, details: details)));
} else if (listResponse[0] == nil) {
completion(.failure(FlutterError(code: code, message: message, details: details)))
} else if listResponse[0] == nil {
completion(.failure(FlutterError(code: "null-error", message: "Flutter api returned null value for non-null return value.", details: "")))
} else {
let result = listResponse[0] as! String
Expand Down
4 changes: 2 additions & 2 deletions packages/pigeon/lib/generator_tools.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import 'ast.dart';
/// The current version of pigeon.
///
/// This must match the version in pubspec.yaml.
const String pigeonVersion = '16.0.3';
const String pigeonVersion = '16.0.4';

/// Read all the content from [stdin] to a String.
String readStdin() {
Expand Down Expand Up @@ -309,7 +309,7 @@ bool isVoid(TypeMirror type) {
void addLines(Indent indent, Iterable<String> lines, {String? linePrefix}) {
final String prefix = linePrefix ?? '';
for (final String line in lines) {
indent.writeln('$prefix$line');
indent.writeln(line.isNotEmpty ? '$prefix$line' : prefix.trimRight());
}
}

Expand Down
38 changes: 24 additions & 14 deletions packages/pigeon/lib/swift_generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,14 @@ class SwiftGenerator extends StructuredGenerator<SwiftOptions> {
required String dartPackageName,
}) {
indent.writeln('import Foundation');
indent.newln();
indent.format('''
#if os(iOS)
import Flutter
import Flutter
#elseif os(macOS)
import FlutterMacOS
import FlutterMacOS
#else
#error("Unsupported platform.")
#error("Unsupported platform.")
#endif''');
}

Expand Down Expand Up @@ -160,6 +161,9 @@ import FlutterMacOS
indent.addScoped('{', '}', () {
indent.write('return ');
indent.addScoped('[', ']', () {
// Follow swift-format style, which is to use a trailing comma unless
// there is only one element.
final String separator = classDefinition.fields.length > 1 ? ',' : '';
for (final NamedType field
in getFieldsInSerializationOrder(classDefinition)) {
String toWriteValue = '';
Expand All @@ -173,7 +177,7 @@ import FlutterMacOS
toWriteValue = field.name;
}

indent.writeln('$toWriteValue,');
indent.writeln('$toWriteValue$separator');
}
});
});
Expand Down Expand Up @@ -294,7 +298,7 @@ import FlutterMacOS
indent.write('class ${api.name}: ${api.name}Protocol ');
indent.addScoped('{', '}', () {
indent.writeln('private let binaryMessenger: FlutterBinaryMessenger');
indent.write('init(binaryMessenger: FlutterBinaryMessenger)');
indent.write('init(binaryMessenger: FlutterBinaryMessenger) ');
indent.addScoped('{', '}', () {
indent.writeln('self.binaryMessenger = binaryMessenger');
});
Expand Down Expand Up @@ -330,20 +334,20 @@ import FlutterMacOS
indent.writeScoped(
'guard let listResponse = response as? [Any?] else {', '}', () {
indent.writeln(
'completion(.failure(createConnectionError(withChannelName:channelName)))');
'completion(.failure(createConnectionError(withChannelName: channelName)))');
indent.writeln('return');
});
indent.writeScoped('if (listResponse.count > 1) {', '} ', () {
indent.writeScoped('if listResponse.count > 1 {', '} ', () {
indent.writeln('let code: String = listResponse[0] as! String');
indent.writeln(
'let message: String? = nilOrValue(listResponse[1])');
indent.writeln(
'let details: String? = nilOrValue(listResponse[2])');
indent.writeln(
'completion(.failure(FlutterError(code: code, message: message, details: details)));');
'completion(.failure(FlutterError(code: code, message: message, details: details)))');
}, addTrailingNewline: false);
if (!func.returnType.isNullable && !func.returnType.isVoid) {
indent.addScoped('else if (listResponse[0] == nil) {', '} ', () {
indent.addScoped('else if listResponse[0] == nil {', '} ', () {
indent.writeln(
'completion(.failure(FlutterError(code: "null-error", message: "Flutter api returned null value for non-null return value.", details: "")))');
}, addTrailingNewline: false);
Expand Down Expand Up @@ -495,8 +499,14 @@ import FlutterMacOS
});
}
final String tryStatement = method.isAsynchronous ? '' : 'try ';
// Empty parens are not required when calling a method whose only
// argument is a trailing closure.
final String argumentString =
methodArgument.isEmpty && method.isAsynchronous
? ''
: '(${methodArgument.join(', ')})';
final String call =
'${tryStatement}api.${components.name}(${methodArgument.join(', ')})';
'${tryStatement}api.${components.name}$argumentString';
if (method.isAsynchronous) {
final String resultName =
method.returnType.isVoid ? 'nil' : 'res';
Expand All @@ -506,7 +516,7 @@ import FlutterMacOS

indent.addScoped('{ result in', '}', () {
indent.write('switch result ');
indent.addScoped('{', '}', () {
indent.addScoped('{', '}', nestCount: 0, () {
final String nullsafe =
method.returnType.isNullable ? '?' : '';
final String enumTag =
Expand Down Expand Up @@ -573,7 +583,7 @@ import FlutterMacOS
indent.write('override func readValue(ofType type: UInt8) -> Any? ');
indent.addScoped('{', '}', () {
indent.write('switch type ');
indent.addScoped('{', '}', () {
indent.addScoped('{', '}', nestCount: 0, () {
for (final EnumeratedClass customClass
in getCodecClasses(api, root)) {
indent.writeln('case ${customClass.enumeration}:');
Expand Down Expand Up @@ -764,14 +774,14 @@ import FlutterMacOS
indent.addScoped('[', ']', () {
indent.writeln('flutterError.code,');
indent.writeln('flutterError.message,');
indent.writeln('flutterError.details');
indent.writeln('flutterError.details,');
});
});
indent.write('return ');
indent.addScoped('[', ']', () {
indent.writeln(r'"\(error)",');
indent.writeln(r'"\(type(of: error))",');
indent.writeln(r'"Stacktrace: \(Thread.callStackSymbols)"');
indent.writeln(r'"Stacktrace: \(Thread.callStackSymbols)",');
});
});
}
Expand Down
Loading