forked from flutter/packages
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pigeon_lib.dart
2683 lines (2443 loc) · 93.2 KB
/
pigeon_lib.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: avoid_print
import 'dart:convert';
import 'dart:io';
import 'dart:mirrors';
import 'package:analyzer/dart/analysis/analysis_context.dart'
show AnalysisContext;
import 'package:analyzer/dart/analysis/analysis_context_collection.dart'
show AnalysisContextCollection;
import 'package:analyzer/dart/analysis/results.dart' show ParsedUnitResult;
import 'package:analyzer/dart/analysis/session.dart' show AnalysisSession;
import 'package:analyzer/dart/ast/ast.dart' as dart_ast;
import 'package:analyzer/dart/ast/syntactic_entity.dart'
as dart_ast_syntactic_entity;
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart' as dart_ast_visitor;
import 'package:analyzer/error/error.dart' show AnalysisError;
import 'package:args/args.dart';
import 'package:collection/collection.dart' as collection;
import 'package:path/path.dart' as path;
import 'package:pub_semver/pub_semver.dart';
import 'ast.dart';
import 'ast_generator.dart';
import 'cpp_generator.dart';
import 'dart_generator.dart';
import 'generator_tools.dart';
import 'generator_tools.dart' as generator_tools;
import 'gobject_generator.dart';
import 'java_generator.dart';
import 'kotlin_generator.dart';
import 'objc_generator.dart';
import 'swift_generator.dart';
class _Asynchronous {
const _Asynchronous();
}
class _Attached {
const _Attached();
}
class _Static {
const _Static();
}
/// Metadata to annotate a Api method as asynchronous
const Object async = _Asynchronous();
/// Metadata to annotate the field of a ProxyApi as an Attached Field.
///
/// Attached fields provide a synchronous [ProxyApi] instance as a field for
/// another [ProxyApi].
///
/// Attached fields:
/// * Must be nonnull.
/// * Must be a ProxyApi (a class annotated with `@ProxyApi()`).
/// * Must not contain any unattached fields.
/// * Must not have a required callback Flutter method.
///
/// Example generated code:
///
/// ```dart
/// class MyProxyApi {
/// final MyOtherProxyApi myField = pigeon_myField().
/// }
/// ```
///
/// The field provides access to the value synchronously, but the native
/// instance is stored in the native `InstanceManager` asynchronously. Similar
/// to how constructors are implemented.
const Object attached = _Attached();
/// Metadata to annotate a field of a ProxyApi as static.
///
/// Static fields are the same as [attached] fields except the field is static
/// and not attached to any instance of the ProxyApi.
const Object static = _Static();
/// Metadata annotation used to configure how Pigeon will generate code.
class ConfigurePigeon {
/// Constructor for ConfigurePigeon.
const ConfigurePigeon(this.options);
/// The [PigeonOptions] that will be merged into the command line options.
final PigeonOptions options;
}
/// Metadata to annotate a Pigeon API implemented by the host-platform.
///
/// The abstract class with this annotation groups a collection of Dart↔host
/// interop methods. These methods are invoked by Dart and are received by a
/// host-platform (such as in Android or iOS) by a class implementing the
/// generated host-platform interface.
class HostApi {
/// Parametric constructor for [HostApi].
const HostApi({this.dartHostTestHandler});
/// The name of an interface generated for tests. Implement this
/// interface and invoke `[name of this handler].setup` to receive
/// calls from your real [HostApi] class in Dart instead of the host
/// platform code, as is typical.
///
/// When using this, you must specify the `--out_test_dart` argument
/// to specify where to generate the test file.
///
/// Prefer to use a mock of the real [HostApi] with a mocking library for unit
/// tests. Generating this Dart handler is sometimes useful in integration
/// testing.
///
/// Defaults to `null` in which case no handler will be generated.
final String? dartHostTestHandler;
}
/// Metadata to annotate a Pigeon API implemented by Flutter.
///
/// The abstract class with this annotation groups a collection of Dart↔host
/// interop methods. These methods are invoked by the host-platform (such as in
/// Android or iOS) and are received by Flutter by a class implementing the
/// generated Dart interface.
class FlutterApi {
/// Parametric constructor for [FlutterApi].
const FlutterApi();
}
/// Metadata to annotate a Pigeon API that wraps a native class.
///
/// The abstract class with this annotation groups a collection of Dart↔host
/// constructors, fields, methods and host↔Dart methods used to wrap a native
/// class.
///
/// The generated Dart class acts as a proxy to a native type and maintains
/// instances automatically with an `InstanceManager`. The generated host
/// language class implements methods to interact with class instances or static
/// methods.
class ProxyApi {
/// Parametric constructor for [ProxyApi].
const ProxyApi({this.superClass, this.kotlinOptions, this.swiftOptions});
/// The proxy api that is a super class to this one.
///
/// This provides an alternative to calling `extends` on a class since this
/// requires calling the super class constructor.
///
/// Note that using this instead of `extends` can cause unexpected conflicts
/// with inherited method names.
final Type? superClass;
/// Options that control how Swift code will be generated for a specific
/// ProxyApi.
final SwiftProxyApiOptions? swiftOptions;
/// Options that control how Kotlin code will be generated for a specific
/// ProxyApi.
final KotlinProxyApiOptions? kotlinOptions;
}
/// Metadata to annotate a pigeon API that contains event channels.
///
/// This class is a tool to designate a set of event channel methods,
/// the class itself will not be generated.
///
/// All methods contained within the class will return a `Stream` of the
/// defined return type of the method definition.
class EventChannelApi {
/// Constructor.
const EventChannelApi();
}
/// Metadata to annotation methods to control the selector used for objc output.
/// The number of components in the provided selector must match the number of
/// arguments in the annotated method.
/// For example:
/// @ObjcSelector('divideValue:by:') double divide(int x, int y);
class ObjCSelector {
/// Constructor.
const ObjCSelector(this.value);
/// The string representation of the selector.
final String value;
}
/// Metadata to annotate methods to control the signature used for Swift output.
///
/// The number of components in the provided signature must match the number of
/// arguments in the annotated method.
/// For example:
/// @SwiftFunction('divide(_:by:)') double divide(int x, String y);
class SwiftFunction {
/// Constructor.
const SwiftFunction(this.value);
/// The string representation of the function signature.
final String value;
}
/// Metadata to annotate data classes to be defined as class in Swift output.
class SwiftClass {
/// Constructor.
const SwiftClass();
}
/// Type of TaskQueue which determines how handlers are dispatched for
/// HostApi's.
enum TaskQueueType {
/// Handlers are invoked serially on the default thread. This is the value if
/// unspecified.
serial,
/// Handlers are invoked serially on a background thread.
serialBackgroundThread,
// TODO(gaaclarke): Add support for concurrent task queues.
// /// Handlers are invoked concurrently on a background thread.
// concurrentBackgroundThread,
}
/// Metadata annotation to control how handlers are dispatched for HostApi's.
/// Note that the TaskQueue API might not be available on the target version of
/// Flutter, see also:
/// https://docs.flutter.dev/development/platform-integration/platform-channels.
class TaskQueue {
/// The constructor for a TaskQueue.
const TaskQueue({required this.type});
/// The type of the TaskQueue.
final TaskQueueType type;
}
/// Represents an error as a result of parsing and generating code.
class Error {
/// Parametric constructor for Error.
Error({
required this.message,
this.filename,
this.lineNumber,
});
/// A description of the error.
String message;
/// What file caused the [Error].
String? filename;
/// What line the error happened on.
int? lineNumber;
@override
String toString() {
return '(Error message:"$message" filename:"$filename" lineNumber:$lineNumber)';
}
}
/// Options used when running the code generator.
class PigeonOptions {
/// Creates a instance of PigeonOptions
const PigeonOptions({
this.input,
this.dartOut,
this.dartTestOut,
this.objcHeaderOut,
this.objcSourceOut,
this.objcOptions,
this.javaOut,
this.javaOptions,
this.swiftOut,
this.swiftOptions,
this.kotlinOut,
this.kotlinOptions,
this.cppHeaderOut,
this.cppSourceOut,
this.cppOptions,
this.gobjectHeaderOut,
this.gobjectSourceOut,
this.gobjectOptions,
this.dartOptions,
this.copyrightHeader,
this.oneLanguage,
this.astOut,
this.debugGenerators,
this.basePath,
String? dartPackageName,
}) : _dartPackageName = dartPackageName;
/// Path to the file which will be processed.
final String? input;
/// Path to the Dart file that will be generated.
final String? dartOut;
/// Path to the Dart file that will be generated for test support classes.
final String? dartTestOut;
/// Path to the ".h" Objective-C file will be generated.
final String? objcHeaderOut;
/// Path to the ".m" Objective-C file will be generated.
final String? objcSourceOut;
/// Options that control how Objective-C will be generated.
final ObjcOptions? objcOptions;
/// Path to the java file that will be generated.
final String? javaOut;
/// Options that control how Java will be generated.
final JavaOptions? javaOptions;
/// Path to the swift file that will be generated.
final String? swiftOut;
/// Options that control how Swift will be generated.
final SwiftOptions? swiftOptions;
/// Path to the kotlin file that will be generated.
final String? kotlinOut;
/// Options that control how Kotlin will be generated.
final KotlinOptions? kotlinOptions;
/// Path to the ".h" C++ file that will be generated.
final String? cppHeaderOut;
/// Path to the ".cpp" C++ file that will be generated.
final String? cppSourceOut;
/// Options that control how C++ will be generated.
final CppOptions? cppOptions;
/// Path to the ".h" GObject file that will be generated.
final String? gobjectHeaderOut;
/// Path to the ".cc" GObject file that will be generated.
final String? gobjectSourceOut;
/// Options that control how GObject source will be generated.
final GObjectOptions? gobjectOptions;
/// Options that control how Dart will be generated.
final DartOptions? dartOptions;
/// Path to a copyright header that will get prepended to generated code.
final String? copyrightHeader;
/// If Pigeon allows generating code for one language.
final bool? oneLanguage;
/// Path to AST debugging output.
final String? astOut;
/// True means print out line number of generators in comments at newlines.
final bool? debugGenerators;
/// A base path to be prepended to all provided output paths.
final String? basePath;
/// The name of the package the pigeon files will be used in.
final String? _dartPackageName;
/// Creates a [PigeonOptions] from a Map representation where:
/// `x = PigeonOptions.fromMap(x.toMap())`.
static PigeonOptions fromMap(Map<String, Object> map) {
return PigeonOptions(
input: map['input'] as String?,
dartOut: map['dartOut'] as String?,
dartTestOut: map['dartTestOut'] as String?,
objcHeaderOut: map['objcHeaderOut'] as String?,
objcSourceOut: map['objcSourceOut'] as String?,
objcOptions: map.containsKey('objcOptions')
? ObjcOptions.fromMap(map['objcOptions']! as Map<String, Object>)
: null,
javaOut: map['javaOut'] as String?,
javaOptions: map.containsKey('javaOptions')
? JavaOptions.fromMap(map['javaOptions']! as Map<String, Object>)
: null,
swiftOut: map['swiftOut'] as String?,
swiftOptions: map.containsKey('swiftOptions')
? SwiftOptions.fromList(map['swiftOptions']! as Map<String, Object>)
: null,
kotlinOut: map['kotlinOut'] as String?,
kotlinOptions: map.containsKey('kotlinOptions')
? KotlinOptions.fromMap(map['kotlinOptions']! as Map<String, Object>)
: null,
cppHeaderOut: map['cppHeaderOut'] as String?,
cppSourceOut: map['cppSourceOut'] as String?,
cppOptions: map.containsKey('cppOptions')
? CppOptions.fromMap(map['cppOptions']! as Map<String, Object>)
: null,
gobjectHeaderOut: map['gobjectHeaderOut'] as String?,
gobjectSourceOut: map['gobjectSourceOut'] as String?,
gobjectOptions: map.containsKey('gobjectOptions')
? GObjectOptions.fromMap(
map['gobjectOptions']! as Map<String, Object>)
: null,
dartOptions: map.containsKey('dartOptions')
? DartOptions.fromMap(map['dartOptions']! as Map<String, Object>)
: null,
copyrightHeader: map['copyrightHeader'] as String?,
oneLanguage: map['oneLanguage'] as bool?,
astOut: map['astOut'] as String?,
debugGenerators: map['debugGenerators'] as bool?,
basePath: map['basePath'] as String?,
dartPackageName: map['dartPackageName'] as String?,
);
}
/// Converts a [PigeonOptions] to a Map representation where:
/// `x = PigeonOptions.fromMap(x.toMap())`.
Map<String, Object> toMap() {
final Map<String, Object> result = <String, Object>{
if (input != null) 'input': input!,
if (dartOut != null) 'dartOut': dartOut!,
if (dartTestOut != null) 'dartTestOut': dartTestOut!,
if (objcHeaderOut != null) 'objcHeaderOut': objcHeaderOut!,
if (objcSourceOut != null) 'objcSourceOut': objcSourceOut!,
if (objcOptions != null) 'objcOptions': objcOptions!.toMap(),
if (javaOut != null) 'javaOut': javaOut!,
if (javaOptions != null) 'javaOptions': javaOptions!.toMap(),
if (swiftOut != null) 'swiftOut': swiftOut!,
if (swiftOptions != null) 'swiftOptions': swiftOptions!.toMap(),
if (kotlinOut != null) 'kotlinOut': kotlinOut!,
if (kotlinOptions != null) 'kotlinOptions': kotlinOptions!.toMap(),
if (cppHeaderOut != null) 'cppHeaderOut': cppHeaderOut!,
if (cppSourceOut != null) 'cppSourceOut': cppSourceOut!,
if (cppOptions != null) 'cppOptions': cppOptions!.toMap(),
if (gobjectHeaderOut != null) 'gobjectHeaderOut': gobjectHeaderOut!,
if (gobjectSourceOut != null) 'gobjectSourceOut': gobjectSourceOut!,
if (gobjectOptions != null) 'gobjectOptions': gobjectOptions!.toMap(),
if (dartOptions != null) 'dartOptions': dartOptions!.toMap(),
if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!,
if (astOut != null) 'astOut': astOut!,
if (oneLanguage != null) 'oneLanguage': oneLanguage!,
if (debugGenerators != null) 'debugGenerators': debugGenerators!,
if (basePath != null) 'basePath': basePath!,
if (_dartPackageName != null) 'dartPackageName': _dartPackageName,
};
return result;
}
/// Overrides any non-null parameters from [options] into this to make a new
/// [PigeonOptions].
PigeonOptions merge(PigeonOptions options) {
return PigeonOptions.fromMap(mergeMaps(toMap(), options.toMap()));
}
/// Returns provided or deduced package name, throws `Exception` if none found.
String getPackageName() {
final String? name = _dartPackageName ?? deducePackageName(dartOut ?? '');
if (name == null) {
throw Exception(
'Unable to deduce package name, and no package name supplied.\n'
'Add a `dartPackageName` property to your `PigeonOptions` config,\n'
'or add --dartPackageName={name_of_package} to your command line pigeon call.',
);
}
return name;
}
}
/// A collection of an AST represented as a [Root] and [Error]'s.
class ParseResults {
/// Parametric constructor for [ParseResults].
ParseResults({
required this.root,
required this.errors,
required this.pigeonOptions,
});
/// The resulting AST.
final Root root;
/// Errors generated while parsing input.
final List<Error> errors;
/// The Map representation of any [PigeonOptions] specified with
/// [ConfigurePigeon] during parsing.
final Map<String, Object>? pigeonOptions;
}
Iterable<String> _lineReader(String path) sync* {
final String contents = File(path).readAsStringSync();
const LineSplitter lineSplitter = LineSplitter();
final List<String> lines = lineSplitter.convert(contents);
for (final String line in lines) {
yield line;
}
}
IOSink? _openSink(String? output, {String basePath = ''}) {
if (output == null) {
return null;
}
IOSink sink;
File file;
if (output == 'stdout') {
sink = stdout;
} else {
file = File(path.posix.join(basePath, output));
file.createSync(recursive: true);
sink = file.openWrite();
}
return sink;
}
/// An adapter that will call a generator to write code to a sink
/// based on the contents of [PigeonOptions].
abstract class GeneratorAdapter {
/// Constructor for [GeneratorAdapter]
GeneratorAdapter(this.fileTypeList);
/// A list of file types the generator should create.
List<FileType> fileTypeList;
/// Returns an [IOSink] instance to be written to
/// if the [GeneratorAdapter] should generate.
///
/// If it returns `null`, the [GeneratorAdapter] will be skipped.
IOSink? shouldGenerate(PigeonOptions options, FileType fileType);
/// Write the generated code described in [root] to [sink] using the [options].
void generate(
StringSink sink, PigeonOptions options, Root root, FileType fileType);
/// Generates errors that would only be appropriate for this [GeneratorAdapter].
///
/// For example, if a certain feature isn't implemented in a [GeneratorAdapter] yet.
List<Error> validate(PigeonOptions options, Root root);
}
DartOptions _dartOptionsWithCopyrightHeader(
DartOptions? dartOptions,
String? copyrightHeader, {
String? dartOutPath,
String? testOutPath,
String basePath = '',
}) {
dartOptions = dartOptions ?? const DartOptions();
return dartOptions.merge(DartOptions(
sourceOutPath: dartOutPath,
testOutPath: testOutPath,
copyrightHeader: copyrightHeader != null
? _lineReader(path.posix.join(basePath, copyrightHeader))
: null,
));
}
void _errorOnEventChannelApi(List<Error> errors, String generator, Root root) {
if (root.containsEventChannel) {
errors.add(Error(message: '$generator does not support event channels'));
}
}
void _errorOnSealedClass(List<Error> errors, String generator, Root root) {
if (root.classes.any(
(Class element) => element.isSealed,
)) {
errors.add(Error(message: '$generator does not support sealed classes'));
}
}
void _errorOnInheritedClass(List<Error> errors, String generator, Root root) {
if (root.classes.any(
(Class element) => element.superClass != null,
)) {
errors.add(
Error(message: '$generator does not support inheritance in classes'));
}
}
/// A [GeneratorAdapter] that generates the AST.
class AstGeneratorAdapter implements GeneratorAdapter {
/// Constructor for [AstGeneratorAdapter].
AstGeneratorAdapter();
@override
List<FileType> fileTypeList = const <FileType>[FileType.na];
@override
void generate(
StringSink sink, PigeonOptions options, Root root, FileType fileType) {
generateAst(root, sink);
}
@override
IOSink? shouldGenerate(PigeonOptions options, FileType _) =>
_openSink(options.astOut, basePath: options.basePath ?? '');
@override
List<Error> validate(PigeonOptions options, Root root) => <Error>[];
}
/// A [GeneratorAdapter] that generates Dart source code.
class DartGeneratorAdapter implements GeneratorAdapter {
/// Constructor for [DartGeneratorAdapter].
DartGeneratorAdapter();
/// A string representing the name of the language being generated.
String languageString = 'Dart';
@override
List<FileType> fileTypeList = const <FileType>[FileType.na];
@override
void generate(
StringSink sink, PigeonOptions options, Root root, FileType fileType) {
final DartOptions dartOptionsWithHeader = _dartOptionsWithCopyrightHeader(
options.dartOptions,
options.copyrightHeader,
testOutPath: options.dartTestOut,
basePath: options.basePath ?? '',
);
const DartGenerator generator = DartGenerator();
generator.generate(
dartOptionsWithHeader,
root,
sink,
dartPackageName: options.getPackageName(),
);
}
@override
IOSink? shouldGenerate(PigeonOptions options, FileType _) =>
_openSink(options.dartOut, basePath: options.basePath ?? '');
@override
List<Error> validate(PigeonOptions options, Root root) => <Error>[];
}
/// A [GeneratorAdapter] that generates Dart test source code.
class DartTestGeneratorAdapter implements GeneratorAdapter {
/// Constructor for [DartTestGeneratorAdapter].
DartTestGeneratorAdapter();
@override
List<FileType> fileTypeList = const <FileType>[FileType.na];
@override
void generate(
StringSink sink, PigeonOptions options, Root root, FileType fileType) {
final DartOptions dartOptionsWithHeader = _dartOptionsWithCopyrightHeader(
options.dartOptions,
options.copyrightHeader,
dartOutPath: options.dartOut,
testOutPath: options.dartTestOut,
basePath: options.basePath ?? '',
);
const DartGenerator testGenerator = DartGenerator();
// The test code needs the actual package name of the Dart output, even if
// the package name has been overridden for other uses.
final String outputPackageName =
deducePackageName(options.dartOut ?? '') ?? options.getPackageName();
testGenerator.generateTest(
dartOptionsWithHeader,
root,
sink,
dartPackageName: options.getPackageName(),
dartOutputPackageName: outputPackageName,
);
}
@override
IOSink? shouldGenerate(PigeonOptions options, FileType _) {
if (options.dartTestOut != null) {
return _openSink(options.dartTestOut, basePath: options.basePath ?? '');
} else {
return null;
}
}
@override
List<Error> validate(PigeonOptions options, Root root) => <Error>[];
}
/// A [GeneratorAdapter] that generates Objective-C code.
class ObjcGeneratorAdapter implements GeneratorAdapter {
/// Constructor for [ObjcGeneratorAdapter].
ObjcGeneratorAdapter(
{this.fileTypeList = const <FileType>[FileType.header, FileType.source]});
/// A string representing the name of the language being generated.
String languageString = 'Objective-C';
@override
List<FileType> fileTypeList;
@override
void generate(
StringSink sink, PigeonOptions options, Root root, FileType fileType) {
final ObjcOptions objcOptions = options.objcOptions ?? const ObjcOptions();
final ObjcOptions objcOptionsWithHeader = objcOptions.merge(ObjcOptions(
fileSpecificClassNameComponent: options.objcSourceOut
?.split('/')
.lastOrNull
?.split('.')
.firstOrNull ??
'',
copyrightHeader: options.copyrightHeader != null
? _lineReader(
path.posix.join(options.basePath ?? '', options.copyrightHeader))
: null,
));
final OutputFileOptions<ObjcOptions> outputFileOptions =
OutputFileOptions<ObjcOptions>(
fileType: fileType, languageOptions: objcOptionsWithHeader);
const ObjcGenerator generator = ObjcGenerator();
generator.generate(
outputFileOptions,
root,
sink,
dartPackageName: options.getPackageName(),
);
}
@override
IOSink? shouldGenerate(PigeonOptions options, FileType fileType) {
if (fileType == FileType.source) {
return _openSink(options.objcSourceOut, basePath: options.basePath ?? '');
} else {
return _openSink(options.objcHeaderOut, basePath: options.basePath ?? '');
}
}
@override
List<Error> validate(PigeonOptions options, Root root) {
final List<Error> errors = <Error>[];
_errorOnEventChannelApi(errors, languageString, root);
_errorOnSealedClass(errors, languageString, root);
_errorOnInheritedClass(errors, languageString, root);
return errors;
}
}
/// A [GeneratorAdapter] that generates Java source code.
class JavaGeneratorAdapter implements GeneratorAdapter {
/// Constructor for [JavaGeneratorAdapter].
JavaGeneratorAdapter();
/// A string representing the name of the language being generated.
String languageString = 'Java';
@override
List<FileType> fileTypeList = const <FileType>[FileType.na];
@override
void generate(
StringSink sink, PigeonOptions options, Root root, FileType fileType) {
JavaOptions javaOptions = options.javaOptions ?? const JavaOptions();
javaOptions = javaOptions.merge(JavaOptions(
className: javaOptions.className ??
path.basenameWithoutExtension(options.javaOut!),
copyrightHeader: options.copyrightHeader != null
? _lineReader(
path.posix.join(options.basePath ?? '', options.copyrightHeader))
: null,
));
const JavaGenerator generator = JavaGenerator();
generator.generate(
javaOptions,
root,
sink,
dartPackageName: options.getPackageName(),
);
}
@override
IOSink? shouldGenerate(PigeonOptions options, FileType _) =>
_openSink(options.javaOut, basePath: options.basePath ?? '');
@override
List<Error> validate(PigeonOptions options, Root root) {
final List<Error> errors = <Error>[];
_errorOnEventChannelApi(errors, languageString, root);
_errorOnSealedClass(errors, languageString, root);
_errorOnInheritedClass(errors, languageString, root);
return errors;
}
}
/// A [GeneratorAdapter] that generates Swift source code.
class SwiftGeneratorAdapter implements GeneratorAdapter {
/// Constructor for [SwiftGeneratorAdapter].
SwiftGeneratorAdapter();
/// A string representing the name of the language being generated.
String languageString = 'Swift';
@override
List<FileType> fileTypeList = const <FileType>[FileType.na];
@override
void generate(
StringSink sink, PigeonOptions options, Root root, FileType fileType) {
SwiftOptions swiftOptions = options.swiftOptions ?? const SwiftOptions();
swiftOptions = swiftOptions.merge(SwiftOptions(
fileSpecificClassNameComponent:
options.swiftOut?.split('/').lastOrNull?.split('.').firstOrNull ?? '',
copyrightHeader: options.copyrightHeader != null
? _lineReader(
path.posix.join(options.basePath ?? '', options.copyrightHeader))
: null,
errorClassName: swiftOptions.errorClassName,
includeErrorClass: swiftOptions.includeErrorClass,
));
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: options.getPackageName(),
);
}
@override
IOSink? shouldGenerate(PigeonOptions options, FileType _) =>
_openSink(options.swiftOut, basePath: options.basePath ?? '');
@override
List<Error> validate(PigeonOptions options, Root root) => <Error>[];
}
/// A [GeneratorAdapter] that generates C++ source code.
class CppGeneratorAdapter implements GeneratorAdapter {
/// Constructor for [CppGeneratorAdapter].
CppGeneratorAdapter(
{this.fileTypeList = const <FileType>[FileType.header, FileType.source]});
/// A string representing the name of the language being generated.
String languageString = 'C++';
@override
List<FileType> fileTypeList;
@override
void generate(
StringSink sink, PigeonOptions options, Root root, FileType fileType) {
final CppOptions cppOptions = options.cppOptions ?? const CppOptions();
final CppOptions cppOptionsWithHeader = cppOptions.merge(CppOptions(
copyrightHeader: options.copyrightHeader != null
? _lineReader(
path.posix.join(options.basePath ?? '', options.copyrightHeader))
: null,
));
final OutputFileOptions<CppOptions> outputFileOptions =
OutputFileOptions<CppOptions>(
fileType: fileType, languageOptions: cppOptionsWithHeader);
const CppGenerator generator = CppGenerator();
generator.generate(
outputFileOptions,
root,
sink,
dartPackageName: options.getPackageName(),
);
}
@override
IOSink? shouldGenerate(PigeonOptions options, FileType fileType) {
if (fileType == FileType.source) {
return _openSink(options.cppSourceOut, basePath: options.basePath ?? '');
} else {
return _openSink(options.cppHeaderOut, basePath: options.basePath ?? '');
}
}
@override
List<Error> validate(PigeonOptions options, Root root) {
final List<Error> errors = <Error>[];
_errorOnEventChannelApi(errors, languageString, root);
_errorOnSealedClass(errors, languageString, root);
_errorOnInheritedClass(errors, languageString, root);
return errors;
}
}
/// A [GeneratorAdapter] that generates GObject source code.
class GObjectGeneratorAdapter implements GeneratorAdapter {
/// Constructor for [GObjectGeneratorAdapter].
GObjectGeneratorAdapter(
{this.fileTypeList = const <FileType>[FileType.header, FileType.source]});
/// A string representing the name of the language being generated.
String languageString = 'GObject';
@override
List<FileType> fileTypeList;
@override
void generate(
StringSink sink, PigeonOptions options, Root root, FileType fileType) {
final GObjectOptions gobjectOptions =
options.gobjectOptions ?? const GObjectOptions();
final GObjectOptions gobjectOptionsWithHeader =
gobjectOptions.merge(GObjectOptions(
copyrightHeader: options.copyrightHeader != null
? _lineReader(
path.posix.join(options.basePath ?? '', options.copyrightHeader))
: null,
));
final OutputFileOptions<GObjectOptions> outputFileOptions =
OutputFileOptions<GObjectOptions>(
fileType: fileType, languageOptions: gobjectOptionsWithHeader);
const GObjectGenerator generator = GObjectGenerator();
generator.generate(
outputFileOptions,
root,
sink,
dartPackageName: options.getPackageName(),
);
}
@override
IOSink? shouldGenerate(PigeonOptions options, FileType fileType) {
if (fileType == FileType.source) {
return _openSink(options.gobjectSourceOut,
basePath: options.basePath ?? '');
} else {
return _openSink(options.gobjectHeaderOut,
basePath: options.basePath ?? '');
}
}
@override
List<Error> validate(PigeonOptions options, Root root) {
final List<Error> errors = <Error>[];
// TODO(tarrinneal): Remove once overflow class is added to gobject generator.
// https://github.com/flutter/flutter/issues/152916
if (root.classes.length + root.enums.length > totalCustomCodecKeysAllowed) {
errors.add(Error(
message:
'GObject generator does not yet support more than $totalCustomCodecKeysAllowed custom types.'));
}
_errorOnEventChannelApi(errors, languageString, root);
_errorOnSealedClass(errors, languageString, root);
_errorOnInheritedClass(errors, languageString, root);
return errors;
}
}
/// A [GeneratorAdapter] that generates Kotlin source code.
class KotlinGeneratorAdapter implements GeneratorAdapter {
/// Constructor for [KotlinGeneratorAdapter].
KotlinGeneratorAdapter({this.fileTypeList = const <FileType>[FileType.na]});
@override
List<FileType> fileTypeList;
@override
void generate(
StringSink sink, PigeonOptions options, Root root, FileType fileType) {
KotlinOptions kotlinOptions =
options.kotlinOptions ?? const KotlinOptions();
kotlinOptions = kotlinOptions.merge(KotlinOptions(
errorClassName: kotlinOptions.errorClassName ?? 'FlutterError',
includeErrorClass: kotlinOptions.includeErrorClass,
fileSpecificClassNameComponent:
options.kotlinOut?.split('/').lastOrNull?.split('.').firstOrNull ??
'',
copyrightHeader: options.copyrightHeader != null
? _lineReader(
path.posix.join(options.basePath ?? '', options.copyrightHeader))
: null,
));
const KotlinGenerator generator = KotlinGenerator();
generator.generate(
kotlinOptions,
root,
sink,
dartPackageName: options.getPackageName(),
);
}
@override
IOSink? shouldGenerate(PigeonOptions options, FileType _) =>
_openSink(options.kotlinOut, basePath: options.basePath ?? '');
@override
List<Error> validate(PigeonOptions options, Root root) => <Error>[];
}
dart_ast.Annotation? _findMetadata(
dart_ast.NodeList<dart_ast.Annotation> metadata, String query) {
final Iterable<dart_ast.Annotation> annotations = metadata
.where((dart_ast.Annotation element) => element.name.name == query);
return annotations.isEmpty ? null : annotations.first;
}
bool _hasMetadata(
dart_ast.NodeList<dart_ast.Annotation> metadata, String query) {
return _findMetadata(metadata, query) != null;
}
extension _ObjectAs on Object {
/// A convenience for chaining calls with casts.
T? asNullable<T>() => this as T?;
}