aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/rules/objc/ObjcRuleClasses.java
blob: cb33acb6ec24ee8526af1e996f12f64bc765f451 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.rules.objc;

import static com.google.devtools.build.lib.packages.Attribute.ANY_RULE;
import static com.google.devtools.build.lib.packages.Attribute.ConfigurationTransition.HOST;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL;
import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST;
import static com.google.devtools.build.lib.syntax.Type.BOOLEAN;
import static com.google.devtools.build.lib.syntax.Type.STRING;
import static com.google.devtools.build.lib.syntax.Type.STRING_LIST;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.BaseRuleClasses;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.RuleDefinition;
import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.actions.ExecutionRequirements;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.Attribute.LateBoundLabel;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.RuleClass.Builder;
import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType;
import com.google.devtools.build.lib.rules.apple.AppleConfiguration;
import com.google.devtools.build.lib.rules.apple.AppleToolchain;
import com.google.devtools.build.lib.rules.apple.AppleToolchain.RequiresXcodeConfigRule;
import com.google.devtools.build.lib.rules.apple.Platform;
import com.google.devtools.build.lib.rules.cpp.CppConfiguration;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.util.FileType;
import com.google.devtools.build.lib.util.FileTypeSet;

/**
 * Shared rule classes and associated utility code for Objective-C rules.
 */
public class ObjcRuleClasses {
  static final String CLANG = "clang";
  static final String CLANG_PLUSPLUS = "clang++";
  static final String SWIFT = "swift";
  static final String LIBTOOL = "libtool";
  static final String DSYMUTIL = "dsymutil";
  static final String LIPO = "lipo";
  static final String STRIP = "strip";

  private ObjcRuleClasses() {
    throw new UnsupportedOperationException("static-only");
  }

  public static IntermediateArtifacts intermediateArtifacts(RuleContext ruleContext) {
    return new IntermediateArtifacts(ruleContext, /*archiveFileNameSuffix=*/ "");
  }

  /**
   * Returns a {@link IntermediateArtifacts} to be used to compile and link the ObjC source files
   * generated by J2ObjC.
   */
  static IntermediateArtifacts j2objcIntermediateArtifacts(RuleContext ruleContext) {
    // We need to append "_j2objc" to the name of the generated archive file to distinguish it from
    // the C/C++ archive file created by proto_library targets with attribute cc_api_version
    // specified.
    return new IntermediateArtifacts(
        ruleContext,
        /*archiveFileNameSuffix=*/"_j2objc");
  }

  /**
   * Returns a {@link J2ObjcMappingFileProvider} containing J2ObjC mapping files from rules
   * that can be reached transitively through the "deps" attribute.
   *
   * @param ruleContext the rule context of the current rule
   * @return a {@link J2ObjcMappingFileProvider} containing J2ObjC mapping files information from
   *     the transitive closure.
   */
  public static J2ObjcMappingFileProvider j2ObjcMappingFileProvider(RuleContext ruleContext) {
    J2ObjcMappingFileProvider.Builder builder = new J2ObjcMappingFileProvider.Builder();
    Iterable<J2ObjcMappingFileProvider> providers =
        ruleContext.getPrerequisites("deps", Mode.TARGET, J2ObjcMappingFileProvider.class);
    for (J2ObjcMappingFileProvider provider : providers) {
      builder.addTransitive(provider);
    }

    return builder.build();
  }

  public static Artifact artifactByAppendingToBaseName(RuleContext context, String suffix) {
    return context.getPackageRelativeArtifact(
        context.getLabel().getName() + suffix, context.getBinOrGenfilesDirectory());
  }

  public static ObjcConfiguration objcConfiguration(RuleContext ruleContext) {
    return ruleContext.getFragment(ObjcConfiguration.class);
  }

  /**
   * Returns true if the source file can be instrumented for coverage.
   */
  public static boolean isInstrumentable(Artifact sourceArtifact) {
    return !ASSEMBLY_SOURCES.matches(sourceArtifact.getFilename());
  }

  @VisibleForTesting
  static final Iterable<SdkFramework> AUTOMATIC_SDK_FRAMEWORKS = ImmutableList.of(
      new SdkFramework("Foundation"), new SdkFramework("UIKit"));

  /**
   * Label of a filegroup that contains all crosstool and grte files for all configurations,
   * as specified on the command-line.
   *
   * <p> Since this is the loading-phase default for the :cc_toolchain attribute of rules
   * using the crosstool, it must contain in its transitive closure the computer value
   * of that attribute under the default configuration.
   */
  public static final String CROSSTOOL_LABEL = "//tools/defaults:crosstool";

  /**
   * Late-bound attribute giving the CcToolchain for CROSSTOOL_LABEL.
   *
   * TODO(cpeyser): Use AppleCcToolchain instead of CcToolchain once released.
   */
  public static final LateBoundLabel<BuildConfiguration> APPLE_TOOLCHAIN =
      new LateBoundLabel<BuildConfiguration>(CROSSTOOL_LABEL, CppConfiguration.class) {
        @Override
        public Label resolve(
            Rule rule, AttributeMap attributes, BuildConfiguration configuration) {
          return configuration.getFragment(CppConfiguration.class).getCcToolchainRuleLabel();
        }
      };

  /**
   * A null value for the lipo context collector.  Objc builds do not use a lipo context collector.
   */
  // TODO(b/28084560): Allow :lipo_context_collector not to be set instead of having a null
  // instance.
  public static final LateBoundLabel<BuildConfiguration> NULL_LIPO_CONTEXT_COLLECTOR =
      new LateBoundLabel<BuildConfiguration>() {
        @Override
        public Label resolve(
            Rule rule, AttributeMap attributes, BuildConfiguration configuration) {
          return null;
        }
      };
      
      
  /**
   * Creates a new spawn action builder with apple environment variables set that are typically
   * needed by the apple toolchain. This should be used to start to build spawn actions that, in
   * order to run, require both a darwin architecture and a collection of environment variables
   * which contain information about the target and host architectures. This implicitly
   * assumes that this action is targeting ios platforms, and that
   * {@link AppleConfiguration#getIosCpu()} is the source of truth for their target architecture.
   * 
   * @deprecated use {@link #spawnAppleEnvActionBuilder(RuleContext, Platform)} instead
   */
  // TODO(cparsons): Refactor callers to use the alternate method. Callers should be aware
  // of their effective Platform.
  @Deprecated
  static SpawnAction.Builder spawnAppleEnvActionBuilder(RuleContext ruleContext) {
    AppleConfiguration appleConfiguration = ruleContext.getFragment(AppleConfiguration.class);

    return spawnAppleEnvActionBuilder(ruleContext,
        Platform.forIosArch(appleConfiguration.getIosCpu()));
  }

  /**
   * Creates a new spawn action builder with apple environment variables set that are typically
   * needed by the apple toolchain. This should be used to start to build spawn actions that, in
   * order to run, require both a darwin architecture and a collection of environment variables
   * which contain information about the target and host architectures.
   */
  static SpawnAction.Builder spawnAppleEnvActionBuilder(RuleContext ruleContext,
      Platform targetPlatform) {
    AppleConfiguration appleConfiguration = ruleContext.getFragment(AppleConfiguration.class);

    ImmutableMap.Builder<String, String> envBuilder = ImmutableMap.<String, String>builder()
        .putAll(appleConfiguration.getTargetAppleEnvironment(targetPlatform))
        .putAll(appleConfiguration.getAppleHostSystemEnv());

    return spawnOnDarwinActionBuilder()
        .setEnvironment(envBuilder.build());
  }

  /**
   * Creates a new spawn action builder that requires a darwin architecture to run.
   */
  static SpawnAction.Builder spawnOnDarwinActionBuilder() {
    return new SpawnAction.Builder()
        .setExecutionInfo(ImmutableMap.of(ExecutionRequirements.REQUIRES_DARWIN, ""));
  }

  /**
   * Creates a new spawn action builder that requires a darwin architecture to run and calls bash
   * to execute cmd.
   * Once we have a fix for b/21874752  we should be able to call setShellCommand(cmd)
   * directly, but right now we don't have a buildhelpers package on Macs so we must specify
   * the path to /bin/bash explicitly.
   */
  static SpawnAction.Builder spawnBashOnDarwinActionBuilder(String cmd) {
    return spawnOnDarwinActionBuilder()
        .setShellCommand(ImmutableList.of("/bin/bash", "-c", cmd));
  }

  /**
   * Creates a new configured target builder with the given {@code filesToBuild}, which are also
   * used as runfiles.
   *
   * @param ruleContext the current rule context
   * @param filesToBuild files to build for this target. These also become the data runfiles
   */
  static RuleConfiguredTargetBuilder ruleConfiguredTarget(RuleContext ruleContext,
      NestedSet<Artifact> filesToBuild) {
    RunfilesProvider runfilesProvider = RunfilesProvider.withData(
        new Runfiles.Builder(
            ruleContext.getWorkspaceName(),
            ruleContext.getConfiguration().legacyExternalRunfiles())
            .addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES).build(),
        new Runfiles.Builder(
            ruleContext.getWorkspaceName(),
            ruleContext.getConfiguration().legacyExternalRunfiles())
            .addTransitiveArtifacts(filesToBuild).build());

    return new RuleConfiguredTargetBuilder(ruleContext)
        .setFilesToBuild(filesToBuild)
        .add(RunfilesProvider.class, runfilesProvider);
  }

  /**
   * Attributes for {@code objc_*} rules that have compiler options.
   */
  public static class CoptsRule implements RuleDefinition {
    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment environment) {
      return builder
          /* <!-- #BLAZE_RULE($objc_opts_rule).ATTRIBUTE(copts) -->
          Extra flags to pass to the compiler.
          Subject to <a href="make-variables.html">"Make variable"</a> substitution and
          <a href="common-definitions.html#sh-tokenization">Bourne shell tokenization</a>.
          These flags will only apply to this target, and not those upon which
          it depends, or those which depend on it.
          <p>
          Note that for the generated Xcode project, directory paths specified using "-I" flags in
          copts are parsed out, prepended with "$(WORKSPACE_ROOT)/" if they are relative paths, and
          added to the header search paths for the associated Xcode target.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("copts", STRING_LIST))
          .build();
    }

    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_opts_rule")
          .type(RuleClassType.ABSTRACT)
          .build();
    }
  }

  /**
   * Attributes for {@code objc_*} rules that can link in SDK frameworks.
   */
  public static class SdkFrameworksDependerRule implements RuleDefinition {
    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment environment) {
      return builder
          /* <!-- #BLAZE_RULE($objc_sdk_frameworks_depender_rule).ATTRIBUTE(sdk_frameworks) -->
          Names of SDK frameworks to link with.
          For instance, "XCTest" or "Cocoa". "UIKit" and "Foundation" are always
          included and do not mean anything if you include them.

          <p>When linking a library, only those frameworks named in that library's
          sdk_frameworks attribute are linked in. When linking a binary, all
          SDK frameworks named in that binary's transitive dependency graph are
          used.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("sdk_frameworks", STRING_LIST))
          /* <!-- #BLAZE_RULE($objc_sdk_frameworks_depender_rule).ATTRIBUTE(weak_sdk_frameworks) -->
          Names of SDK frameworks to weakly link with. For instance,
          "MediaAccessibility".

          In difference to regularly linked SDK frameworks, symbols
          from weakly linked frameworks do not cause an error if they
          are not present at runtime.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("weak_sdk_frameworks", STRING_LIST))
          /* <!-- #BLAZE_RULE($objc_sdk_frameworks_depender_rule).ATTRIBUTE(sdk_dylibs) -->
          Names of SDK .dylib libraries to link with. For instance, "libz" or
          "libarchive".

          "libc++" is included automatically if the binary has any C++ or
          Objective-C++ sources in its dependency tree. When linking a binary,
          all libraries named in that binary's transitive dependency graph are
          used.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("sdk_dylibs", STRING_LIST))
          .build();
    }

    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_sdk_frameworks_depender_rule")
          .type(RuleClassType.ABSTRACT)
          .build();
    }
  }

  /**
   * Iff a file matches this type, it is considered to use C++.
   */
  static final FileType CPP_SOURCES = FileType.of(".cc", ".cpp", ".mm", ".cxx", ".C");

  static final FileType NON_CPP_SOURCES = FileType.of(".m", ".c");

  static final FileType ASSEMBLY_SOURCES = FileType.of(".s", ".S", ".asm");

  static final FileType OBJECT_FILE_SOURCES = FileType.of(".o");
  
  static final FileType SWIFT_SOURCES = FileType.of(".swift");

  /**
   * Header files, which are not compiled directly, but may be included/imported from source files.
   */
  static final FileType HEADERS = FileType.of(".h", ".inc");

  /**
   * Files allowed in the srcs attribute. This includes private headers.
   */
  static final FileTypeSet SRCS_TYPE =
      FileTypeSet.of(
          NON_CPP_SOURCES,
          CPP_SOURCES,
          ASSEMBLY_SOURCES,
          OBJECT_FILE_SOURCES,
          SWIFT_SOURCES,
          HEADERS);

  /**
   * Files that should actually be compiled.
   */
  static final FileTypeSet COMPILABLE_SRCS_TYPE = FileTypeSet.of(NON_CPP_SOURCES, CPP_SOURCES,
      ASSEMBLY_SOURCES, SWIFT_SOURCES);

  /**
   * Files that are already compiled.
   */
  static final FileTypeSet PRECOMPILED_SRCS_TYPE = FileTypeSet.of(OBJECT_FILE_SOURCES);
  
  static final FileTypeSet NON_ARC_SRCS_TYPE = FileTypeSet.of(FileType.of(".m", ".mm"));

  static final FileTypeSet PLIST_TYPE = FileTypeSet.of(FileType.of(".plist"));

  static final FileType STORYBOARD_TYPE = FileType.of(".storyboard");

  static final FileType XIB_TYPE = FileType.of(".xib");

  // TODO(bazel-team): Restrict this to actual header files only.
  static final FileTypeSet HDRS_TYPE = FileTypeSet.ANY_FILE;

  static final FileTypeSet ENTITLEMENTS_TYPE =
      FileTypeSet.of(FileType.of(".entitlements", ".plist"));

  static final FileTypeSet STRINGS_TYPE = FileTypeSet.of(FileType.of(".strings"));

  /**
   * Coverage note files which contain information to reconstruct the basic block graphs and assign
   * source line numbers to blocks.
   */
  static final FileType COVERAGE_NOTES = FileType.of(".gcno");

  /**
   * Common attributes for {@code objc_*} rules that allow the definition of resources such as
   * storyboards. These resources are used during compilation of the declaring rule as well as when
   * bundling a dependent bundle (application, extension, etc.).
   */
  public static class ResourcesRule implements RuleDefinition {
    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          /* <!-- #BLAZE_RULE($objc_resources_rule).ATTRIBUTE(strings) -->
          Files which are plists of strings, often localizable.

          These files are converted to binary plists (if they are not already)
          and placed in the bundle root of the final package. If this file's
          immediate containing directory is named *.lproj (e.g. en.lproj,
          Base.lproj), it will be placed under a directory of that name in the
          final bundle. This allows for localizable strings.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("strings", LABEL_LIST)
              .allowedFileTypes(STRINGS_TYPE)
              .direct_compile_time_input())
          /* <!-- #BLAZE_RULE($objc_resources_rule).ATTRIBUTE(xibs) -->
          Files which are .xib resources, possibly localizable.

          These files are compiled to .nib files and placed the bundle root of
          the final package. If this file's immediate containing directory is
          named *.lproj (e.g. en.lproj, Base.lproj), it will be placed under a
          directory of that name in the final bundle. This allows for
          localizable UI.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("xibs", LABEL_LIST)
              .direct_compile_time_input()
              .allowedFileTypes(XIB_TYPE))
          /* <!-- #BLAZE_RULE($objc_resources_rule).ATTRIBUTE(storyboards) -->
          Files which are .storyboard resources, possibly localizable.

          These files are compiled to .storyboardc directories, which are
          placed in the bundle root of the final package. If the storyboards's
          immediate containing directory is named *.lproj (e.g. en.lproj,
          Base.lproj), it will be placed under a directory of that name in the
          final bundle. This allows for localizable UI.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("storyboards", LABEL_LIST)
              .allowedFileTypes(STORYBOARD_TYPE))
          /* <!-- #BLAZE_RULE($objc_resources_rule).ATTRIBUTE(resources) -->
          Files to include in the final application bundle.

          They are not processed or compiled in any way besides the processing
          done by the rules that actually generate them. These files are placed
          in the root of the bundle (e.g. Payload/foo.app/...) in most cases.
          However, if they appear to be localized (i.e. are contained in a
          directory called *.lproj), they will be placed in a directory of the
          same name in the app bundle.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("resources", LABEL_LIST).legacyAllowAnyFileType().direct_compile_time_input())
          /* <!-- #BLAZE_RULE($objc_resources_rule).ATTRIBUTE(structured_resources) -->
          Files to include in the final application bundle.

          They are not processed or compiled in any way besides the processing
          done by the rules that actually generate them. In differences to
          <code>resources</code> these files are placed in the bundle root in
          the same structure passed to this argument, so
          <code>["res/foo.png"]</code> will end up in
          <code>Payload/foo.app/res/foo.png</code>.
          <p>Note that in the generated XCode project file, all files in the top directory of
          the specified files will be included in the Xcode-generated app bundle. So
          specifying <code>["res/foo.png"]</code> will lead to the inclusion of all files in
          directory <code>res</code>.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("structured_resources", LABEL_LIST)
              .legacyAllowAnyFileType()
              .direct_compile_time_input())
          /* <!-- #BLAZE_RULE($objc_resources_rule).ATTRIBUTE(datamodels) -->
          Files that comprise the data models of the final linked binary.

          Each file must have a containing directory named *.xcdatamodel, which
          is usually contained by another *.xcdatamodeld (note the added d)
          directory.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("datamodels", LABEL_LIST).legacyAllowAnyFileType()
              .direct_compile_time_input())
          /* <!-- #BLAZE_RULE($objc_resources_rule).ATTRIBUTE(asset_catalogs) -->
          Files that comprise the asset catalogs of the final linked binary.

          Each file must have a containing directory named *.xcassets. This
          containing directory becomes the root of one of the asset catalogs
          linked with any binary that depends directly or indirectly on this
          target.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("asset_catalogs", LABEL_LIST).legacyAllowAnyFileType()
              .direct_compile_time_input())
          /* <!-- #BLAZE_RULE($objc_resources_rule).ATTRIBUTE(bundles) -->
          The list of bundle targets that this target requires to be included
          in the final bundle.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("bundles", LABEL_LIST)
              .direct_compile_time_input()
              .allowedRuleClasses("objc_bundle", "objc_bundle_library")
              .allowedFileTypes())
          .build();
    }
    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_resources_rule")
          .type(RuleClassType.ABSTRACT)
          .ancestors(ResourceToolsRule.class, XcrunRule.class)
          .build();
    }
  }

  /**
   * Common attributes for {@code objc_*} rules that process resources (by defining or consuming
   * them).
   */
  public static class ResourceToolsRule implements RuleDefinition {
    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          .add(attr("$plmerge", LABEL).cfg(HOST).exec()
              .value(env.getToolsLabel("//tools/objc:plmerge")))
          .add(attr("$actoolwrapper", LABEL).cfg(HOST).exec()
              .value(env.getToolsLabel("//tools/objc:actoolwrapper")))
          .add(attr("$ibtoolwrapper", LABEL).cfg(HOST).exec()
              .value(env.getToolsLabel("//tools/objc:ibtoolwrapper")))
          .build();
    }
    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_resource_tools_rule")
          .type(RuleClassType.ABSTRACT)
          .build();
    }
  }

  /**
   * Common attributes for {@code objc_*} rules that export an xcode project.
   */
  public static class XcodegenRule implements RuleDefinition {
    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          .add(attr("$xcodegen", LABEL).cfg(HOST).exec()
              .value(env.getToolsLabel("//tools/objc:xcodegen")))
          .add(attr("$dummy_source", LABEL)
              .value(env.getToolsLabel("//tools/objc:objc_dummy.mm")))
          .build();
    }
    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_xcodegen_rule")
          .type(RuleClassType.ABSTRACT)
          .build();
    }
  }

  /**
   * Common attributes for {@code objc_*} rules that depend on a crosstool.
   */
  public static class CrosstoolRule implements RuleDefinition {

    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          .add(attr(":cc_toolchain", LABEL).value(APPLE_TOOLCHAIN))
          .add(
              attr(":lipo_context_collector", LABEL)
                  .value(NULL_LIPO_CONTEXT_COLLECTOR)
                  .skipPrereqValidatorCheck())
          .build();
    }

    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_crosstool_rule")
          .type(RuleClassType.ABSTRACT)
          .build();
    }
  }

  /**
   * Common attributes for {@code objc_*} rules that can be input to compilation (i.e. can be
   * dependencies of other compiling rules).
   */
  public static class CompileDependencyRule implements RuleDefinition {
    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          /* <!-- #BLAZE_RULE($objc_compile_dependency_rule).ATTRIBUTE(hdrs) -->
          The list of C, C++, Objective-C, and Objective-C++ files that are
          included as headers by source files in this rule or by users of this
          library. These will be compiled separately from the source if modules
          are enabled.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("hdrs", LABEL_LIST)
              .direct_compile_time_input()
              .allowedFileTypes(HDRS_TYPE))
          /* <!-- #BLAZE_RULE($objc_compile_dependency_rule).ATTRIBUTE(textual_hdrs) -->
          The list of C, C++, Objective-C, and Objective-C++ files that are
          included as headers by source files in this rule or by users of this
          library. Unlike hdrs, these will not be compiled separately from the
          sources.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("textual_hdrs", LABEL_LIST)
              .direct_compile_time_input()
              .allowedFileTypes(HDRS_TYPE))
          /* <!-- #BLAZE_RULE($objc_compile_dependency_rule).ATTRIBUTE(bridging_header) -->
          A header defining the Objective-C interfaces to be exposed in Swift.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("bridging_header", BuildType.LABEL)
              .direct_compile_time_input()
              .allowedFileTypes(HDRS_TYPE))
          /* <!-- #BLAZE_RULE($objc_compile_dependency_rule).ATTRIBUTE(includes) -->
          List of <code>#include/#import</code> search paths to add to this target
          and all depending targets.

          This is to support third party and open-sourced libraries that do not
          specify the entire workspace path in their
          <code>#import/#include</code> statements.
          <p>
          The paths are interpreted relative to the package directory, and the
          genfiles and bin roots (e.g. <code>blaze-genfiles/pkg/includedir</code>
          and <code>blaze-out/pkg/includedir</code>) are included in addition to the
          actual client root.
          <p>
          Unlike <a href="#objc_library.copts">COPTS</a>, these flags are added for this rule
          and every rule that depends on it. (Note: not the rules it depends upon!) Be
          very careful, since this may have far-reaching effects.  When in doubt, add
          "-I" flags to <a href="#objc_library.copts">COPTS</a> instead.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("includes", Type.STRING_LIST))
          /* <!-- #BLAZE_RULE($objc_compile_dependency_rule).ATTRIBUTE(sdk_includes) -->
          List of <code>#include/#import</code> search paths to add to this target
          and all depending targets, where each path is relative to
          <code>$(SDKROOT)/usr/include</code>.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("sdk_includes", Type.STRING_LIST))
          .build();
    }
    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_compile_dependency_rule")
          .type(RuleClassType.ABSTRACT)
          .ancestors(ResourcesRule.class, SdkFrameworksDependerRule.class)
          .build();
    }
  }

  /**
   * Common attributes for {@code objc_*} rules that contain compilable content.
   */
  public static class CompilingRule implements RuleDefinition {
    private static final Iterable<String> ALLOWED_DEPS_RULE_CLASSES =
        ImmutableSet.of(
            "objc_library",
            "objc_import",
            "objc_framework",
            "objc_proto_library",
            "j2objc_library",
            "cc_library",
            "cc_inc_library",
            "ios_framework",
            "swift_library",
            "experimental_objc_library");

    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          /* <!-- #BLAZE_RULE($objc_compiling_rule).ATTRIBUTE(srcs) -->
           The list of C, C++, Objective-C, and Objective-C++ source and header
           files that are processed to create the library target.
           These are your checked-in files, plus any generated files.
           Source files are compiled into .o files with Clang. Header files
           may be included/imported by any source or header in the srcs attribute
           of this target, but not by headers in hdrs or any targets that depend
           on this rule.
           Additionally, precompiled .o files may be given as srcs.  Be careful to
           ensure consistency in the architecture of provided .o files and that of the
           build to avoid missing symbol linker errors.
           <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("srcs", LABEL_LIST).direct_compile_time_input().allowedFileTypes(SRCS_TYPE))
          /* <!-- #BLAZE_RULE($objc_compiling_rule).ATTRIBUTE(non_arc_srcs) -->
           The list of Objective-C files that are processed to create the
           library target that DO NOT use ARC.
           The files in this attribute are treated very similar to those in the
           srcs attribute, but are compiled without ARC enabled.
           <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(
              attr("non_arc_srcs", LABEL_LIST)
                  .direct_compile_time_input()
                  .allowedFileTypes(NON_ARC_SRCS_TYPE))
          /* <!-- #BLAZE_RULE($objc_compiling_rule).ATTRIBUTE(pch) -->
           Header file to prepend to every source file being compiled (both arc
           and non-arc).
           Use of pch files is actively discouraged in BUILD files, and this should be
           considered deprecated. Since pch files are not actually precompiled this is not
           a build-speed enhancement, and instead is just a global dependency. From a build
           efficiency point of view you are actually better including what you need directly
           in your sources where you need it.
           <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("pch", LABEL).direct_compile_time_input().allowedFileTypes(FileType.of(".pch")))
          /* <!-- #BLAZE_RULE($objc_compiling_rule).ATTRIBUTE(deps) -->
           The list of targets that are linked together to form the final bundle.
           <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .override(
              attr("deps", LABEL_LIST)
                  .direct_compile_time_input()
                  .allowedRuleClasses(ALLOWED_DEPS_RULE_CLASSES)
                  .allowedFileTypes())
          /* <!-- #BLAZE_RULE($objc_compiling_rule).ATTRIBUTE(non_propagated_deps) -->
           The list of targets that are required in order to build this target,
           but which are not included in the final bundle.
           This attribute should only rarely be used, and probably only for proto
           dependencies.
           <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(
              attr("non_propagated_deps", LABEL_LIST)
                  .direct_compile_time_input()
                  .allowedRuleClasses(ALLOWED_DEPS_RULE_CLASSES)
                  .allowedFileTypes())
          /* <!-- #BLAZE_RULE($objc_compiling_rule).ATTRIBUTE(defines) -->
           Extra <code>-D</code> flags to pass to the compiler. They should be in
           the form <code>KEY=VALUE</code> or simply <code>KEY</code> and are
           passed not only to the compiler for this target (as <code>copts</code>
           are) but also to all <code>objc_</code> dependers of this target.
           Subject to <a href="make-variables.html">"Make variable"</a> substitution and
           <a href="common-definitions.html#sh-tokenization">Bourne shell tokenization</a>.
           <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("defines", STRING_LIST))
          /* <!-- #BLAZE_RULE($objc_compiling_rule).ATTRIBUTE(enable_modules) -->
           Enables clang module support (via -fmodules).
           Setting this to 1 will allow you to @import system headers and other targets:
           @import UIKit;
           @import path_to_package_target;
           <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("enable_modules", BOOLEAN))
          .build();
    }
    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_compiling_rule")
          .type(RuleClassType.ABSTRACT)
          .ancestors(
              BaseRuleClasses.RuleBase.class,
              CompileDependencyRule.class,
              CoptsRule.class,
              XcrunRule.class)
          .build();
    }
  }

  /**
   * Common attributes for {@code objc_*} rules that can optionally be set to {@code alwayslink}.
   */
  public static class AlwaysLinkRule implements RuleDefinition {
    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          /* <!-- #BLAZE_RULE($objc_alwayslink_rule).ATTRIBUTE(alwayslink) -->
          If 1, any bundle or binary that depends (directly or indirectly) on this
          library will link in all the object files for the files listed in
          <code>srcs</code> and <code>non_arc_srcs</code>, even if some contain no
          symbols referenced by the binary.
          This is useful if your code isn't explicitly called by code in
          the binary, e.g., if your code registers to receive some callback
          provided by some service.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("alwayslink", BOOLEAN))
          .build();
    }
    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_alwayslink_rule")
          .type(RuleClassType.ABSTRACT)
          .ancestors(CompileDependencyRule.class)
          .build();
    }
  }

  /**
   * Common attributes for {@code objc_*} rules that link sources and dependencies.
   */
  public static class LinkingRule implements RuleDefinition {
    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          .add(
              attr("$dumpsyms", LABEL)
                  .cfg(HOST)
                  .singleArtifact()
                  .value(env.getToolsLabel("//tools/osx/crosstool:dump_syms")))
          .add(
              attr("$j2objc_dead_code_pruner", LABEL)
                  .allowedFileTypes(FileType.of(".py"))
                  .cfg(HOST)
                  .exec()
                  .singleArtifact()
                  .value(env.getToolsLabel("//tools/objc:j2objc_dead_code_pruner")))
          .add(attr("$dummy_lib", LABEL).value(env.getToolsLabel("//tools/objc:dummy_lib")))
          /* <!-- #BLAZE_RULE($objc_linking_rule).ATTRIBUTE(linkopts) -->
          Extra flags to pass to the linker. 
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("linkopts", STRING_LIST))
          .build();
    }
    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_linking_rule")
          .type(RuleClassType.ABSTRACT)
          .ancestors(CompilingRule.class)
          .build();
    }
  }

  /**
   * Common attributes for {@code objc_*} rules that create a bundle.
   */
  public static class BundlingRule implements RuleDefinition {
    static final String INFOPLIST_ATTR = "infoplist";
    static final String FAMILIES_ATTR = "families";

    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          /* <!-- #BLAZE_RULE($objc_bundling_rule).ATTRIBUTE(infoplist)[DEPRECATED] -->
           The infoplist file. This corresponds to <i>appname</i>-Info.plist in Xcode projects.
           Blaze will perform variable substitution on the plist file for the following values:
           <ul>
             <li><code>${EXECUTABLE_NAME}</code>: The name of the executable generated and included
                in the bundle by blaze, which can be used as the value for
                <code>CFBundleExecutable</code> within the plist.
             <li><code>${BUNDLE_NAME}</code>: This target's name and bundle suffix (.bundle or .app)
                in the form<code><var>name</var></code>.<code>suffix</code>.
             <li><code>${PRODUCT_NAME}</code>: This target's name.
          </ul>
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(INFOPLIST_ATTR, LABEL).allowedFileTypes(PLIST_TYPE))
          /* <!-- #BLAZE_RULE($objc_bundling_rule).ATTRIBUTE(infoplists) -->
           Infoplist files to be merged. The merged output corresponds to <i>appname</i>-Info.plist
           in Xcode projects.  Duplicate keys between infoplist files will cause an error if
           and only if the values conflict.  If both <code>infoplist</code> and
           <code>infoplists</code> are specified, the files defined in both attributes will be used.
           Blaze will perform variable substitution on the plist files for the following values:
           <ul>
             <li><code>${EXECUTABLE_NAME}</code>: The name of the executable generated and included
                in the bundle by blaze, which can be used as the value for
                <code>CFBundleExecutable</code> within the plist.
             <li><code>${BUNDLE_NAME}</code>: This target's name and bundle suffix (.bundle or .app)
                in the form<code><var>name</var></code>.<code>suffix</code>.
             <li><code>${PRODUCT_NAME}</code>: This target's name.
          </ul>
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr("infoplists", BuildType.LABEL_LIST).allowedFileTypes(PLIST_TYPE))
          /* <!-- #BLAZE_RULE($objc_bundling_rule).ATTRIBUTE(families) -->
          The device families to which this bundle or binary is targeted.

          This is known as the <code>TARGETED_DEVICE_FAMILY</code> build setting
          in Xcode project files. It is a list of one or more of the strings
          <code>"iphone"</code> and <code>"ipad"</code>.

          <p>By default this is set to <code>"iphone"</code>, if explicitly specified may not be
          empty.</p>
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(
              attr(FAMILIES_ATTR, STRING_LIST)
                  .value(ImmutableList.of(TargetDeviceFamily.IPHONE.getNameInRule())))
          .add(
              attr("$momcwrapper", LABEL)
                  .cfg(HOST)
                  .exec()
                  .value(env.getToolsLabel("//tools/objc:momcwrapper")))
          .add(
              attr("$swiftstdlibtoolwrapper", LABEL)
                  .cfg(HOST)
                  .exec()
                  .value(env.getToolsLabel("//tools/objc:swiftstdlibtoolwrapper")))
          .build();
    }

    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_bundling_rule")
          .type(RuleClassType.ABSTRACT)
          .ancestors(
              AppleToolchain.RequiresXcodeConfigRule.class,
              ResourcesRule.class,
              ResourceToolsRule.class,
              XcrunRule.class)
          .build();
    }
  }

  /**
   * Common attributes for {@code objc_*} rules that create a bundle meant for release (e.g.
   * application or extension).
   */
  public static class ReleaseBundlingRule implements RuleDefinition {
    static final String APP_ICON_ATTR = "app_icon";
    static final String BUNDLE_ID_ATTR = "bundle_id";
    static final String DEFAULT_PROVISIONING_PROFILE_ATTR = ":default_provisioning_profile";
    static final String ENTITLEMENTS_ATTR = "entitlements";
    static final String EXTRA_ENTITLEMENTS_ATTR = ":extra_entitlements";
    static final String LAUNCH_IMAGE_ATTR = "launch_image";
    static final String LAUNCH_STORYBOARD_ATTR = "launch_storyboard";
    static final String PROVISIONING_PROFILE_ATTR = "provisioning_profile";

    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          /* <!-- #BLAZE_RULE($objc_release_bundling_rule).ATTRIBUTE(entitlements) -->
          The entitlements file required for device builds of this application.

          See
          <a href="https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/AboutEntitlements.html">the apple documentation</a>
          for more information. If absent, the default entitlements from the
          provisioning profile will be used.
          <p>
          The following variables are substituted as per
          <a href="https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html">their definitions in Apple's documentation</a>:
          $(AppIdentifierPrefix) and $(CFBundleIdentifier).
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(ENTITLEMENTS_ATTR, LABEL)
              .allowedFileTypes(ENTITLEMENTS_TYPE))
          .add(
              attr(EXTRA_ENTITLEMENTS_ATTR, LABEL)
                  .singleArtifact()
                  .value(
                      new LateBoundLabel<BuildConfiguration>(ObjcConfiguration.class) {
                        @Override
                        public Label resolve(
                            Rule rule, AttributeMap attributes, BuildConfiguration configuration) {
                          return configuration
                              .getFragment(ObjcConfiguration.class)
                              .getExtraEntitlements();
                        }
                      })
              .allowedFileTypes(ENTITLEMENTS_TYPE))
          /* <!-- #BLAZE_RULE($objc_release_bundling_rule).ATTRIBUTE(provisioning_profile) -->
          The provisioning profile (.mobileprovision file) to use when bundling
          the application.

          This is only used for non-simulator builds.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(
              attr(PROVISIONING_PROFILE_ATTR, LABEL)
                  .singleArtifact()
                  .allowedFileTypes(FileType.of(".mobileprovision")))
          // Will be used if provisioning_profile is null.
          .add(
              attr(DEFAULT_PROVISIONING_PROFILE_ATTR, LABEL)
                  .singleArtifact()
                  .allowedFileTypes(FileType.of(".mobileprovision"))
                  .value(
                      new LateBoundLabel<BuildConfiguration>(ObjcConfiguration.class) {
                        @Override
                        public Label resolve(Rule rule, AttributeMap attributes,
                            BuildConfiguration configuration) {
                          AppleConfiguration appleConfiguration =
                              configuration.getFragment(AppleConfiguration.class);
                          if (appleConfiguration.getBundlingPlatform() != Platform.IOS_DEVICE) {
                            return null;
                          }
                          if (rule.isAttributeValueExplicitlySpecified(PROVISIONING_PROFILE_ATTR)) {
                            return null;
                          }
                          return appleConfiguration.getDefaultProvisioningProfileLabel();
                        }
                      }))
          /* <!-- #BLAZE_RULE($objc_release_bundling_rule).ATTRIBUTE(app_icon) -->
          The name of the application icon.

          The icon should be in one of the asset catalogs of this target or
          a (transitive) dependency. In a new project, this is initialized
          to "AppIcon" by Xcode.
          <p>
          If the application icon is not in an asset catalog, do not use this
          attribute. Instead, add a CFBundleIcons entry to the Info.plist file.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(APP_ICON_ATTR, STRING))
          /* <!-- #BLAZE_RULE($objc_release_bundling_rule).ATTRIBUTE(launch_image) -->
          The name of the launch image.

          The icon should be in one of the asset catalogs of this target or
          a (transitive) dependency. In a new project, this is initialized
          to "LaunchImage" by Xcode.
          <p>
          If the launch image is not in an asset catalog, do not use this
          attribute. Instead, add an appropriately-named image resource to the
          bundle.
          <p>
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(LAUNCH_IMAGE_ATTR, STRING))
          /* <!-- #BLAZE_RULE($objc_release_bundling_rule).ATTRIBUTE(launch_storyboard) -->
          The location of the launch storyboard (.xib or .storyboard).

          The provided storyboard will be compiled to the appropriate format
          (.nib or .storyboardc respectively) and placed in the root of the
          final package. If the storyboard's immediate containing directory is
          named *.lproj (e.g. en.lproj, Base.lproj), it will be placed under a
          directory of that name in the final bundle. This allows for
          localizable UI.
          <p>
          The generated storyboard is registered in the final bundle's
          <code>Info.plist</code> under the key
          <code>UILaunchStoryboardName</code>.
          <p>
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(
              attr(LAUNCH_STORYBOARD_ATTR, LABEL)
                  .direct_compile_time_input()
                  .allowedFileTypes(FileTypeSet.of(XIB_TYPE, STORYBOARD_TYPE)))
          /* <!-- #BLAZE_RULE($objc_release_bundling_rule).ATTRIBUTE(bundle_id) -->
          The bundle ID (reverse-DNS path followed by app name) of the binary.

          If specified, it will override the bundle ID specified in the associated plist file. If
          no bundle ID is specified on either this attribute or in the plist file, a junk value
          will be used.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(
              attr(BUNDLE_ID_ATTR, STRING)
                  .value(
                      new Attribute.ComputedDefault() {
                        @Override
                        public Object getDefault(AttributeMap rule) {
                          // For tests and similar, we don't want to force people to explicitly
                          // specify throw-away data.
                          return "example." + rule.getName();
                        }
                      }))
          .build();
    }
    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_release_bundling_rule")
          .type(RuleClassType.ABSTRACT)
          .ancestors(BundlingRule.class, ReleaseBundlingToolsRule.class)
          .build();
    }
  }

  /**
   * Common attributes for rules that require tools to create a bundle meant for
   * release (e.g. application or extension).
   */
  public static class ReleaseBundlingToolsRule implements RuleDefinition {
    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          .add(
              attr("$bundlemerge", LABEL)
                  .cfg(HOST)
                  .exec()
                  .value(env.getToolsLabel("//tools/objc:bundlemerge")))
          .add(
              attr("$environment_plist", LABEL)
                  .cfg(HOST)
                  .exec()
                  .value(env.getToolsLabel("//tools/objc:environment_plist")))
          .build();
    }
    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$release_bundling_tools_rule")
          .type(RuleClassType.ABSTRACT)
          .build();
    }
  }

  /**
   * Common attributes for {@code objc_*} rules that create a signed IPA.
   */
  public static class IpaRule implements RuleDefinition {
    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          /* <!-- #BLAZE_RULE($objc_ipa_rule).ATTRIBUTE(ipa_post_processor) -->
          A tool that edits this target's IPA output after it is assembled but before it is
          (optionally) signed.
          <p>
          The tool is invoked with a single positional argument which represents the path to a
          directory containing the unzipped contents of the IPA. The only entry in this directory
          will be the <code>Payload</code> root directory of the IPA. Any changes made by the tool
          must be made in this directory, whose contents will be (optionally) signed and then
          zipped up as the final IPA after the tool terminates.
          <p>
          The tool's execution must be hermetic given these inputs to ensure that its result can be
          safely cached.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(
              attr("ipa_post_processor", LABEL)
                  .allowedRuleClasses(ANY_RULE)
                  .allowedFileTypes(FileTypeSet.ANY_FILE)
                  .exec())
          .build();
    }

    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_ipa_rule")
          .type(RuleClassType.ABSTRACT)
          .build();
    }
  }

  /**
   * Common attributes for {@code objc_*} rules that use the iOS simulator.
   */
  public static class SimulatorRule implements RuleDefinition {
    static final String IOSSIM_ATTR = "$iossim";
    static final String STD_REDIRECT_DYLIB_ATTR = "$std_redirect_dylib";

    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          // Needed to run the binary in the simulator.
          .add(attr(IOSSIM_ATTR, LABEL).cfg(HOST).exec()
              .value(env.getToolsLabel("//third_party/iossim:iossim")))
          .add(attr(STD_REDIRECT_DYLIB_ATTR, LABEL).cfg(HOST).exec()
              .value(env.getToolsLabel("//tools/objc:StdRedirect.dylib")))
          .build();
    }
    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_simulator_rule")
          .type(RuleClassType.ABSTRACT)
          .build();
    }
  }

  /**
   * Common attributes for {@code objc_*} rules that need to call xcrun.
   */
  public static class XcrunRule implements RuleDefinition {
    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          .add(attr("$xcrunwrapper", LABEL).cfg(HOST).exec()
              .value(env.getToolsLabel("//tools/objc:xcrunwrapper")))
          .build();
    }
    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$objc_xcrun_rule")
          .type(RuleClassType.ABSTRACT)
          .ancestors(RequiresXcodeConfigRule.class)
          .build();
    }
  }

  /**
   * Attributes for {@code apple_watch*} rules that creates a watch extension bundle.
   */
  public static class WatchExtensionBundleRule implements RuleDefinition {
    static final String WATCH_EXT_BUNDLE_ID_ATTR = "ext_bundle_id";
    static final String WATCH_EXT_DEFAULT_PROVISIONING_PROFILE_ATTR =
        ":default_ext_provisioning_profile";
    static final String WATCH_EXT_ENTITLEMENTS_ATTR = "ext_entitlements";
    static final String WATCH_EXT_PROVISIONING_PROFILE_ATTR = "ext_provisioning_profile";
    static final String WATCH_EXT_INFOPLISTS_ATTR = "ext_infoplists";
    static final String WATCH_EXT_RESOURCES_ATTR = "ext_resources";
    static final String WATCH_EXT_STRUCTURED_RESOURCES_ATTR = "ext_structured_resources";
    static final String WATCH_EXT_STRINGS_ATTR = "ext_strings";
    static final String WATCH_EXT_FAMILIES_ATTR = "ext_families";

    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          /* <!-- #BLAZE_RULE($watch_extension_bundle_rule).ATTRIBUTE(ext_bundle_id) -->
          The bundle ID (reverse-DNS path followed by app name) of the watch extension binary.

          If specified, it will override the bundle ID specified in the associated plist file. If
          no bundle ID is specified on either this attribute or in the plist file, a junk value
          will be used.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(
              attr(WATCH_EXT_BUNDLE_ID_ATTR, STRING)
                  .value(
                      new Attribute.ComputedDefault() {
                        @Override
                        public Object getDefault(AttributeMap rule) {
                          // For tests and similar, we don't want to force people to explicitly
                          // specify throw-away data.
                          return "example.ext." + rule.getName();
                        }
                      }))
          /* <!-- #BLAZE_RULE($watch_extension_bundle_rule).ATTRIBUTE(ext_entitlements) -->
          The entitlements file required for device builds of watch extension.

          See
          <a href="https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/AboutEntitlements.html">the apple documentation</a>
          for more information. If absent, the default entitlements from the
          provisioning profile will be used.
          <p>
          The following variables are substituted as per
          <a href="https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html">their definitions in Apple's documentation</a>:
          $(AppIdentifierPrefix) and $(CFBundleIdentifier).
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_EXT_ENTITLEMENTS_ATTR, LABEL)
              .allowedFileTypes(ENTITLEMENTS_TYPE))
          /* <!-- #BLAZE_RULE($watch_extension_bundle_rule).ATTRIBUTE(ext_families) -->
          The device families to which the watch extension is targeted.

          This is known as the <code>TARGETED_DEVICE_FAMILY</code> build setting
          in Xcode project files. It is a list of one or more of the strings
          <code>"iphone"</code> and <code>"ipad"</code>.

          <p>By default this is set to <code>"iphone"</code>, if explicitly specified may not be
          empty.</p>
          <p>The watch application is always built for <code>"watch"</code> for device builds and
          <code>"iphone, watch"</code> for simulator builds.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(
              attr(WATCH_EXT_FAMILIES_ATTR, STRING_LIST)
                  .value(ImmutableList.of(TargetDeviceFamily.IPHONE.getNameInRule())))
          /* <!-- #BLAZE_RULE($watch_extension_bundle_rule).ATTRIBUTE(ext_infoplists) -->
           Infoplist files to be merged. The merged output corresponds to <i>appname</i>-Info.plist
           in Xcode projects.  Duplicate keys between infoplist files will cause an error if
           and only if the values conflict.  If both <code>infoplist</code> and
           <code>infoplists</code> are specified, the files defined in both attributes will be used.
           Blaze will perform variable substitution on the plist files for the following values:
           <ul>
             <li><code>${EXECUTABLE_NAME}</code>: The name of the executable generated and included
                in the bundle by blaze, which can be used as the value for
                <code>CFBundleExecutable</code> within the plist.
             <li><code>${BUNDLE_NAME}</code>: This target's name and bundle suffix (.bundle or .app)
                in the form<code><var>name</var></code>.<code>suffix</code>.
             <li><code>${PRODUCT_NAME}</code>: This target's name.
          </ul>
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_EXT_INFOPLISTS_ATTR, BuildType.LABEL_LIST).allowedFileTypes(PLIST_TYPE))
          /* <!-- #BLAZE_RULE($watch_extension_bundle_rule).ATTRIBUTE(ext_provisioning_profile) -->
          The provisioning profile (.mobileprovision file) to use when bundling
          the watch extension.

          This is only used for non-simulator builds.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(
              attr(WATCH_EXT_PROVISIONING_PROFILE_ATTR, LABEL)
                  .singleArtifact()
                  .allowedFileTypes(FileType.of(".mobileprovision")))
          .add(
              attr(WATCH_EXT_DEFAULT_PROVISIONING_PROFILE_ATTR, LABEL)
                  .singleArtifact()
                  .allowedFileTypes(FileType.of(".mobileprovision"))
                  .value(
                      new LateBoundLabel<BuildConfiguration>(ObjcConfiguration.class) {
                        @Override
                        public Label resolve(Rule rule, AttributeMap attributes,
                            BuildConfiguration configuration) {
                          AppleConfiguration appleConfiguration =
                              configuration.getFragment(AppleConfiguration.class);
                          if (appleConfiguration.getBundlingPlatform() != Platform.IOS_DEVICE) {
                            return null;
                          }
                          if (rule.isAttributeValueExplicitlySpecified(
                              WATCH_EXT_PROVISIONING_PROFILE_ATTR)) {
                            return null;
                          }
                          return appleConfiguration.getDefaultProvisioningProfileLabel();
                        }
                      }))
          /* <!-- #BLAZE_RULE($watch_extension_bundle_rule).ATTRIBUTE(ext_resources) -->
          Files to include in the final watch extension bundle.

          They are not processed or compiled in any way besides the processing
          done by the rules that actually generate them. These files are placed
          in the root of the bundle (e.g. Foo.app/...) in most cases.
          However, if they appear to be localized (i.e. are contained in a
          directory called *.lproj), they will be placed in a directory of the
          same name in the app bundle.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_EXT_RESOURCES_ATTR, LABEL_LIST).legacyAllowAnyFileType()
              .direct_compile_time_input())
          /* <!-- #BLAZE_RULE($watch_extension_bundle_rule).ATTRIBUTE(ext_structured_resources)-->
          Files to include in the final watch extension bundle.

          They are not processed or compiled in any way besides the processing
          done by the rules that actually generate them. In differences to
          <code>resources</code> these files are placed in the bundle root in
          the same structure passed to this argument, so
          <code>["res/foo.png"]</code> will end up in
          <code>Foo.app/res/foo.png</code>.
          <p>Note that in the generated XCode project file, all files in the top directory of
          the specified files will be included in the Xcode-generated app bundle. So
          specifying <code>["res/foo.png"]</code> will lead to the inclusion of all files in
          directory <code>res</code>.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_EXT_STRUCTURED_RESOURCES_ATTR, LABEL_LIST)
              .legacyAllowAnyFileType()
              .direct_compile_time_input())
          /* <!-- #BLAZE_RULE($watch_extension_bundle_rule).ATTRIBUTE(ext_strings) -->
          Files which are plists of strings, often localizable to be added to watch extension.

          These files are converted to binary plists (if they are not already)
          and placed in the bundle root of the final package. If this file's
          immediate containing directory is named *.lproj (e.g. en.lproj,
          Base.lproj), it will be placed under a directory of that name in the
          final bundle. This allows for localizable strings.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_EXT_STRINGS_ATTR, LABEL_LIST)
              .allowedFileTypes(STRINGS_TYPE)
              .direct_compile_time_input())
            .build();
    }

    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$watch_extension_bundle_rule")
          .type(RuleClassType.ABSTRACT)
          .ancestors(
              AppleToolchain.RequiresXcodeConfigRule.class,
              ResourceToolsRule.class,
              ReleaseBundlingToolsRule.class,
              XcrunRule.class)
          .build();
    }
  }

  /**
   * Attributes for {@code apple_watch*} rules that creates a watch application bundle.
   */
  public static class WatchApplicationBundleRule implements RuleDefinition {
    static final String WATCH_APP_NAME_ATTR = "app_name";
    static final String WATCH_APP_ICON_ATTR = "app_icon";
    static final String WATCH_APP_BUNDLE_ID_ATTR = "app_bundle_id";
    static final String WATCH_APP_DEFAULT_PROVISIONING_PROFILE_ATTR =
        ":default_app_provisioning_profile";
    static final String WATCH_APP_ENTITLEMENTS_ATTR = "app_entitlements";
    static final String WATCH_APP_PROVISIONING_PROFILE_ATTR = "app_provisioning_profile";
    static final String WATCH_APP_ASSET_CATALOGS_ATTR = "app_asset_catalogs";
    static final String WATCH_APP_INFOPLISTS_ATTR = "app_infoplists";
    static final String WATCH_APP_STORYBOARDS_ATTR = "app_storyboards";
    static final String WATCH_APP_RESOURCES_ATTR = "app_resources";
    static final String WATCH_APP_STRUCTURED_RESOURCES_ATTR = "app_structured_resources";
    static final String WATCH_APP_STRINGS_ATTR = "app_strings";

    @Override
    public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
      return builder
          /* <!-- #BLAZE_RULE($watch_application_bundle_rule).ATTRIBUTE(app_name) -->
          Name of the final watch application binary.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_APP_NAME_ATTR, STRING).mandatory())
          /* <!-- #BLAZE_RULE($watch_application_bundle_rule).ATTRIBUTE(app_icon) -->
          The name of the watch application icon.

          The icon should be in one of the asset catalogs of this target or
          a (transitive) dependency. In a new project, this is initialized
          to "AppIcon" by Xcode.
          <p>
          If the application icon is not in an asset catalog, do not use this
          attribute. Instead, add a CFBundleIcons entry to the Info.plist file.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_APP_ICON_ATTR, STRING))
          /* <!-- #BLAZE_RULE($watch_application_bundle_rule).ATTRIBUTE(app_entitlements) -->
          The entitlements file required for device builds of watch application.

          See
          <a href="https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/AboutEntitlements.html">the apple documentation</a>
          for more information. If absent, the default entitlements from the
          provisioning profile will be used.
          <p>
          The following variables are substituted as per
          <a href="https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html">their definitions in Apple's documentation</a>:
          $(AppIdentifierPrefix) and $(CFBundleIdentifier).
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_APP_ENTITLEMENTS_ATTR, LABEL)
              .allowedFileTypes(ENTITLEMENTS_TYPE))
          /* <!-- #BLAZE_RULE($watch_application_bundle_rule).ATTRIBUTE(app_asset_catalogs) -->
          Files that comprise the asset catalogs of the final linked binary.

          Each file must have a containing directory named *.xcassets. This
          containing directory becomes the root of one of the asset catalogs
          linked with any binary that depends directly or indirectly on this
          target.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_APP_ASSET_CATALOGS_ATTR, LABEL_LIST).legacyAllowAnyFileType()
              .direct_compile_time_input())
          /* <!-- #BLAZE_RULE($watch_application_bundle_rule).ATTRIBUTE(app_bundle_id) -->
          The bundle ID (reverse-DNS path followed by app name) of the watch application binary.

          If specified, it will override the bundle ID specified in the associated plist file. If
          no bundle ID is specified on either this attribute or in the plist file, a junk value
          will be used.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(
              attr(WATCH_APP_BUNDLE_ID_ATTR, STRING)
                  .value(
                      new Attribute.ComputedDefault(WATCH_APP_NAME_ATTR) {
                        @Override
                        public Object getDefault(AttributeMap rule) {
                          // For tests and similar, we don't want to force people to explicitly
                          // specify throw-away data.
                          return "example.app." + rule.get(WATCH_APP_NAME_ATTR, STRING);
                        }
                      }))
          /* <!-- #BLAZE_RULE($watch_application_bundle_rule).ATTRIBUTE(app_infoplists) -->
           Infoplist files to be merged. The merged output corresponds to <i>appname</i>-Info.plist
           in Xcode projects.  Duplicate keys between infoplist files will cause an error if
           and only if the values conflict.  If both <code>infoplist</code> and
           <code>infoplists</code> are specified, the files defined in both attributes will be used.
           Blaze will perform variable substitution on the plist files for the following values:
           <ul>
             <li><code>${EXECUTABLE_NAME}</code>: The name of the executable generated and included
                in the bundle by blaze, which can be used as the value for
                <code>CFBundleExecutable</code> within the plist.
             <li><code>${BUNDLE_NAME}</code>: This target's name and bundle suffix (.bundle or .app)
                in the form<code><var>name</var></code>.<code>suffix</code>.
             <li><code>${PRODUCT_NAME}</code>: This target's name.
          </ul>
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_APP_INFOPLISTS_ATTR, BuildType.LABEL_LIST).allowedFileTypes(PLIST_TYPE))
          /* <!-- #BLAZE_RULE($watch_application_bundle_rule).ATTRIBUTE(app_provisioning_profile)-->
          The provisioning profile (.mobileprovision file) to use when bundling
          the watch application.

          This is only used for non-simulator builds.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(
              attr(WATCH_APP_PROVISIONING_PROFILE_ATTR, LABEL)
                  .singleArtifact()
                  .allowedFileTypes(FileType.of(".mobileprovision")))
          .add(
              attr(WATCH_APP_DEFAULT_PROVISIONING_PROFILE_ATTR, LABEL)
                  .singleArtifact()
                  .allowedFileTypes(FileType.of(".mobileprovision"))
                  .value(
                      new LateBoundLabel<BuildConfiguration>(ObjcConfiguration.class) {
                        @Override
                        public Label resolve(Rule rule, AttributeMap attributes,
                            BuildConfiguration configuration) {
                          AppleConfiguration appleConfiguration =
                              configuration.getFragment(AppleConfiguration.class);
                          if (appleConfiguration.getBundlingPlatform() != Platform.IOS_DEVICE) {
                            return null;
                          }
                          if (rule.isAttributeValueExplicitlySpecified(
                              WATCH_APP_PROVISIONING_PROFILE_ATTR)) {
                            return null;
                          }
                          return appleConfiguration.getDefaultProvisioningProfileLabel();
                        }
                      }))
          /* <!-- #BLAZE_RULE($objc_resources_rule).ATTRIBUTE(app_storyboards) -->
          Files which are .storyboard resources for the watch application, possibly
          localizable.

          These files are compiled and placed in the bundle root of the final package.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_APP_STORYBOARDS_ATTR, LABEL_LIST)
              .allowedFileTypes(STORYBOARD_TYPE))
          /* <!-- #BLAZE_RULE($watch_application_bundle_rule).ATTRIBUTE(app_resources) -->
          Files to include in the final watch application bundle.

          They are not processed or compiled in any way besides the processing
          done by the rules that actually generate them. These files are placed
          in the root of the bundle (e.g. Foo.app/...) in most cases.
          However, if they appear to be localized (i.e. are contained in a
          directory called *.lproj), they will be placed in a directory of the
          same name in the app bundle.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_APP_RESOURCES_ATTR, LABEL_LIST).legacyAllowAnyFileType()
              .direct_compile_time_input())
          /* <!-- #BLAZE_RULE($watch_application_bundle_rule).ATTRIBUTE(app_structured_resources)-->
          Files to include in the final watch application bundle.

          They are not processed or compiled in any way besides the processing
          done by the rules that actually generate them. In differences to
          <code>resources</code> these files are placed in the bundle root in
          the same structure passed to this argument, so
          <code>["res/foo.png"]</code> will end up in
          <code>Foo.app/res/foo.png</code>.
          <p>Note that in the generated XCode project file, all files in the top directory of
          the specified files will be included in the Xcode-generated app bundle. So
          specifying <code>["res/foo.png"]</code> will lead to the inclusion of all files in
          directory <code>res</code>.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_APP_STRUCTURED_RESOURCES_ATTR, LABEL_LIST)
              .legacyAllowAnyFileType()
              .direct_compile_time_input())
          /* <!-- #BLAZE_RULE($watch_application_bundle_rule).ATTRIBUTE(app_strings) -->
          Files which are plists of strings, often localizable to be added to watch application.

          These files are converted to binary plists (if they are not already)
          and placed in the bundle root of the final package. If this file's
          immediate containing directory is named *.lproj (e.g. en.lproj,
          Base.lproj), it will be placed under a directory of that name in the
          final bundle. This allows for localizable strings.
          <!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
          .add(attr(WATCH_APP_STRINGS_ATTR, LABEL_LIST)
              .allowedFileTypes(STRINGS_TYPE)
              .direct_compile_time_input())
          .build();
    }
    @Override
    public Metadata getMetadata() {
      return RuleDefinition.Metadata.builder()
          .name("$watch_application_bundle_rule")
          .type(RuleClassType.ABSTRACT)
          .ancestors(
              AppleToolchain.RequiresXcodeConfigRule.class,
              ResourceToolsRule.class,
              ReleaseBundlingToolsRule.class,
              XcrunRule.class)
          .build();
    }
  }
}