aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/test/java/com/google/devtools/build/lib/ideinfo/intellij_info.bzl
blob: c73e7f835bb68e34a9390053971ef8d28f2e1430 (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
# Copyright 2016 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.

# Implementaion of AndroidStudio-specific information collecting aspect.

# A map to convert rule names to a RuleIdeInfo.Kind
# Deprecated - only here for backwards compatibility with the tests
_kind_to_kind_id = {
    "android_binary": 0,
    "android_library": 1,
    "android_test": 2,
    "android_robolectric_test": 3,
    "java_library": 4,
    "java_test": 5,
    "java_import": 6,
    "java_binary": 7,
    "proto_library": 8,
    "android_sdk": 9,
    "java_plugin": 10,
    "android_resources": 11,
    "cc_library": 12,
    "cc_binary": 13,
    "cc_test": 14,
    "cc_inc_library": 15,
    "cc_toolchain": 16,
    "java_wrap_cc": 17,
}

# A map to convert JavaApiFlavor to ProtoLibraryLegacyJavaIdeInfo.ApiFlavor
_api_flavor_to_id = {
    "FLAVOR_NONE": 0,
    "FLAVOR_IMMUTABLE": 1,
    "FLAVOR_MUTABLE": 2,
    "FLAVOR_BOTH": 3,
}

_unrecognized_rule = -1

def get_kind_legacy(target, ctx):
  """ Gets kind of a rule given a target and rule context.
  """
  return _kind_to_kind_id.get(ctx.rule.kind, _unrecognized_rule)

# Compile-time dependency attributes, grouped by type.
DEPS = struct(
    label = [
        "binary_under_test",  #  From android_test
        "java_lib",  # From proto_library
        "_proto1_java_lib",  # From proto_library
        "_junit",  # From android_robolectric_test
        "_cc_toolchain",  # From C rules
        "module_target",
        "_java_toolchain",  # From java rules
    ],
    label_list = [
        "deps",
        "exports",
        "_robolectric",  # From android_robolectric_test
    ],
)

# Run-time dependency attributes, grouped by type.
RUNTIME_DEPS = struct(
    label = [
        # todo(dslomov,tomlu): resources are tricky since they are sometimes labels and sometimes label_lists.
        # "resources"
    ],
    label_list = [
        "runtime_deps",
    ],
)

# All dependency attributes along which the aspect propagates, grouped by type.
ALL_DEPS = struct(
    label = DEPS.label + RUNTIME_DEPS.label,
    label_list = DEPS.label_list + RUNTIME_DEPS.label_list,
)

def struct_omit_none(**kwargs):
    """A replacement for standard `struct` function that omits the fields with None value."""
    d = {name: kwargs[name] for name in kwargs if kwargs[name] != None}
    return struct(**d)

def artifact_location(file):
  """Creates an ArtifactLocation proto from a File."""
  if file == None:
    return None
  return struct_omit_none(
      relative_path = file.short_path,
      is_source = file.is_source,
      root_execution_path_fragment = file.root.path if not file.is_source else None
  )

def source_directory_tuple(resource_file):
  """Creates a tuple of (source directory, is_source, root execution path)."""
  return (
      str(android_common.resource_source_directory(resource_file)),
      resource_file.is_source,
      resource_file.root.path if not resource_file.is_source else None
  )

def all_unique_source_directories(resources):
  """Builds a list of ArtifactLocation protos.

  This is done for all source directories for a list of Android resources.
  """
  # Sets can contain tuples, but cannot contain structs.
  # Use set of tuples to unquify source directories.
  source_directory_tuples = set([source_directory_tuple(file) for file in resources])
  return [struct_omit_none(relative_path = relative_path,
                           is_source = is_source,
                           root_execution_path_fragment = root_execution_path_fragment)
          for (relative_path, is_source, root_execution_path_fragment) in source_directory_tuples]

def build_file_artifact_location(build_file_path):
  """Creates an ArtifactLocation proto representing a location of a given BUILD file."""
  return struct(
      relative_path = build_file_path,
      is_source = True,
  )

def library_artifact(java_output):
  """Creates a LibraryArtifact representing a given java_output."""
  if java_output == None or java_output.class_jar == None:
    return None
  return struct_omit_none(
        jar = artifact_location(java_output.class_jar),
        interface_jar = artifact_location(java_output.ijar),
        source_jar = artifact_location(java_output.source_jar),
  )

def annotation_processing_jars(annotation_processing):
  """Creates a LibraryArtifact representing Java annotation processing jars."""
  return struct_omit_none(
        jar = artifact_location(annotation_processing.class_jar),
        source_jar = artifact_location(annotation_processing.source_jar),
  )

def jars_from_output(output):
  """Collect jars for ide-resolve-files from Java output."""
  if output == None:
    return []
  return [jar
          for jar in [output.class_jar, output.ijar, output.source_jar]
          if jar != None and not jar.is_source]

def build_c_rule_ide_info(target, ctx):
  """Build CRuleIdeInfo.

  Returns a pair of (CRuleIdeInfo proto, a set of ide-resolve-files).
  (or (None, empty set) if the rule is not a C rule).
  """
  if not hasattr(target, "cc"):
    return (None, set())

  sources = getSourcesFromRule(ctx)

  rule_includes = []
  if hasattr(ctx.rule.attr, "includes"):
    rule_includes = ctx.rule.attr.includes
  rule_defines = []
  if hasattr(ctx.rule.attr, "defines"):
    rule_defines = ctx.rule.attr.defines
  rule_copts = []
  if hasattr(ctx.rule.attr, "copts"):
    rule_copts = ctx.rule.attr.copts

  cc_provider = target.cc

  ide_resolve_files = set()

  return (struct_omit_none(
                  source = sources,
                  rule_include = rule_includes,
                  rule_define = rule_defines,
                  rule_copt = rule_copts,
                  transitive_include_directory = cc_provider.include_directories,
                  transitive_quote_include_directory = cc_provider.quote_include_directories,
                  transitive_define = cc_provider.defines,
                  transitive_system_include_directory = cc_provider.system_include_directories
         ),
         ide_resolve_files)

def build_c_toolchain_ide_info(target, ctx):
  """Build CToolchainIdeInfo.

  Returns a pair of (CToolchainIdeInfo proto, a set of ide-resolve-files).
  (or (None, empty set) if the rule is not a cc_toolchain rule).
  """

  if ctx.rule.kind != "cc_toolchain":
    return (None, set())

  # This should exist because we requested it in our aspect definition.
  cc_fragment = ctx.fragments.cpp

  return (struct_omit_none(
                  target_name = cc_fragment.target_gnu_system_name,
                  base_compiler_option = cc_fragment.compiler_options(ctx.features),
                  c_option = cc_fragment.c_options,
                  cpp_option = cc_fragment.cxx_options(ctx.features),
                  link_option = cc_fragment.link_options,
                  unfiltered_compiler_option = cc_fragment.unfiltered_compiler_options(ctx.features),
                  preprocessor_executable =
                      replaceEmptyPathWithDot(str(cc_fragment.preprocessor_executable)),
                  cpp_executable = str(cc_fragment.compiler_executable),
                  built_in_include_directory = [str(d)
                                                for d in cc_fragment.built_in_include_directories]
         ),
         set())

# TODO(salguarnieri) Remove once skylark provides the path safe string from a PathFragment.
def replaceEmptyPathWithDot(pathString):
  return "." if len(pathString) == 0 else pathString

def getSourcesFromRule(context):
  """
  Get the list of sources from a rule as artifact locations.

  Returns the list of sources as artifact locations for a rule or an empty list if no sources are
  present.
  """

  if hasattr(context.rule.attr, "srcs"):
    return [artifact_location(file)
            for src in context.rule.attr.srcs
            for file in src.files]
  return []

def build_java_rule_ide_info(target, ctx):
  """
  Build JavaRuleIdeInfo.

  Returns a pair of (JavaRuleIdeInfo proto, a set of ide-resolve-files).
  (or (None, empty set) if the rule is not Java rule).
  """
  if not hasattr(target, "java") or ctx.rule.kind == "proto_library":
    return (None, set())

  sources = getSourcesFromRule(ctx)

  jars = [library_artifact(output) for output in target.java.outputs.jars]
  ide_resolve_files = set([jar
       for output in target.java.outputs.jars
       for jar in jars_from_output(output)])

  gen_jars = []
  if target.java.annotation_processing and target.java.annotation_processing.enabled:
    gen_jars = [annotation_processing_jars(target.java.annotation_processing)]
    ide_resolve_files = ide_resolve_files | set([ jar
        for jar in [target.java.annotation_processing.class_jar,
                    target.java.annotation_processing.source_jar]
        if jar != None and not jar.is_source])

  jdeps = artifact_location(target.java.outputs.jdeps)

  return (struct_omit_none(
                 sources = sources,
                 jars = jars,
                 jdeps = jdeps,
                 generated_jars = gen_jars
          ),
          ide_resolve_files)

def build_android_rule_ide_info(target, ctx):
  """
  Build AndroidRuleIdeInfo.

  Returns a pair of (AndroidRuleIdeInfo proto, a set of ide-resolve-files).
  (or (None, empty set) if the rule is not Android rule).
  """
  if not hasattr(target, "android"):
    return (None, set())
  ide_resolve_files = set(jars_from_output(target.android.idl.output))
  return (struct_omit_none(
            java_package = target.android.java_package,
            manifest = artifact_location(target.android.manifest),
            apk = artifact_location(target.android.apk),
            dependency_apk = [artifact_location(apk) for apk in target.android.apks_under_test],
            has_idl_sources = target.android.idl.output != None,
            idl_jar = library_artifact(target.android.idl.output),
            generate_resource_class = target.android.defines_resources,
            resources = all_unique_source_directories(target.android.resources),
        ),
        ide_resolve_files)

def build_test_info(target, ctx):
  """Build TestInfo"""
  if not is_test_rule(ctx):
    return None
  return struct_omit_none(
           size = ctx.rule.attr.size,
         )

def is_test_rule(ctx):
  kind_string = ctx.rule.kind
  return kind_string.endswith("_test")

def build_proto_library_legacy_java_ide_info(target, ctx):
  """Build ProtoLibraryLegacyJavaIdeInfo."""
  if not hasattr(target, "proto_legacy_java"):
    return None
  proto_info = target.proto_legacy_java.legacy_info
  return struct_omit_none(
    api_version = proto_info.api_version,
    api_flavor = _api_flavor_to_id[proto_info.api_flavor],
    jars1 = [library_artifact(output) for output in proto_info.jars1],
    jars_mutable = [library_artifact(output) for output in proto_info.jars_mutable],
    jars_immutable = [library_artifact(output) for output in proto_info.jars_immutable],
  )

def build_java_toolchain_ide_info(target):
  """Build JavaToolchainIdeInfo."""
  if not hasattr(target, "java_toolchain"):
    return None
  toolchain_info = target.java_toolchain
  return struct_omit_none(
      source_version = toolchain_info.source_version,
      target_version = toolchain_info.target_version,
  )

def collect_labels(rule_attrs, attrs):
  """
  Collect labels from attribute values.

  Assuming that values of attributes from attr_list in rule_atrs
  are label lists, collect a set of string representation of those labels.
  """
  return set([str(dep.label)
      for attr_name in attrs.label_list
      if hasattr(rule_attrs, attr_name)
      for dep in getattr(rule_attrs, attr_name)]) | \
         set([str(getattr(rule_attrs, attr_name).label)
      for attr_name in attrs.label
      if hasattr(rule_attrs, attr_name)])

def collect_export_deps(rule_attrs):
  """Build a union of all export dependencies."""
  result = set()
  for attr_name in DEPS.label_list:
    if hasattr(rule_attrs, attr_name):
      for dep in getattr(rule_attrs, attr_name):
        result = result | dep.export_deps
  for attr_name in DEPS.label:
    if hasattr(rule_attrs, attr_name):
      dep = getattr(rule_attrs, attr_name)
      result = result | dep.export_deps

  return result

def _aspect_impl(target, ctx):
  """Aspect implementation function."""
  kind_legacy = get_kind_legacy(target, ctx)
  kind_string = ctx.rule.kind
  rule_attrs = ctx.rule.attr

  # Collect transitive values
  compiletime_deps = collect_labels(rule_attrs, DEPS) | collect_export_deps(rule_attrs)
  runtime_deps = collect_labels(rule_attrs, RUNTIME_DEPS)

  ide_info_text = set()
  ide_resolve_files = set()
  ide_infos = []

  for attr_name in ALL_DEPS.label_list:
    if hasattr(rule_attrs, attr_name):
      for dep in getattr(rule_attrs, attr_name):
        ide_info_text = ide_info_text | dep.intellij_info_files.ide_info_text
        ide_resolve_files = ide_resolve_files | dep.intellij_info_files.ide_resolve_files
        ide_infos += dep.ide_infos

  for attr_name in ALL_DEPS.label:
    if hasattr(rule_attrs, attr_name):
      dep = getattr(rule_attrs, attr_name)
      ide_info_text = ide_info_text | dep.intellij_info_files.ide_info_text
      ide_resolve_files = ide_resolve_files | dep.intellij_info_files.ide_resolve_files


  # Collect C-specific information
  (c_rule_ide_info, c_ide_resolve_files) = build_c_rule_ide_info(target, ctx)
  ide_resolve_files = ide_resolve_files | c_ide_resolve_files

  (c_toolchain_ide_info, c_toolchain_ide_resolve_files) = build_c_toolchain_ide_info(target, ctx)
  ide_resolve_files = ide_resolve_files | c_toolchain_ide_resolve_files

  # Collect Java-specific information
  (java_rule_ide_info, java_ide_resolve_files) = build_java_rule_ide_info(target, ctx)
  ide_resolve_files = ide_resolve_files | java_ide_resolve_files

  # Collect Android-specific information
  (android_rule_ide_info, android_ide_resolve_files) = build_android_rule_ide_info(target, ctx)
  ide_resolve_files = ide_resolve_files | android_ide_resolve_files

  proto_library_legacy_java_ide_info = build_proto_library_legacy_java_ide_info(target, ctx)

  java_toolchain_ide_info = build_java_toolchain_ide_info(target)

  # Collect test info
  test_info = build_test_info(target, ctx)

  # Collect information about exports.
  export_deps = set()
  if hasattr(target, "java"):
    export_deps = set([str(l) for l in target.java.transitive_exports])
    # Empty android libraries export all their dependencies.
    if ctx.rule.kind == "android_library" and \
            (not hasattr(rule_attrs, "src") or not ctx.rule.attr.src):
      export_deps = export_deps | compiletime_deps

  # Build RuleIdeInfo proto
  info = struct_omit_none(
      label = str(target.label),
      kind = kind_legacy if kind_legacy != _unrecognized_rule else None,
      kind_string = kind_string,
      dependencies = list(compiletime_deps),
      runtime_deps = list(runtime_deps),
      build_file_artifact_location = build_file_artifact_location(ctx.build_file_path),
      c_rule_ide_info = c_rule_ide_info,
      c_toolchain_ide_info = c_toolchain_ide_info,
      java_rule_ide_info = java_rule_ide_info,
      android_rule_ide_info = android_rule_ide_info,
      tags = ctx.rule.attr.tags,
      test_info = test_info,
      proto_library_legacy_java_ide_info = proto_library_legacy_java_ide_info,
      java_toolchain_ide_info = java_toolchain_ide_info,
  )

  # Output the ide information file.
  output = ctx.new_file(target.label.name + ".intellij-build.txt")
  ctx.file_action(output, info.to_proto())
  ide_info_text += set([output])
  ide_infos += [info]

  # Return providers.
  return struct(
      output_groups = {
        "ide-info-text" : ide_info_text,
        "ide-resolve" : ide_resolve_files,
      },
      intellij_info_files = struct(
        ide_info_text = ide_info_text,
        ide_resolve_files = ide_resolve_files,
      ),
      export_deps = export_deps,
      ide_infos = ide_infos,
    )

intellij_info_aspect = aspect(
    attr_aspects = ALL_DEPS.label + ALL_DEPS.label_list,
    fragments = ["cpp"],
    implementation = _aspect_impl,
)