Repository navigation
Expand file tree
/
Copy pathcompile.bzl
More file actions
2167 lines (1897 loc) · 78.8 KB
/
Copy pathcompile.bzl
File metadata and controls
2167 lines (1897 loc) · 78.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under both the MIT license found in the
# LICENSE-MIT file in the root directory of this source tree and the Apache
# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
# of this source tree.
load("@prelude//:paths.bzl", "paths")
load("@prelude//cxx:cxx_context.bzl", "get_cxx_toolchain_info")
load(
"@prelude//cxx:preprocessor.bzl",
"CPreprocessor",
"CPreprocessorInfo",
"CPreprocessorTSet",
"cxx_inherited_preprocessor_infos",
)
load(
"@prelude//linking:link_info.bzl",
"LinkStyle",
"MergedLinkInfo",
"SharedLibLinkable",
"get_link_args_for_strategy",
"to_link_strategy",
"unpack_link_args",
)
load("@prelude//utils:argfile.bzl", "argfile", "at_argfile")
load("@prelude//utils:arglike.bzl", "ArgLike")
load("@prelude//utils:graph_utils.bzl", "post_order_traversal")
load("@prelude//utils:strings.bzl", "strip_prefix")
load("@prelude//utils:utils.bzl", "dedupe_by_value")
load(
":library_info.bzl",
"ExtraLibraryInfo",
"HaskellLibraryInfo",
"HaskellLibraryInfoTSet",
"HaskellLibraryProvider",
"get_libname",
)
load(
":link_info.bzl",
"GhcLinkableInfo",
"HaskellLinkGroupInfo",
"HaskellLinkGroupProvider",
"HaskellLinkInfo",
"get_link_infos_from_extra_lib_info",
"make_extra_libraries_tset",
"traverse_extra_libraries",
)
load(
":toolchain.bzl",
"DynamicHaskellToolchainPackageDbInfo",
"HaskellToolchainInfo",
"HaskellToolchainLibrary",
"HaskellToolchainPackageDbTSet",
"augment_toolchain_package_db",
)
load(
":util.bzl",
"attr_deps",
"attr_deps_haskell_lib_infos",
"attr_deps_haskell_link_group_infos",
"attr_deps_haskell_link_infos",
"attr_deps_haskell_toolchain_libraries",
"check_is_worker_execute",
"decompose_main",
"get_artifact_suffix",
"is_haskell_boot",
"is_haskell_src",
"make_haskell_names_from_label",
"md_module_mapping",
"output_extensions",
"src_to_module_name",
"srcs_to_pairs",
)
CompiledModuleInfo = provider(fields = {
"name": provider_field(str),
"abi": provider_field(Artifact | None),
"interfaces": provider_field(list[Artifact]),
"hie_files": provider_field(list[Artifact]),
# TODO[AH] track this module's package-name/id & package-db instead.
"db_deps": provider_field(list[Artifact]),
"package": provider_field(str),
})
# Module dependency graph transitive sets including package deps as leaves
ModGraphTSet = transitive_set()
GraphInfo = record(
graph = dict[str, list[str]], # `dict[modname, list[modname]]`
graph_set = dict[str, ModGraphTSet],
)
ArtifactOutputMap = record(
outputs = dict[Artifact, OutputArtifact],
)
def _compiled_module_project_as_abi(mod: CompiledModuleInfo) -> cmd_args:
if mod.abi:
return cmd_args(mod.abi)
else:
return cmd_args()
def _compiled_module_project_as_interfaces(mod: CompiledModuleInfo) -> cmd_args:
return cmd_args(mod.interfaces)
def _compiled_module_project_as_hie_files(mod: CompiledModuleInfo) -> cmd_args:
return cmd_args(mod.hie_files)
def _compiled_module_reduce_as_packagedb_deps(children: list[dict[Artifact, None]], mod: CompiledModuleInfo | None) -> dict[Artifact, None]:
# TODO[AH] is there a better way to avoid duplicate package-dbs?
# Using a projection instead would produce duplicates.
result = {db: None for db in mod.db_deps} if mod else {}
for child in children:
result.update(child)
return result
CompiledModuleTSet = transitive_set(
args_projections = {
"abi": _compiled_module_project_as_abi,
"interfaces": _compiled_module_project_as_interfaces,
"hie_files": _compiled_module_project_as_hie_files,
},
reductions = {
"packagedb_deps": _compiled_module_reduce_as_packagedb_deps,
},
)
DynamicCompileResultInfo = provider(fields = {
"modules": dict[str, CompiledModuleTSet],
})
# The type of the return value of the `_compile()` function.
CompileResultInfo = record(
objects = field(list[Artifact]),
extra_objects = field(list[Artifact]),
interfaces = field(list[Artifact]),
extra_interfaces = field(list[Artifact]),
hie = field(list[Artifact]),
stubs = field(Artifact),
hashes = field(list[Artifact]),
producing_indices = field(bool),
module_tsets = field(DynamicValue),
)
PackagesInfo = record(
exposed_package_args = cmd_args,
packagedb_args = cmd_args,
local_packagedb_args = cmd_args,
extra_libs_args = cmd_args,
transitive_deps = field(HaskellLibraryInfoTSet),
)
# A record that holds module compilation results.
# NOTE: extra_interfaces and extra_objects are needed to hold
# dyn_hi/dyn_o artifacts built with static build. Those files
# are needed for compiling modules with TH for one-shot mode,
# unfortunately.
_Module = record(
name = field(str),
source = field(Artifact),
interfaces = field(list[Artifact]),
extra_interfaces = field(list[Artifact]),
hash = field(Artifact | None),
objects = field(list[Artifact]),
extra_objects = field(list[Artifact]),
hie_files = field(list[Artifact]),
stub_dir = field(Artifact | None),
prefix_dir = field(str),
)
def _get_module_outputs(
module: _Module,
outputs: ArtifactOutputMap) -> list[OutputArtifact]:
outputs_dict = outputs.outputs
objects = [outputs_dict[obj] for obj in module.objects]
extra_objects = [outputs_dict[obj] for obj in module.extra_objects]
his = [outputs_dict[hi] for hi in module.interfaces]
extra_his = [outputs_dict[hi] for hi in module.extra_interfaces]
hies = [outputs_dict[hie] for hie in module.hie_files]
return objects + extra_objects + his + extra_his + hies
_DynamicDoCompileOptions = record(
artifact_suffix = str,
compiler_flags = list[typing.Any], # Arguments.
ghc_rts_flags = list[typing.Any], # Arguments.
deps = list[Dependency],
direct_extra_libs = list[Dependency],
direct_deps_info = list[HaskellLibraryInfoTSet],
direct_deps_link_info = list[HaskellLinkInfo],
haskell_direct_deps_lib_infos = list[HaskellLibraryInfo],
enable_haddock = bool,
enable_profiling = bool,
external_tool_paths = list[RunInfo],
ghc_wrapper = RunInfo,
haskell_toolchain = HaskellToolchainInfo,
linker_info = typing.Any,
label = Label,
link_style = LinkStyle,
link_args = ArgLike,
main = str | None,
md_file = Artifact,
modules = dict[str, _Module],
pkgname = str,
sources = list[typing.Any], # Source.
sources_deps = dict[typing.Any, list[typing.Any]], # Source -> list[Source].
srcs_envs = dict[typing.Any, dict[str, typing.Any]], # Source -> (str -> Argument).
toolchain_deps_by_name = dict[str, None],
worker = WorkerInfo | None,
allow_worker = bool,
is_worker_execute = bool,
allow_cache_upload = bool,
link_group_libs = list[HaskellLinkGroupInfo],
# GHC plugin flags applied to all modules in the unit (from `plugins` attr).
# These flags will contain `-package-db`, `-plugin-package`,
# `-fplugin-opt=...`, etc
unit_plugin_flags = field(cmd_args | None, default = None),
# Per-source plugin flags (from `srcs_plugins` attr). Source -> cmd_args.
srcs_plugin_flags = field(dict[typing.Any, cmd_args], default = {}),
# Per-source plugin tool paths (from `srcs_plugins` attr). Source -> list[RunInfo].
srcs_plugin_tool_paths = field(dict[typing.Any, typing.Any], default = {}),
# Toolchain library names required by plugins (from `plugins` attr) that
# need to be added to the GHC command line. These are not necessarily the
# same as the toolchain libraries required by the unit itself, since it's
# possible that plugins require additional libraries that the unit doesn't
# directly depend on.
plugin_toolchain_deps = field(list[str], default = []),
)
def _strip_prefix(prefix: str, s: str) -> str:
stripped = strip_prefix(prefix, s)
return stripped if stripped != None else s
def _modules_by_name(
ctx: AnalysisContext,
*,
sources: list[Artifact],
is_worker_execute: bool,
link_style: LinkStyle,
enable_profiling: bool,
suffix: str,
module_prefix: str | None,
is_haskell_binary: bool,
src_main: Artifact | None) -> dict[str, _Module]:
modules = {}
predefined_name_map = {}
if is_haskell_binary and src_main:
if ctx.attrs.main:
(main_module, _main_function) = decompose_main(ctx.attrs.main)
else:
main_module = "Main"
predefined_name_map[src_main.short_path] = main_module
main_path = main_module.replace(".", "/")
else:
main_module = None
main_path = None
osuf, hisuf = output_extensions(link_style, enable_profiling)
for src in sources:
bootsuf = ""
if is_haskell_boot(src.short_path):
bootsuf = "-boot"
elif not is_haskell_src(src.short_path):
continue
module_name = src_to_module_name(src.short_path, predefined_name_map) + bootsuf
if module_name == main_module:
interface_path = main_path + "." + hisuf
object_path = main_path + "." + osuf
hie_path = main_path + ".hie"
else:
if module_prefix:
short_path_stripped = module_prefix.replace(".", "/") + "/" + src.short_path
interface_path = paths.replace_extension(short_path_stripped, "." + hisuf + bootsuf)
module_name = "{}.{}".format(module_prefix, module_name)
else:
s = src.short_path
for prefix in ctx.attrs.strip_prefix:
s1 = strip_prefix(prefix, src.short_path)
if s1 != None:
module_name = _strip_prefix(".", _strip_prefix(prefix.replace("/", "."), module_name))
s = s1
break
short_path_stripped = _strip_prefix("/", s)
interface_path = paths.replace_extension(short_path_stripped, "." + hisuf + bootsuf)
object_path = paths.replace_extension(short_path_stripped, "." + osuf + bootsuf)
hie_path = paths.replace_extension(short_path_stripped, ".hie")
interface = ctx.actions.declare_output("mod-" + suffix, interface_path)
interfaces = [interface]
object = ctx.actions.declare_output("mod-" + suffix, object_path)
objects = [object]
hie_file = ctx.actions.declare_output("mod-" + suffix, hie_path)
hie_files = [hie_file]
if ctx.attrs.incremental:
hash = ctx.actions.declare_output("mod-" + suffix, interface_path + ".hash")
else:
hash = None
if link_style in [LinkStyle("static"), LinkStyle("static_pic")] and not is_worker_execute:
dyn_osuf, dyn_hisuf = output_extensions(LinkStyle("shared"), enable_profiling)
if module_name == main_module:
extra_interface_path = main_path + "." + dyn_hisuf
extra_object_path = main_path + "." + dyn_osuf
else:
extra_interface_path = paths.replace_extension(short_path_stripped, "." + dyn_hisuf + bootsuf)
extra_object_path = paths.replace_extension(short_path_stripped, "." + dyn_osuf + bootsuf)
extra_interface = ctx.actions.declare_output("mod-" + suffix, extra_interface_path)
extra_interfaces = [extra_interface]
extra_object = ctx.actions.declare_output("mod-" + suffix, extra_object_path)
extra_objects = [extra_object]
else:
extra_interfaces = []
extra_objects = []
if ctx.attrs.incremental:
if bootsuf == "":
stub_dir = ctx.actions.declare_output("stub-" + suffix + "-" + module_name, dir = True)
else:
stub_dir = None
else:
stub_dir = None
prefix_dir = "mod-" + suffix
modules[module_name] = _Module(
name = module_name,
source = src,
interfaces = interfaces,
extra_interfaces = extra_interfaces,
hash = hash,
objects = objects,
extra_objects = extra_objects,
hie_files = hie_files,
stub_dir = stub_dir,
prefix_dir = prefix_dir,
)
return modules
# Collect the metadata outputs of the transitive closure of the current unit's dependencies.
def transitive_metadata(actions: AnalysisActions, pkgname: str, packages_info: PackagesInfo) -> Artifact:
dep_units_file = actions.declare_output("dep-units-{}.json".format(pkgname))
dep_units = reversed(packages_info.transitive_deps.project_as_json("dep_units", ordering = "topological").traverse())
actions.write_json(dep_units_file, dep_units, pretty = True)
return dep_units_file
# Static variant of the dependency unit list for the persistent worker's metadata calculation.
def direct_metadata_static(actions: AnalysisActions, pkgname: str, libs: list[HaskellLibraryInfo]) -> cmd_args:
dep_units_file = actions.declare_output("dep-units-static-{}.json".format(pkgname))
dep_units = [struct(name = lib.name, build_plan = lib.skeleton) for lib in libs]
return cmd_args(
actions.write_json(dep_units_file, dep_units, with_inputs = True, pretty = True),
prepend = "--dep-units-static",
)
def add_output_dirs(args: cmd_args, output_dir: cmd_args):
for dir in ["o", "hi", "hie", "dump"]:
args.add("-{}dir".format(dir), output_dir)
UnitParams = record(
name = field(str),
link_style = field(LinkStyle),
enable_profiling = field(bool),
main = field(None | str),
enable_haddock = field(bool),
external_tool_paths = field(list[RunInfo]),
artifact_suffix = field(str),
haskell_toolchain = field(HaskellToolchainInfo),
compiler_flags = field(list[str | ResolvedStringWithMacros]),
is_worker_execute = field(bool),
# GHC plugin flags applied to all modules in the unit.
plugin_flags = field(cmd_args | None, default = None),
)
def _add_dynamic_too_if_required(is_worker_execute: bool, link_style: LinkStyle, args: cmd_args) -> bool:
if link_style in [LinkStyle("static_pic"), LinkStyle("static")] and not is_worker_execute:
args.add("-dynamic-too")
return True
else:
return False
# Assemble GHC arguments that are specific to a given unit, but not to a module.
# Used for the metadata step as a basis for oneshot mode and as the full argument list for the make mode worker.
# The worker also stores these in the metadata JSON in order to restore the unit state from cache after restarting.
# In oneshot mode, the compile step also uses these arguments.
def unit_ghc_args(actions: AnalysisActions, arg: UnitParams) -> cmd_args:
args = cmd_args(
"-no-link",
"-i",
"-j",
"-hide-all-packages",
"-fwrite-ide-info",
"-package-env=-",
)
args.add(arg.haskell_toolchain.compiler_flags)
# Plugin flags come before compiler_flags so that user-provided flags
# appear later on the GHC command line and can override earlier defaults.
if arg.plugin_flags != None:
args.add(arg.plugin_flags)
args.add(arg.compiler_flags)
args.add("-this-unit-id", arg.name)
if arg.enable_profiling:
args.add("-prof")
if arg.link_style == LinkStyle("shared"):
args.add("-dynamic", "-fPIC")
elif arg.link_style == LinkStyle("static_pic"):
args.add("-fPIC", "-fexternal-dynamic-refs")
_add_dynamic_too_if_required(arg.is_worker_execute, arg.link_style, args)
args.add("-fbyte-code-and-object-code")
osuf, hisuf = output_extensions(arg.link_style, arg.enable_profiling)
args.add("-osuf", osuf, "-hisuf", hisuf)
if arg.main != None:
args.add(["-main-is", arg.main])
if arg.enable_haddock:
args.add("-haddock")
return args
def unit_buck2_args(actions: AnalysisActions, arg: UnitParams) -> cmd_args:
args = cmd_args()
args.add(cmd_args(
arg.external_tool_paths,
format = "--bin-exe={}",
))
return args
MetadataUnitParams = record(
unit = field(UnitParams),
toolchain_libs = field(list[str]),
deps = field(list[Dependency]),
direct_extra_libs = field(list[Dependency]),
is_binary = field(bool),
)
def metadata_unit_args(
actions: AnalysisActions,
arg: MetadataUnitParams,
packages_info: PackagesInfo,
output: OutputArtifact) -> (cmd_args, cmd_args):
# Configure all output directories to use e.g. `mod-shared` next to the metadata file (`output`).
output_dir = cmd_args(
[cmd_args(output, ignore_artifacts = True, parent = 1), "mod-" + arg.unit.artifact_suffix],
delimiter = "/",
)
ghc_args = unit_ghc_args(actions, arg.unit)
add_output_dirs(ghc_args, output_dir)
package_flag = _package_flag(arg.unit.haskell_toolchain)
ghc_args.add(cmd_args(arg.toolchain_libs, prepend = package_flag))
if not arg.unit.is_worker_execute:
ghc_args.add(cmd_args(packages_info.local_packagedb_args, prepend = "-package-db"))
ghc_args.add(cmd_args(packages_info.exposed_package_args, hidden = packages_info.local_packagedb_args))
else:
# Real local package dbs are not inputs because the worker resolves local package flags against the db
# built from --dep-units-static data.
ghc_args.add(packages_info.exposed_package_args)
ghc_args.add(cmd_args(packages_info.packagedb_args, prepend = "-package-db"))
ghc_args.add("-fprefer-byte-code")
ghc_args.add(packages_info.extra_libs_args)
buck2_args = unit_buck2_args(actions, arg.unit)
return (ghc_args, buck2_args)
MetadataParams = record(
unit = field(MetadataUnitParams),
direct_deps_link_info = field(list[HaskellLinkInfo]),
haskell_direct_deps_lib_infos = field(list[HaskellLibraryInfo]),
md_gen = field(RunInfo),
sources = field(list[Artifact]),
strip_prefix = field(str),
suffix = field(str),
worker = field(None | WorkerInfo),
allow_worker = field(bool),
allow_cache_upload = field(bool),
label = field(Label),
incremental = field(bool),
linker_info = field(typing.Any),
)
def _dynamic_target_metadata_impl(
actions: AnalysisActions,
output: OutputArtifact,
arg: MetadataParams,
pkg_deps: None | ResolvedDynamicValue) -> list[Provider]:
munit = arg.unit
unit = munit.unit
haskell_toolchain = unit.haskell_toolchain
is_worker_execute = arg.unit.unit.is_worker_execute
# Add -package-db and -package/-expose-package flags for each Haskell
# library dependency.
packages_info = get_packages_info(
actions,
arg.label,
munit.deps,
munit.direct_extra_libs,
arg.direct_deps_link_info,
haskell_toolchain,
arg.linker_info,
arg.haskell_direct_deps_lib_infos,
unit.link_style,
specify_pkg_version = False,
enable_profiling = unit.enable_profiling,
use_empty_lib = True,
for_deps = True,
pkg_deps = pkg_deps,
is_worker_execute = is_worker_execute,
)
package_flag = _package_flag(haskell_toolchain)
(ghc_args, buck2_args) = metadata_unit_args(actions, munit, packages_info, output)
buck_args_file = argfile(
actions = actions,
name = "haskell_metadata_buck2_{}.args".format(unit.name),
args = buck2_args,
allow_args = True,
)
if is_worker_execute:
makefile = actions.declare_output(unit.name + ".depends.make")
ghc_args.add("-include-pkg-deps")
ghc_args.add("-dep-json", cmd_args(output, ignore_artifacts = True))
ghc_args.add("-dep-makefile", cmd_args(makefile, ignore_artifacts = True))
ghc_args.add(cmd_args(arg.sources))
ghc_args_file = argfile(
actions = actions,
name = "haskell_metadata_ghc_{}.args".format(unit.name),
args = ghc_args,
allow_args = True,
)
if is_worker_execute:
md_args = cmd_args()
md_args.add("-M")
md_args.add("--ghc-dir", haskell_toolchain.ghc_dir)
add_worker_args(haskell_toolchain, md_args, unit.name)
md_args.add(buck2_args)
# Specifying this activates the new build plan logic
md_args.add("--build-plan", cmd_args(output, ignore_artifacts = True))
md_args.add("--fields", "exposed_modules,module_graph,package_deps,th_modules,cache")
md_args.add(direct_metadata_static(actions, unit.name, arg.haskell_direct_deps_lib_infos))
md_args.add("--unit", unit.name)
if munit.is_binary:
md_args.add("--unit-is-binary")
md_args.add("--unit-buck-args-path", buck_args_file)
md_args.add("--dep-units-path", transitive_metadata(actions, unit.name, packages_info))
md_args.add(cmd_args(ghc_args_file, prepend = "--ghc-args", hidden = [output, makefile.as_output()]))
actions.run(
md_args,
category = "haskell_metadata",
identifier = arg.suffix if arg.suffix else None,
exe = WorkerRunInfo(worker = arg.worker),
allow_cache_upload = arg.allow_cache_upload,
)
else:
md_args = cmd_args()
md_args.add("--ghc", haskell_toolchain.compiler)
md_args.add(cmd_args(ghc_args, format = "--ghc-arg={}"))
md_args.add(cmd_args(arg.sources, format = "--source={}"))
md_args.add("--source-prefix", arg.strip_prefix)
md_args.add("--output", output)
md_args.add(buck2_args)
md_args.add("--unit-buck-args", buck_args_file)
md_args.add("--unit-args", ghc_args_file)
# We won't need to look at the ghc argsfile later, but the user might!
md_args.add("--use-ghc-args-file-at", actions.declare_output("ghc-args").as_output())
md_args_outer = cmd_args(arg.md_gen)
md_args_outer.add(at_argfile(
actions = actions,
name = "dynamic_target_metadata_args",
args = md_args,
allow_args = True,
))
actions.run(
md_args_outer,
category = "haskell_metadata",
identifier = arg.suffix if arg.suffix else None,
allow_cache_upload = arg.allow_cache_upload,
)
return []
_dynamic_target_metadata = dynamic_actions(
impl = _dynamic_target_metadata_impl,
attrs = {
"output": dynattrs.output(),
"arg": dynattrs.value(MetadataParams),
"pkg_deps": dynattrs.option(dynattrs.dynamic_value()),
},
)
def target_metadata(
ctx: AnalysisContext,
*,
link_style: LinkStyle,
enable_profiling: bool,
enable_haddock: bool,
main: None | str,
is_binary: bool,
sources: list[Artifact],
worker: WorkerInfo | None) -> Artifact:
prof_suffix = "-prof" if enable_profiling else ""
link_suffix = "-" + link_style.value
md_file = ctx.actions.declare_output(ctx.label.name + link_suffix + prof_suffix + ".md.json")
md_gen = ctx.attrs._generate_target_metadata[RunInfo]
libprefix = repr(ctx.label.path).replace("//", "_").replace("/", "_")
if getattr(ctx.attrs, "use_same_package_name", None): # haskell_library case
(pkgname, libname) = make_haskell_names_from_label(ctx.label, ctx.attrs.use_same_package_name)
else: # haskell_binary case
(pkgname, libname) = make_haskell_names_from_label(ctx.label, False)
haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
linker_info = get_cxx_toolchain_info(ctx).linker_info
allow_worker = ctx.attrs.allow_worker
is_worker_execute = check_is_worker_execute(worker, allow_worker, haskell_toolchain.use_worker)
toolchain_libs = [dep.name for dep in attr_deps_haskell_toolchain_libraries(ctx)]
haskell_direct_deps_lib_infos = attr_deps_haskell_lib_infos(
ctx,
link_style,
enable_profiling,
)
# The object and interface file paths are depending on the real module name
# as inferred by GHC, not the source file path; currently this requires the
# module name to correspond to the source file path as otherwise GHC will
# not be able to find the created object or interface files in the search
# path.
#
# (module X.Y.Z must be defined in a file at X/Y/Z.hs)
ctx.actions.dynamic_output_new(_dynamic_target_metadata(
pkg_deps = haskell_toolchain.packages.dynamic if haskell_toolchain.packages else None,
output = md_file.as_output(),
arg = MetadataParams(
unit = MetadataUnitParams(
unit = UnitParams(
name = pkgname,
link_style = link_style,
enable_profiling = enable_profiling,
enable_haddock = enable_haddock,
main = main,
external_tool_paths = [tool[RunInfo] for tool in ctx.attrs.external_tools],
artifact_suffix = get_artifact_suffix(link_style, enable_profiling),
haskell_toolchain = haskell_toolchain,
compiler_flags = ctx.attrs.compiler_flags,
is_worker_execute = is_worker_execute,
),
toolchain_libs = toolchain_libs,
deps = attr_deps(ctx),
direct_extra_libs = ctx.attrs.extra_libraries,
is_binary = is_binary,
),
direct_deps_link_info = attr_deps_haskell_link_infos(ctx),
haskell_direct_deps_lib_infos = haskell_direct_deps_lib_infos,
md_gen = md_gen,
sources = sources,
strip_prefix = str(ctx.label.path),
suffix = link_style.value + ("+prof" if enable_profiling else ""),
worker = worker,
allow_worker = allow_worker,
allow_cache_upload = ctx.attrs.allow_cache_upload,
label = ctx.label,
incremental = ctx.attrs.incremental,
linker_info = linker_info,
),
))
return md_file.with_associated_artifacts([src for src in sources if not src.is_source])
# List of a unit's modules for the persistent worker's metadata calculation.
def target_skeleton(ctx: AnalysisContext, sources: list[Artifact]) -> Artifact:
# Mirrors the module naming of _modules_by_name.
# Boot files are skipped because they are not importable from other units.
modules = []
for src in sources:
if is_haskell_boot(src.short_path) or not is_haskell_src(src.short_path):
continue
module_name = src_to_module_name(src.short_path)
if ctx.attrs.module_prefix:
module_name = "{}.{}".format(ctx.attrs.module_prefix, module_name)
else:
for prefix in ctx.attrs.strip_prefix:
if strip_prefix(prefix, src.short_path) != None:
module_name = _strip_prefix(".", _strip_prefix(prefix.replace("/", "."), module_name))
break
modules.append(module_name)
skeleton_file = ctx.actions.declare_output("skeleton.json")
ctx.actions.write_json(skeleton_file, modules, pretty = True)
return skeleton_file
def _package_flag(toolchain: HaskellToolchainInfo) -> str:
if toolchain.support_expose_package:
return "-expose-package"
else:
return "-package"
# Get list of extra library artifacts and dynamic value associated with them
def get_extra_lib_info(
link_style: LinkStyle,
extra_libraries: list[Dependency]) -> ExtraLibraryInfo:
extra_libs = []
extra_lib_dyns = []
for lib in extra_libraries:
x = lib[MergedLinkInfo]._infos[to_link_strategy(link_style)].value
extra_libs.extend([l.lib for l in x.default.linkables])
extra_lib_dyns = [
lib[GhcLinkableInfo].extra_ghc_linker_flags_dynamic
for lib in extra_libraries
]
extra_lib_info = ExtraLibraryInfo(
extra_libs = dedupe_by_value(extra_libs),
extra_lib_dyns = dedupe_by_value(extra_lib_dyns),
as_deps = list(extra_libraries), # NOTE: Should hold a *copy* of extra_libraries
)
return extra_lib_info
def get_packages_info(
actions: AnalysisActions,
label: Label,
deps: list[Dependency],
direct_extra_libs: list[Dependency], # extra library dependency of this package
direct_deps_link_info: list[HaskellLinkInfo],
haskell_toolchain: HaskellToolchainInfo,
linker_info: typing.Any,
haskell_direct_deps_lib_infos: list[HaskellLibraryInfo],
link_style: LinkStyle,
specify_pkg_version: bool,
enable_profiling: bool,
use_empty_lib: bool,
pkg_deps: ResolvedDynamicValue | None,
for_deps: bool,
is_worker_execute: bool) -> PackagesInfo:
# Collect library dependencies. Note that these don't need to be in a
# particular order.
libs = actions.tset(
HaskellLibraryInfoTSet,
children = [
lib.prof_info[link_style] if enable_profiling else lib.info[link_style]
for lib in direct_deps_link_info
],
)
hidden_args = [l for lib in libs.traverse() for l in lib.libs]
exposed_package_args = cmd_args()
if for_deps:
get_db = lambda l: l.deps_db
elif use_empty_lib:
get_db = lambda l: l.empty_db
else:
get_db = lambda l: l.db
local_packagedb_args = cmd_args()
packagedb_args = cmd_args()
packagedb_set = {}
for lib in libs.traverse():
packagedb_set[get_db(lib)] = None
if not for_deps:
hidden_args = cmd_args(hidden = [
lib.interfaces.values(),
lib.stub_dirs,
lib.libs,
])
exposed_package_args.add(hidden_args)
extra_libs_args = cmd_args()
extra_libraries = make_extra_libraries_tset(
actions,
extra_libraries = direct_extra_libs,
haskell_libraries = direct_deps_link_info,
)
extra_lib_info = get_extra_lib_info(
link_style,
traverse_extra_libraries(extra_libraries),
)
link_infos = get_link_infos_from_extra_lib_info(actions, label, linker_info, link_style, extra_lib_info)
for link_info in link_infos:
for linkable in link_info.linkables:
if isinstance(linkable, SharedLibLinkable):
extra_libs_args.add(cmd_args(linkable.lib, format = "-L{}", parent = 1))
extra_libs_args.add(cmd_args(get_libname(linkable), format = "-l{}"))
else:
fail("Unimplemented linkable: {}".format(linkable))
if pkg_deps:
toolchain_package_db = pkg_deps.providers[DynamicHaskellToolchainPackageDbInfo].toolchain_packages
else:
toolchain_package_db = {}
direct_toolchain_libs = [
dep[HaskellToolchainLibrary].name
for dep in deps
if HaskellToolchainLibrary in dep
]
transitive_toolchain_libs = libs.reduce("toolchain_packages")
toolchain_package_db = augment_toolchain_package_db(
actions,
toolchain_package_db,
[dep[HaskellToolchainLibrary] for dep in deps if HaskellToolchainLibrary in dep] +
transitive_toolchain_libs,
)
toolchain_libs = direct_toolchain_libs + [p.name for p in transitive_toolchain_libs]
toolchain_package_db_tset = actions.tset(
HaskellToolchainPackageDbTSet,
children = [toolchain_package_db[name] for name in toolchain_libs if name in toolchain_package_db],
)
# These we need to add for all the packages/dependencies, i.e.
# direct and transitive (e.g. `fbcode-common-hs-util-hs-array`)
local_packagedb_args.add(packagedb_set.keys())
packagedb_args.add(toolchain_package_db_tset.project_as_args("toolchain_package_db"))
local_package_flag = "-package-id" if is_worker_execute else "-package"
# Expose only the packages we depend on directly
for lib in haskell_direct_deps_lib_infos:
pkg_name = lib.name
if (specify_pkg_version):
pkg_name += "-{}".format(lib.version)
exposed_package_args.add(local_package_flag, pkg_name)
return PackagesInfo(
exposed_package_args = exposed_package_args,
local_packagedb_args = local_packagedb_args,
packagedb_args = packagedb_args,
extra_libs_args = extra_libs_args,
transitive_deps = libs,
)
CommonCompileModuleArgs = record(
pkgname = field(str),
command = field(cmd_args),
args_for_file = field(cmd_args),
oneshot_args_for_file = field(cmd_args),
oneshot_wrapper_args = field(cmd_args),
common_args_file = field(Artifact),
package_env_args = field(cmd_args),
target_deps_args = field(cmd_args),
toolchain_package_db = field(dict[str, HaskellToolchainPackageDbTSet]),
)
def add_worker_args(
haskell_toolchain: HaskellToolchainInfo,
command: cmd_args,
pkgname: str) -> None:
command.add("--worker-target-id", "singleton")
def make_package_env(
*,
actions: AnalysisActions,
haskell_toolchain: HaskellToolchainInfo,
label: Label,
link_style: LinkStyle,
enable_profiling: bool,
allow_worker: bool,
worker: WorkerInfo | None,
packagedb_args: cmd_args) -> Artifact:
# TODO[AH] Avoid duplicates and share identical env files.
# The set of package-dbs can be known at the package level, not just the
# module level. So, we could generate this file outside of the
# dynamic_output action.
package_env_file = actions.declare_output(".".join([
label.name,
"package-db",
output_extensions(link_style, enable_profiling)[1],
"env",
]))
package_env = cmd_args(delimiter = "\n")
is_worker_execute = check_is_worker_execute(worker, allow_worker, haskell_toolchain.use_worker)
if not is_worker_execute:
package_env.add(cmd_args(
packagedb_args,
format = "package-db {}",
).relative_to(package_env_file, parent = 1))
actions.write(
package_env_file,
package_env,
)
return package_env_file
# Only add RTS argument list markers if the attribute was specified and is nonempty.
def add_rts_flags(args: cmd_args, flags: None | list[str]):
if flags:
args.add(["+RTS"] + flags + ["-RTS"])
# Arguments interpreted by `ghc_wrapper` or the worker.
# Since the worker receives arguments in gRPC requests, there is no executable at the head of the list.
# The worker does not need to invoke GHC as a subprocess, so `--ghc` is not needed.
def _common_compile_wrapper_args(
ghc_wrapper: RunInfo,
haskell_toolchain: HaskellToolchainInfo,
pkgname: str,
is_worker_execute: bool) -> cmd_args:
args = cmd_args()
if is_worker_execute:
add_worker_args(haskell_toolchain, args, pkgname)
else:
args.add(ghc_wrapper)
args.add("--ghc", haskell_toolchain.compiler)
args.add("--ghc-dir", haskell_toolchain.ghc_dir)
return args
# This _should_ be `tuple[Artifact, ResolvedDynamicValue]`, but:
# error: `tuple[]` is implemented only for `tuple[T, ...]`
#
# This _could_ be `tuple[Artifact | ResolvedDynamicValue, ...]` but
# `buildifier` hard-errors when `...` is used.
_DirectDep = typing.Any
def _direct_dep_artifact(dep: _DirectDep) -> Artifact:
"""Get the `Artifact` out of a `_DirectDep`.
`_DirectDep` is `Any`, so we provide type-annotated accessors for
`_DirectDep` fields.
"""
return dep[0]
def _direct_dep_compile_result(dep: _DirectDep) -> DynamicCompileResultInfo:
"""Get the `DynamicCompileResultInfo` out of a `_DirectDep`.
`_DirectDep` is `Any`, so we provide type-annotated accessors for
`_DirectDep` fields.
"""
return dep[1].providers[DynamicCompileResultInfo]
_IndexedPackageDeps = record(
# this will be deprecated.
toolchain_deps = list[str],
# this unified package_deps will be used later on.
package_deps = list[str],
exposed_package_modules = list[CompiledModuleTSet],
exposed_package_dbs = list[Artifact],
)
DepsByNameInfo = record(
direct = dict[str, _DirectDep],
toolchain = dict[str, None],
)
ModulePackageDeps = record(
packages = dict[str, list[str]], # `dict[pkgname, list[modname]]`
)