-
Notifications
You must be signed in to change notification settings - Fork 305
/
intellij_info_impl.bzl
1371 lines (1153 loc) · 54.1 KB
/
intellij_info_impl.bzl
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
"""Implementation of IntelliJ-specific information collecting aspect."""
load(
"@bazel_tools//tools/build_defs/cc:action_names.bzl",
"ACTION_NAMES",
)
load(
":artifacts.bzl",
"artifact_location",
"artifacts_from_target_list_attr",
"is_external_artifact",
"sources_from_target",
"struct_omit_none",
"to_artifact_location",
)
load(":flag_hack.bzl", "FlagHackInfo")
load("@intellij_aspect_template//:java_info.bzl", "get_java_info", "java_info_in_target", "java_info_reference")
load("@intellij_aspect_template//:code_generator_info.bzl", "CODE_GENERATOR_RULE_NAMES")
load(
":make_variables.bzl",
"expand_make_variables",
)
IntelliJInfo = provider(
doc = "Collected information about the targets visited by the aspect.",
fields = [
"export_deps",
"kind",
"output_groups",
"target_key",
],
)
# Defensive list of features that can appear in the C++ toolchain, but which we
# definitely don't want to enable (when enabled, they'd contribute command line
# flags that don't make sense in the context of intellij info).
UNSUPPORTED_FEATURES = [
"thin_lto",
"module_maps",
"use_header_modules",
"fdo_instrument",
"fdo_optimize",
]
# Compile-time dependency attributes, grouped by type.
DEPS = [
"_stl", # From cc rules
"malloc", # From cc_binary rules
"implementation_deps", # From cc_library rules
"_java_toolchain", # From java rules
"deps",
"jars", # from java_import rules
"exports",
"java_lib", # From old proto_library rules
"_android_sdk", # from android rules
"_aidl_lib", # from android_library
"_scala_toolchain", # From scala rules
"test_app", # android_instrumentation_test
"instruments", # android_instrumentation_test
"tests", # From test_suite
"compilers", # From go_proto_library
"associates", # From kotlin rules
]
# Run-time dependency attributes, grouped by type.
RUNTIME_DEPS = [
"runtime_deps",
]
PREREQUISITE_DEPS = []
# Dependency type enum
COMPILE_TIME = 0
RUNTIME = 1
# PythonVersion enum; must match PyIdeInfo.PythonVersion
PY2 = 1
PY3 = 2
# PythonCompatVersion enum; must match PyIdeInfo.PythonSrcsVersion
SRC_PY2 = 1
SRC_PY3 = 2
SRC_PY2AND3 = 3
SRC_PY2ONLY = 4
SRC_PY3ONLY = 5
##### Helpers
def get_code_generator_rule_names(ctx, language_name):
"""Supplies a list of Rule names for code generation for the language specified
For some languages, it is possible to specify Rules' names that are interpreted as
code-generators for the language. These Rules' names are specified as attrs and are provided to
the aspect using the `AspectStrategy#AspectParameter` in the plugin logic.
"""
if not language_name:
fail("the `language_name` must be provided")
if hasattr(CODE_GENERATOR_RULE_NAMES, language_name):
return getattr(CODE_GENERATOR_RULE_NAMES, language_name)
return []
def get_registry_flag(ctx, name):
"""Registry flags are passed to aspects using defines. See CppAspectArgsProvider."""
return ctx.var.get(name) == "true"
def source_directory_tuple(resource_file):
"""Creates a tuple of (exec_path, root_exec_path_fragment, is_source, is_external)."""
relative_path = str(android_common.resource_source_directory(resource_file))
root_exec_path_fragment = resource_file.root.path if not resource_file.is_source else None
return (
relative_path if resource_file.is_source else root_exec_path_fragment + "/" + relative_path,
root_exec_path_fragment,
resource_file.is_source,
is_external_artifact(resource_file.owner),
)
def get_res_artifacts(resources):
"""Get a map from the res folder to the set of resource files within that folder.
Args:
resources: all resources of a target
Returns:
a map from the res folder to the set of resource files within that folder (as a tuple of path segments)
"""
res_artifacts = dict()
for resource in resources:
for file in resource.files.to_list():
res_folder = source_directory_tuple(file)
res_artifacts.setdefault(res_folder, []).append(file)
return res_artifacts
def build_file_artifact_location(ctx):
"""Creates an ArtifactLocation proto representing a location of a given BUILD file."""
return to_artifact_location(
ctx.label.package + "/BUILD",
ctx.label.package + "/BUILD",
True,
is_external_artifact(ctx.label),
)
# https://github.com/bazelbuild/bazel/issues/18966
def _list_or_depset_to_list(list_or_depset):
if hasattr(list_or_depset, "to_list"):
return list_or_depset.to_list()
return list_or_depset
def get_source_jars(output):
if hasattr(output, "source_jars"):
return _list_or_depset_to_list(output.source_jars)
if hasattr(output, "source_jar"):
return [output.source_jar]
return []
def library_artifact(java_output, rule_kind = None):
"""Creates a LibraryArtifact representing a given java_output."""
if java_output == None or java_output.class_jar == None:
return None
src_jars = get_source_jars(java_output)
if rule_kind != None and rule_kind.startswith("scala"):
interface_jar = None
else:
interface_jar = artifact_location(java_output.ijar)
return struct_omit_none(
interface_jar = interface_jar,
jar = artifact_location(java_output.class_jar),
source_jar = artifact_location(src_jars[0]) if src_jars else None,
source_jars = [artifact_location(f) for f in src_jars],
)
def annotation_processing_jars(generated_class_jar, generated_source_jar):
"""Creates a LibraryArtifact representing Java annotation processing jars."""
src_jar = generated_source_jar
return struct_omit_none(
jar = artifact_location(generated_class_jar),
source_jar = artifact_location(src_jar),
source_jars = [artifact_location(src_jar)] if src_jar else None,
)
def jars_from_output(output):
"""Collect jars for intellij-resolve-files from Java output."""
if output == None:
return []
source_jars = get_source_jars(output)
return [
jar
for jar in ([output.ijar if len(source_jars) > 0 and output.ijar else output.class_jar] + source_jars)
if jar != None and not jar.is_source
]
def _collect_target_from_attr(rule_attrs, attr_name, result):
"""Collects the targets from the given attr into the result."""
if not hasattr(rule_attrs, attr_name):
return
attr_value = getattr(rule_attrs, attr_name)
type_name = type(attr_value)
if type_name == "Target":
result.append(attr_value)
elif type_name == "list":
result.extend(attr_value)
def collect_targets_from_attrs(rule_attrs, attrs):
"""Returns a list of targets from the given attributes."""
result = []
for attr_name in attrs:
_collect_target_from_attr(rule_attrs, attr_name, result)
return [target for target in result if is_valid_aspect_target(target)]
def list_omit_none(value):
"""Returns a list of the value, or the empty list if None."""
return [value] if value else []
def is_valid_aspect_target(target):
"""Returns whether the target has had the aspect run on it."""
return IntelliJInfo in target
def get_aspect_ids(ctx):
"""Returns the all aspect ids, filtering out self."""
aspect_ids = None
if hasattr(ctx, "aspect_ids"):
aspect_ids = ctx.aspect_ids
else:
return None
return [aspect_id for aspect_id in aspect_ids if "intellij_info_aspect" not in aspect_id]
def _is_language_specific_proto_library(ctx, target, semantics):
"""Returns True if the target is a proto library with attached language-specific aspect."""
if ctx.rule.kind != "proto_library":
return False
if java_info_in_target(target):
return True
if CcInfo in target:
return True
if semantics.go.is_proto_library(target, ctx):
return True
return False
def stringify_label(label):
"""Stringifies a label, making sure any leading '@'s are stripped from main repo labels."""
s = str(label)
# If the label is in the main repo, make sure any leading '@'s are stripped so that tests are
# okay with the fixture setups.
return s.lstrip("@") if s.startswith("@@//") or s.startswith("@//") else s
def make_target_key(label, aspect_ids):
"""Returns a TargetKey proto struct from a target."""
return struct_omit_none(
aspect_ids = tuple(aspect_ids) if aspect_ids else None,
label = stringify_label(label),
)
def make_dep(dep, dependency_type):
"""Returns a Dependency proto struct."""
return struct(
dependency_type = dependency_type,
target = dep[IntelliJInfo].target_key,
)
def make_deps(deps, dependency_type):
"""Returns a list of Dependency proto structs."""
return [make_dep(dep, dependency_type) for dep in deps]
def make_dep_from_label(label, dependency_type):
"""Returns a Dependency proto struct from a label."""
return struct(
dependency_type = dependency_type,
target = struct(label = stringify_label(label)),
)
def update_sync_output_groups(groups_dict, key, new_set):
"""Updates all sync-relevant output groups associated with 'key'.
This is currently the [key] output group itself, together with [key]-outputs
and [key]-direct-deps.
Args:
groups_dict: the output groups dict, from group name to artifact depset.
key: the base output group name.
new_set: a depset of artifacts to add to the output groups.
"""
update_set_in_dict(groups_dict, key, new_set)
update_set_in_dict(groups_dict, key + "-outputs", new_set)
update_set_in_dict(groups_dict, key + "-direct-deps", new_set)
def update_set_in_dict(input_dict, key, other_set):
"""Updates depset in dict, merging it with another depset."""
input_dict[key] = depset(transitive = [input_dict.get(key, depset()), other_set])
def _get_output_mnemonic(ctx):
"""Gives the output directory mnemonic for some target context."""
return ctx.bin_dir.path.split("/")[1]
def _get_python_version(ctx):
if ctx.attr._flag_hack[FlagHackInfo].incompatible_py2_outputs_are_suffixed:
if _get_output_mnemonic(ctx).find("-py2-") != -1:
return PY2
return PY3
else:
if _get_output_mnemonic(ctx).find("-py3-") != -1:
return PY3
return PY2
_SRCS_VERSION_MAPPING = {
"PY2": SRC_PY2,
"PY3": SRC_PY3,
"PY2AND3": SRC_PY2AND3,
"PY2ONLY": SRC_PY2ONLY,
"PY3ONLY": SRC_PY3ONLY,
}
def _get_python_srcs_version(ctx):
srcs_version = getattr(ctx.rule.attr, "srcs_version", "PY2AND3")
return _SRCS_VERSION_MAPPING.get(srcs_version, default = SRC_PY2AND3)
def _do_starlark_string_expansion(ctx, name, strings, extra_targets = []):
# first, expand all starlark predefined paths:
# location, locations, rootpath, rootpaths, execpath, execpaths
strings = [ctx.expand_location(value, targets = extra_targets) for value in strings]
# then expand any regular GNU make style variables
strings = [expand_make_variables(name, value, ctx) for value in strings]
return strings
##### Builders for individual parts of the aspect output
def collect_py_info(target, ctx, semantics, ide_info, ide_info_file, output_groups):
"""Updates Python-specific output groups, returns false if not a Python target."""
if not PyInfo in target or _is_language_specific_proto_library(ctx, target, semantics):
return False
py_semantics = getattr(semantics, "py", None)
if py_semantics:
py_launcher = py_semantics.get_launcher(target, ctx)
else:
py_launcher = None
sources = sources_from_target(ctx)
to_build = target[PyInfo].transitive_sources
args = getattr(ctx.rule.attr, "args", [])
data_deps = getattr(ctx.rule.attr, "data", [])
args = _do_starlark_string_expansion(ctx, "args", args, data_deps)
imports = getattr(ctx.rule.attr, "imports", [])
is_code_generator = False
# If there are apparently no sources found from `srcs` and the target has a rule name which is
# one of the ones pre-specified to the aspect as being a code-generator for Python then
# interpret the outputs of the target specified in the PyInfo as being sources.
if 0 == len(sources) and ctx.rule.kind in get_code_generator_rule_names(ctx, "python"):
def provider_import_to_attr_import(provider_import):
"""\
Remaps the imports from PyInfo
The imports that are supplied on the `PyInfo` are relative to the runfiles and so are
not the same as those which might be supplied on an attribute of `py_library`. This
function will remap those back so they look as if they were `imports` attributes on
the rule. The form of the runfiles import is `<workspace_name>/<package_dir>/<import>`.
The actual `workspace_name` is not interesting such that the first part can be simply
stripped. Next the package to the Label is stripped leaving a path that would have been
supplied on an `imports` attribute to a Rule.
"""
# Other code in this file appears to assume *NIX path component separators?
provider_import_parts = [p for p in provider_import.split("/")]
package_parts = [p for p in ctx.label.package.split("/")]
if 0 == len(provider_import_parts):
return None
scratch_parts = provider_import_parts[1:] # remove the workspace name or _main
for p in package_parts:
if 0 != len(provider_import_parts) and scratch_parts[0] == p:
scratch_parts = scratch_parts[1:]
else:
return None
return "/".join(scratch_parts)
def provider_imports_to_attr_imports():
result = []
for provider_import in target[PyInfo].imports.to_list():
attr_import = provider_import_to_attr_import(provider_import)
if attr_import:
result.append(attr_import)
return result
if target[PyInfo].imports:
imports.extend(provider_imports_to_attr_imports())
runfiles = target[DefaultInfo].default_runfiles
if runfiles and runfiles.files:
sources.extend([artifact_location(f) for f in runfiles.files.to_list()])
is_code_generator = True
ide_info["py_ide_info"] = struct_omit_none(
launcher = py_launcher,
python_version = _get_python_version(ctx),
sources = sources,
srcs_version = _get_python_srcs_version(ctx),
args = args,
imports = imports,
is_code_generator = is_code_generator,
)
update_sync_output_groups(output_groups, "intellij-info-py", depset([ide_info_file]))
update_sync_output_groups(output_groups, "intellij-compile-py", to_build)
update_sync_output_groups(output_groups, "intellij-resolve-py", to_build)
return True
def _collect_generated_go_sources(target, ctx, semantics):
"""Returns a depset of go source files generated by this target."""
if semantics.go.is_proto_library(target, ctx):
return semantics.go.get_proto_library_generated_srcs(target)
else:
return None
def collect_go_info(target, ctx, semantics, ide_info, ide_info_file, output_groups):
"""Updates Go-specific output groups, returns false if not a recognized Go target."""
sources = []
generated = []
cgo = False
# currently there's no Go Skylark API, with the only exception being proto_library targets
if ctx.rule.kind in [
"go_binary",
"go_library",
"go_test",
"go_source",
"go_appengine_binary",
"go_appengine_library",
"go_appengine_test",
]:
sources = [f for src in getattr(ctx.rule.attr, "srcs", []) for f in src.files.to_list()]
generated = [f for f in sources if not f.is_source]
cgo = getattr(ctx.rule.attr, "cgo", False)
elif ctx.rule.kind == "go_wrap_cc":
genfiles = target.files.to_list()
go_genfiles = [f for f in genfiles if f.basename.endswith(".go")]
if go_genfiles:
sources = go_genfiles
generated = go_genfiles
else:
# if the .go file isn't in 'files', build the .a and .x files instead
generated = genfiles
else:
generated_sources = _collect_generated_go_sources(target, ctx, semantics)
if not generated_sources:
return False
sources = generated_sources
generated = generated_sources
import_path = None
go_semantics = getattr(semantics, "go", None)
if go_semantics:
import_path = go_semantics.get_import_path(ctx)
library_labels = []
if ctx.rule.kind in ("go_test", "go_library", "go_appengine_test"):
if getattr(ctx.rule.attr, "library", None) != None:
library_labels = [stringify_label(ctx.rule.attr.library.label)]
elif getattr(ctx.rule.attr, "embed", None) != None:
for library in ctx.rule.attr.embed:
if library[IntelliJInfo].kind == "go_source" or library[IntelliJInfo].kind == "go_proto_library":
l = library[IntelliJInfo].output_groups["intellij-sources-go-outputs"].to_list()
sources += l
generated += [f for f in l if not f.is_source]
else:
library_labels.append(stringify_label(library.label))
ide_info["go_ide_info"] = struct_omit_none(
import_path = import_path,
library_labels = library_labels,
sources = [artifact_location(f) for f in sources],
cgo = cgo,
)
compile_files = target[OutputGroupInfo].compilation_outputs if hasattr(target[OutputGroupInfo], "compilation_outputs") else depset([])
compile_files = depset(generated, transitive = [compile_files])
update_sync_output_groups(output_groups, "intellij-info-go", depset([ide_info_file]))
update_sync_output_groups(output_groups, "intellij-compile-go", compile_files)
update_sync_output_groups(output_groups, "intellij-resolve-go", depset(generated))
update_sync_output_groups(output_groups, "intellij-sources-go", depset(sources))
return True
def collect_cpp_info(target, ctx, semantics, ide_info, ide_info_file, output_groups):
"""Updates C++-specific output groups, returns false if not a C++ target."""
if CcInfo not in target:
return False
# ignore cc_proto_library, attach to proto_library with aspect attached instead
if ctx.rule.kind == "cc_proto_library":
return False
# Go targets always provide CcInfo. Usually it's empty, but even if it isn't we don't handle it
if ctx.rule.kind.startswith("go_"):
return False
sources = artifacts_from_target_list_attr(ctx, "srcs")
headers = artifacts_from_target_list_attr(ctx, "hdrs")
textual_headers = artifacts_from_target_list_attr(ctx, "textual_hdrs")
target_copts = []
if hasattr(ctx.rule.attr, "copts"):
target_copts += ctx.rule.attr.copts
extra_targets = []
if hasattr(ctx.rule.attr, "additional_compiler_inputs"):
extra_targets += ctx.rule.attr.additional_compiler_inputs
if hasattr(semantics, "cc") and hasattr(semantics.cc, "get_default_copts"):
target_copts += semantics.cc.get_default_copts(ctx)
target_copts = _do_starlark_string_expansion(ctx, "copt", target_copts, extra_targets)
compilation_context = target[CcInfo].compilation_context
# Merge current compilation context with context of implementation dependencies.
if hasattr(ctx.rule.attr, "implementation_deps"):
implementation_deps = ctx.rule.attr.implementation_deps
compilation_context = cc_common.merge_compilation_contexts(
compilation_contexts =
[compilation_context] + [impl[CcInfo].compilation_context for impl in implementation_deps],
)
# external_includes available since bazel 7
external_includes = getattr(compilation_context, "external_includes", depset()).to_list()
c_info = struct_omit_none(
header = headers,
source = sources,
target_copt = target_copts,
textual_header = textual_headers,
transitive_define = compilation_context.defines.to_list(),
transitive_include_directory = compilation_context.includes.to_list(),
transitive_quote_include_directory = compilation_context.quote_includes.to_list(),
# both system and external includes are add using `-isystem`
transitive_system_include_directory = compilation_context.system_includes.to_list() + external_includes,
include_prefix = getattr(ctx.rule.attr, "include_prefix", None),
strip_include_prefix = getattr(ctx.rule.attr, "strip_include_prefix", None),
)
ide_info["c_ide_info"] = c_info
resolve_files = compilation_context.headers
# TODO(brendandouglas): target to cpp files only
compile_files = target[OutputGroupInfo].compilation_outputs if hasattr(target[OutputGroupInfo], "compilation_outputs") else depset([])
update_sync_output_groups(output_groups, "intellij-info-cpp", depset([ide_info_file]))
update_sync_output_groups(output_groups, "intellij-compile-cpp", compile_files)
update_sync_output_groups(output_groups, "intellij-resolve-cpp", resolve_files)
return True
def collect_c_toolchain_info(target, ctx, semantics, ide_info, ide_info_file, output_groups):
"""Updates cc_toolchain-relevant output groups, returns false if not a cc_toolchain target."""
# The other toolchains like the JDK might also have ToolchainInfo but it's not a C++ toolchain,
# so check kind as well.
# TODO(jvoung): We are temporarily getting info from cc_toolchain_suite
# https://github.com/bazelbuild/bazel/commit/3aedb2f6de80630f88ffb6b60795c44e351a5810
# but will switch back to cc_toolchain providing CcToolchainProvider once we migrate C++ rules
# to generic platforms and toolchains.
if ctx.rule.kind != "cc_toolchain" and ctx.rule.kind != "cc_toolchain_suite" and ctx.rule.kind != "cc_toolchain_alias":
return False
if cc_common.CcToolchainInfo not in target:
return False
# cc toolchain to access compiler flags
cpp_toolchain = target[cc_common.CcToolchainInfo]
# cpp fragment to access bazel options
cpp_fragment = ctx.fragments.cpp
copts = cpp_fragment.copts
cxxopts = cpp_fragment.cxxopts
conlyopts = cpp_fragment.conlyopts
feature_configuration = cc_common.configure_features(
ctx = ctx,
cc_toolchain = cpp_toolchain,
requested_features = ctx.features,
unsupported_features = ctx.disabled_features + UNSUPPORTED_FEATURES,
)
c_variables = cc_common.create_compile_variables(
feature_configuration = feature_configuration,
cc_toolchain = cpp_toolchain,
user_compile_flags = copts + conlyopts,
)
cpp_variables = cc_common.create_compile_variables(
feature_configuration = feature_configuration,
cc_toolchain = cpp_toolchain,
user_compile_flags = copts + cxxopts,
)
c_options = cc_common.get_memory_inefficient_command_line(
feature_configuration = feature_configuration,
action_name = ACTION_NAMES.c_compile,
variables = c_variables,
)
cpp_options = cc_common.get_memory_inefficient_command_line(
feature_configuration = feature_configuration,
action_name = ACTION_NAMES.cpp_compile,
variables = cpp_variables,
)
if (get_registry_flag(ctx, "_cpp_use_get_tool_for_action")):
c_compiler = cc_common.get_tool_for_action(
feature_configuration = feature_configuration,
action_name = ACTION_NAMES.c_compile,
)
cpp_compiler = cc_common.get_tool_for_action(
feature_configuration = feature_configuration,
action_name = ACTION_NAMES.cpp_compile,
)
else:
c_compiler = str(cpp_toolchain.compiler_executable)
cpp_compiler = str(cpp_toolchain.compiler_executable)
c_toolchain_info = struct_omit_none(
built_in_include_directory = [str(d) for d in cpp_toolchain.built_in_include_directories],
c_option = c_options,
cpp_option = cpp_options,
c_compiler = c_compiler,
cpp_compiler = cpp_compiler,
target_name = cpp_toolchain.target_gnu_system_name,
)
ide_info["c_toolchain_ide_info"] = c_toolchain_info
update_sync_output_groups(output_groups, "intellij-info-cpp", depset([ide_info_file]))
return True
def get_java_provider(target):
"""Find a provider exposing java compilation/outputs data."""
# Check for kt providers before JavaInfo. e.g. kt targets have
# JavaInfo, but their data lives in the "kt" provider and not JavaInfo.
# See https://github.com/bazelbuild/intellij/pull/1202
if hasattr(target, "kt") and hasattr(target.kt, "outputs"):
return target.kt
java_info = get_java_info(target)
if java_info:
return java_info
if hasattr(java_common, "JavaPluginInfo") and java_common.JavaPluginInfo in target:
return target[java_common.JavaPluginInfo]
return None
def _collect_generated_files(java):
"""Collects generated files from a Java target"""
if hasattr(java, "java_outputs"):
return [
(outputs.generated_class_jar, outputs.generated_source_jar)
for outputs in java.java_outputs
if outputs.generated_class_jar != None
]
# Handles Bazel versions before 5.0.0.
if (hasattr(java, "annotation_processing") and java.annotation_processing and java.annotation_processing.enabled):
return [(java.annotation_processing.class_jar, java.annotation_processing.source_jar)]
return []
def collect_java_info(target, ctx, semantics, ide_info, ide_info_file, output_groups):
"""Updates Java-specific output groups, returns false if not a Java target."""
java = get_java_provider(target)
if not java:
return False
if hasattr(java, "java_outputs") and java.java_outputs:
java_outputs = java.java_outputs
elif hasattr(java, "outputs") and java.outputs:
java_outputs = java.outputs.jars
else:
return False
java_semantics = semantics.java if hasattr(semantics, "java") else None
if java_semantics and java_semantics.skip_target(target, ctx):
return False
ide_info_files = []
sources = sources_from_target(ctx)
jars = [library_artifact(output, ctx.rule.kind) for output in java_outputs]
class_jars = [output.class_jar for output in java_outputs if output and output.class_jar]
output_jars = [jar for output in java_outputs for jar in jars_from_output(output)]
resolve_files = output_jars
compile_files = class_jars
gen_jars = []
for generated_class_jar, generated_source_jar in _collect_generated_files(java):
gen_jars.append(annotation_processing_jars(generated_class_jar, generated_source_jar))
resolve_files += [
jar
for jar in [
generated_class_jar,
generated_source_jar,
]
if jar != None and not jar.is_source
]
compile_files += [
jar
for jar in [generated_class_jar]
if jar != None and not jar.is_source
]
jdeps = None
jdeps_file = None
if java_semantics and hasattr(java_semantics, "get_filtered_jdeps"):
jdeps_file = java_semantics.get_filtered_jdeps(target)
if jdeps_file == None and hasattr(java, "outputs") and hasattr(java.outputs, "jdeps") and java.outputs.jdeps:
jdeps_file = java.outputs.jdeps
if jdeps_file:
jdeps = artifact_location(jdeps_file)
resolve_files.append(jdeps_file)
java_sources, gen_java_sources, srcjars = divide_java_sources(ctx)
if java_semantics:
srcjars = java_semantics.filter_source_jars(target, ctx, srcjars)
package_manifest = None
if java_sources:
package_manifest = build_java_package_manifest(ctx, target, java_sources, ".java-manifest")
ide_info_files.append(package_manifest)
filtered_gen_jar = None
if java_sources and (gen_java_sources or srcjars):
filtered_gen_jar, filtered_gen_resolve_files = _build_filtered_gen_jar(
ctx,
target,
java_outputs,
gen_java_sources,
srcjars,
)
resolve_files += filtered_gen_resolve_files
# Custom lint checks are incorporated as java plugins. We collect them here and register them with the IDE so that the IDE can also run the same checks.
plugin_processor_jar_files = []
if hasattr(ctx.rule.attr, "_android_lint_plugins"):
plugin_processor_jar_files += [
jar
for p in getattr(ctx.rule.attr, "_android_lint_plugins", [])
for jar in _android_lint_plugin_jars(p)
]
if hasattr(java, "annotation_processing") and java.annotation_processing and hasattr(java.annotation_processing, "processor_classpath"):
plugin_processor_jar_files += java.annotation_processing.processor_classpath.to_list()
resolve_files += plugin_processor_jar_files
plugin_processor_jars = [annotation_processing_jars(jar, None) for jar in depset(plugin_processor_jar_files).to_list()]
java_info = struct_omit_none(
filtered_gen_jar = filtered_gen_jar,
generated_jars = gen_jars,
jars = jars,
jdeps = jdeps,
main_class = getattr(ctx.rule.attr, "main_class", None),
package_manifest = artifact_location(package_manifest),
sources = sources,
test_class = getattr(ctx.rule.attr, "test_class", None),
plugin_processor_jars = plugin_processor_jars,
)
ide_info["java_ide_info"] = java_info
ide_info_files.append(ide_info_file)
update_sync_output_groups(output_groups, "intellij-info-java", depset(ide_info_files))
update_sync_output_groups(output_groups, "intellij-compile-java", depset(compile_files))
update_sync_output_groups(output_groups, "intellij-resolve-java", depset(resolve_files))
# also add transitive hjars + src jars, to catch implicit deps
if hasattr(java, "transitive_compile_time_jars"):
update_set_in_dict(output_groups, "intellij-resolve-java-direct-deps", java.transitive_compile_time_jars)
update_set_in_dict(output_groups, "intellij-resolve-java-direct-deps", java.transitive_source_jars)
return True
def _android_lint_plugin_jars(target):
java_info = get_java_info(target)
if java_info:
return java_info.transitive_runtime_jars.to_list()
else:
return []
def _package_manifest_file_argument(f):
artifact = artifact_location(f)
is_external = "1" if is_external_artifact(f.owner) else "0"
return artifact.root_execution_path_fragment + "," + artifact.relative_path + "," + is_external
def build_java_package_manifest(ctx, target, source_files, suffix):
"""Builds the java package manifest for the given source files."""
output = ctx.actions.declare_file(target.label.name + suffix)
args = ctx.actions.args()
args.add("--output_manifest")
args.add(output.path)
args.add_joined(
"--sources",
source_files,
join_with = ":",
map_each = _package_manifest_file_argument,
)
# Bazel has an option to put your command line args in a file, and then pass the name of that file as the only
# argument to your executable. The PackageParser supports taking args in this way, we can pass in an args file
# as "@filename".
# Bazel Persistent Workers take their input as a file that contains the argument that will be parsed and turned
# into a WorkRequest proto and read on stdin. It also wants an argument of the form "@filename". We can use the
# params file as an arg file.
# Thus if we always use a params file, we can support both persistent worker mode and local mode (regular) mode.
args.use_param_file("@%s", use_always = True)
args.set_param_file_format("multiline")
ctx.actions.run(
inputs = source_files,
outputs = [output],
executable = ctx.executable._package_parser,
arguments = [args],
mnemonic = "JavaPackageManifest",
progress_message = "Parsing java package strings for " + str(target.label),
execution_requirements = {
"supports-workers": "1",
"requires-worker-protocol": "proto",
},
)
return output
def _build_filtered_gen_jar(ctx, target, java_outputs, gen_java_sources, srcjars):
"""Filters the passed jar to contain only classes from the given manifest."""
jar_artifacts = []
source_jar_artifacts = []
for jar in java_outputs:
if jar.ijar:
jar_artifacts.append(jar.ijar)
if hasattr(jar, "source_jars") and jar.source_jars:
source_jar_artifacts.extend(_list_or_depset_to_list(jar.source_jars))
elif hasattr(jar, "source_jar") and jar.source_jar:
source_jar_artifacts.append(jar.source_jar)
if len(source_jar_artifacts) == 0 or len(jar_artifacts) == 0:
jar_artifacts.extend([jar.class_jar for jar in java_outputs if jar.class_jar])
filtered_jar = ctx.actions.declare_file(target.label.name + "-filtered-gen.jar")
filtered_source_jar = ctx.actions.declare_file(target.label.name + "-filtered-gen-src.jar")
args = []
for jar in jar_artifacts:
args += ["--filter_jar", jar.path]
for jar in source_jar_artifacts:
args += ["--filter_source_jar", jar.path]
args += ["--filtered_jar", filtered_jar.path]
args += ["--filtered_source_jar", filtered_source_jar.path]
if gen_java_sources:
for java_file in gen_java_sources:
args += ["--keep_java_file", java_file.path]
if srcjars:
for source_jar in srcjars:
args += ["--keep_source_jar", source_jar.path]
ctx.actions.run(
inputs = jar_artifacts + source_jar_artifacts + gen_java_sources + srcjars,
outputs = [filtered_jar, filtered_source_jar],
executable = ctx.executable._jar_filter,
arguments = args,
mnemonic = "JarFilter",
progress_message = "Filtering generated code for " + str(target.label),
)
output_jar = struct(
jar = artifact_location(filtered_jar),
source_jar = artifact_location(filtered_source_jar),
)
intellij_resolve_files = [filtered_jar, filtered_source_jar]
return output_jar, intellij_resolve_files
def divide_java_sources(ctx):
"""Divide sources into plain java, generated java, and srcjars."""
java_sources = []
gen_java_sources = []
srcjars = []
if hasattr(ctx.rule.attr, "srcs"):
srcs = ctx.rule.attr.srcs
for src in srcs:
for f in src.files.to_list():
if f.basename.endswith(".java"):
if f.is_source:
java_sources.append(f)
else:
gen_java_sources.append(f)
elif f.basename.endswith(".srcjar"):
srcjars.append(f)
return java_sources, gen_java_sources, srcjars
def collect_android_info(target, ctx, semantics, ide_info, ide_info_file, output_groups):
"""Updates Android-specific output groups, returns true if any android specific info was collected."""
handled = False
handled = _collect_android_ide_info(target, ctx, semantics, ide_info, ide_info_file, output_groups) or handled
handled = _collect_android_instrumentation_info(target, ctx, semantics, ide_info, ide_info_file, output_groups) or handled
handled = _collect_aar_import_info(ctx, ide_info, ide_info_file, output_groups) or handled
handled = _collect_android_sdk_info(ctx, ide_info, ide_info_file, output_groups) or handled
if handled:
# do this once do avoid adding unnecessary nesting to the depset
# (https://docs.bazel.build/versions/master/skylark/performance.html#reduce-the-number-of-calls-to-depset)
update_sync_output_groups(output_groups, "intellij-info-android", depset([ide_info_file]))
return handled
def _get_android_ide_info(target):
"""Returns the AndroidIdeInfo provider for the given target."""
if hasattr(android_common, "AndroidIdeInfo"):
return target[android_common.AndroidIdeInfo]
# Backwards compatibility: supports android struct provider
legacy_android = getattr(target, "android")
# Transform into AndroidIdeInfo form
return struct(
java_package = legacy_android.java_package,
manifest = legacy_android.manifest,
idl_source_jar = getattr(legacy_android.idl.output, "source_jar", None),
idl_class_jar = getattr(legacy_android.idl.output, "class_jar", None),
defines_android_resources = legacy_android.defines_resources,
idl_import_root = getattr(legacy_android.idl, "import_root", None),
resource_jar = legacy_android.resource_jar,
signed_apk = legacy_android.apk,
apks_under_test = legacy_android.apks_under_test,
)
def _collect_android_ide_info(target, ctx, semantics, ide_info, ide_info_file, output_groups):
"""Populates ide_info proto and intellij_resolve_android output group
Updates ide_info proto with android_ide_info, and intellij_resolve_android with android
resolve files. It returns false on android_library and android_binary targets, as this preserves
consistent functionality with the previous condition of the presence of the .android legacy
provider.
"""
if ctx.rule.kind not in ["android_library", "android_binary", "kt_android_library"]:
return False
android_semantics = semantics.android if hasattr(semantics, "android") else None
extra_ide_info = android_semantics.extra_ide_info(target, ctx) if android_semantics else {}
android = _get_android_ide_info(target)
output_jar = struct(
class_jar = android.idl_class_jar,
ijar = None,
source_jar = android.idl_source_jar,
) if android.idl_class_jar else None
resources = []
res_folders = []
resolve_files = jars_from_output(output_jar)
if hasattr(ctx.rule.attr, "resource_files"):
for artifact_path_fragments, res_files in get_res_artifacts(ctx.rule.attr.resource_files).items():
# Generate unique ArtifactLocation for resource directories.
root = to_artifact_location(*artifact_path_fragments)
resources.append(root)
# Generate aar
aar_file_name = target.label.name.replace("/", "-")
aar_file_name += "-" + str(hash(root.root_execution_path_fragment + root.relative_path + aar_file_name))
aar = ctx.actions.declare_file(aar_file_name + ".aar")
args = ctx.actions.args()
# using param file to get around argument length limitation
# the name of param file (%s) is automatically filled in by blaze
args.use_param_file("@%s")
args.set_param_file_format("multiline")
args.add("--aar", aar)
args.add("--manifest_file", android.manifest)
args.add_joined("--resources", res_files, join_with = ",")
args.add("--resource_root", root.relative_path if root.is_source else root.root_execution_path_fragment + "/" + root.relative_path)
ctx.actions.run(
outputs = [aar],
inputs = [android.manifest] + res_files,
arguments = [args],
executable = ctx.executable._create_aar,
mnemonic = "CreateAar",
progress_message = "Generating " + aar_file_name + ".aar for target " + str(target.label),
)
resolve_files.append(aar)
# Generate unique ResFolderLocation for resource files.
res_folders.append(struct_omit_none(aar = artifact_location(aar), root = root))