-
Notifications
You must be signed in to change notification settings - Fork 369
Expand file tree
/
Copy pathhaskell.bzl
More file actions
1154 lines (1032 loc) · 40.2 KB
/
Copy pathhaskell.bzl
File metadata and controls
1154 lines (1032 loc) · 40.2 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 dual-licensed under either the MIT license found in the
# LICENSE-MIT file in the root directory of this source tree or the Apache
# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
# of this source tree. You may select, at your option, one of the
# above-listed licenses.
# Implementation of the Haskell build rules.
load("@prelude//:paths.bzl", "paths")
load("@prelude//cxx:archive.bzl", "make_archive")
load(
"@prelude//cxx:cxx.bzl",
"get_auto_link_group_specs",
)
load(
"@prelude//cxx:cxx_context.bzl",
"get_cxx_toolchain_info",
)
load(
"@prelude//cxx:cxx_toolchain_types.bzl",
"CxxToolchainInfo",
"LinkerType",
"PicBehavior",
)
load("@prelude//cxx:groups.bzl", "get_dedupped_roots_from_groups")
load(
"@prelude//cxx:link_groups.bzl",
"BuildLinkGroupsContext",
"LinkGroupContext",
"collect_linkables",
"create_link_groups",
"find_relevant_roots",
"get_filtered_labels_to_links_map",
"get_filtered_links",
"get_link_group_info",
"get_link_group_preferred_linkage",
"get_public_link_group_nodes",
"get_transitive_deps_matching_labels",
"is_link_group_shlib",
)
load(
"@prelude//cxx:linker.bzl",
"LINKERS",
"get_rpath_origin",
"get_shared_library_flags",
)
load(
"@prelude//cxx:preprocessor.bzl",
"CPreprocessor",
"CPreprocessorArgs",
"cxx_inherited_preprocessor_infos",
"cxx_merge_cpreprocessors",
)
load(
"@prelude//haskell:compile.bzl",
"CompileResultInfo",
"compile",
)
load(
"@prelude//haskell:haskell_haddock.bzl",
"haskell_haddock_lib",
)
load(
"@prelude//haskell:library_info.bzl",
"HaskellLibraryInfo",
"HaskellLibraryInfoTSet",
"HaskellLibraryProvider",
)
load(
"@prelude//haskell:link_info.bzl",
"HaskellLinkInfo",
"HaskellProfLinkInfo",
"attr_link_style",
"cxx_toolchain_link_style",
)
load(
"@prelude//haskell:toolchain.bzl",
"HaskellToolchainInfo",
)
load(
"@prelude//haskell:util.bzl",
"attr_deps",
"attr_deps_haskell_link_infos_sans_template_deps",
"attr_deps_merged_link_infos",
"attr_deps_profiling_link_infos",
"attr_deps_shared_library_infos",
"get_artifact_suffix",
"is_haskell_src",
"output_extensions",
"src_to_module_name",
"srcs_to_pairs",
)
load(
"@prelude//linking:link_groups.bzl",
"gather_link_group_libs",
"merge_link_group_lib_info",
)
load(
"@prelude//linking:link_info.bzl",
"Archive",
"ArchiveContentsType",
"ArchiveLinkable",
"LibOutputStyle",
"LinkArgs",
"LinkInfo",
"LinkInfos",
"LinkStyle",
"LinkedObject",
"MergedLinkInfo",
"SharedLibLinkable",
"create_merged_link_info",
"default_output_style_for_link_strategy",
"get_lib_output_style",
"get_link_args_for_strategy",
"get_output_styles_for_linkage",
"legacy_output_style_to_link_style",
"to_link_strategy",
"unpack_link_args",
)
load(
"@prelude//linking:linkable_graph.bzl",
"LinkableGraph",
"create_linkable_graph",
"create_linkable_graph_node",
"create_linkable_node",
"reduce_linkable_graph",
)
load(
"@prelude//linking:linkables.bzl",
"linkables",
)
load(
"@prelude//linking:shared_libraries.bzl",
"SharedLibraryInfo",
"create_shared_libraries",
"create_shlib_symlink_tree",
"merge_shared_libraries",
"traverse_shared_library_info",
)
load("@prelude//linking:types.bzl", "Linkage")
load(
"@prelude//python:python.bzl",
"PythonLibraryInfo",
)
load("@prelude//utils:argfile.bzl", "at_argfile")
load("@prelude//utils:utils.bzl", "filter_and_map_idx", "flatten")
HaskellIndexingTSet = transitive_set()
# A list of hie dirs
HaskellIndexInfo = provider(
fields = {
"info": provider_field(typing.Any, default = None), # dict[LinkStyle, HaskellIndexingTset]
},
)
# This conversion is non-standard, see TODO about link style below
def _to_lib_output_style(link_style: LinkStyle) -> LibOutputStyle:
return default_output_style_for_link_strategy(to_link_strategy(link_style))
def _attr_preferred_linkage(ctx: AnalysisContext) -> Linkage:
preferred_linkage = ctx.attrs.preferred_linkage
# force_static is deprecated, but it has precedence over preferred_linkage
if getattr(ctx.attrs, "force_static", False):
preferred_linkage = "static"
return Linkage(preferred_linkage)
# --
def _get_haskell_prebuilt_libs(ctx, link_style: LinkStyle, enable_profiling: bool) -> list[Artifact]:
if link_style == LinkStyle("shared"):
if enable_profiling:
# Profiling doesn't support shared libraries
return []
return ctx.attrs.shared_libs.values()
elif link_style == LinkStyle("static"):
if enable_profiling:
return ctx.attrs.profiled_static_libs
return ctx.attrs.static_libs
elif link_style == LinkStyle("static_pic"):
if enable_profiling:
return ctx.attrs.pic_profiled_static_libs
return ctx.attrs.pic_static_libs
else:
fail("Unexpected LinkStyle: " + link_style.value)
def haskell_prebuilt_library_impl(ctx: AnalysisContext) -> list[Provider]:
# MergedLinkInfo for both with and without profiling
native_infos = []
prof_native_infos = []
haskell_infos = []
shared_library_infos = []
for dep in ctx.attrs.deps:
used = False
if HaskellLinkInfo in dep:
used = True
haskell_infos.append(dep[HaskellLinkInfo])
li = dep.get(MergedLinkInfo)
if li != None:
used = True
native_infos.append(li)
if HaskellLinkInfo not in dep:
prof_native_infos.append(li)
if HaskellProfLinkInfo in dep:
prof_native_infos.append(dep[HaskellProfLinkInfo].prof_infos)
if SharedLibraryInfo in dep:
used = True
shared_library_infos.append(dep[SharedLibraryInfo])
if PythonLibraryInfo in dep:
used = True
if not used:
fail("Unexpected link info encountered")
hlibinfos = {}
prof_hlibinfos = {}
hlinkinfos = {}
prof_hlinkinfos = {}
link_infos = {}
prof_link_infos = {}
for link_style in LinkStyle:
libs = _get_haskell_prebuilt_libs(ctx, link_style, False)
prof_libs = _get_haskell_prebuilt_libs(ctx, link_style, True)
hlibinfo = HaskellLibraryInfo(
name = ctx.attrs.name,
db = ctx.attrs.db,
import_dirs = {},
stub_dirs = [],
id = ctx.attrs.id,
libs = libs,
version = ctx.attrs.version,
is_prebuilt = True,
profiling_enabled = False,
)
prof_hlibinfo = HaskellLibraryInfo(
name = ctx.attrs.name,
db = ctx.attrs.db,
import_dirs = {},
stub_dirs = [],
id = ctx.attrs.id,
libs = prof_libs,
version = ctx.attrs.version,
is_prebuilt = True,
profiling_enabled = True,
)
def archive_linkable(lib):
return ArchiveLinkable(
archive = Archive(artifact = lib),
linker_type = LinkerType("gnu"),
)
def shared_linkable(lib):
return SharedLibLinkable(
lib = lib,
)
linkables = [(shared_linkable if link_style == LinkStyle("shared") else archive_linkable)(lib) for lib in libs]
prof_linkables = [(shared_linkable if link_style == LinkStyle("shared") else archive_linkable)(lib) for lib in prof_libs]
hlibinfos[link_style] = hlibinfo
hlinkinfos[link_style] = ctx.actions.tset(
HaskellLibraryInfoTSet,
value = hlibinfo,
children = [lib.info[link_style] for lib in haskell_infos],
)
prof_hlibinfos[link_style] = prof_hlibinfo
prof_hlinkinfos[link_style] = ctx.actions.tset(
HaskellLibraryInfoTSet,
value = prof_hlibinfo,
children = [lib.prof_info[link_style] for lib in haskell_infos],
)
link_infos[link_style] = LinkInfos(
default = LinkInfo(
pre_flags = ctx.attrs.exported_linker_flags,
post_flags = ctx.attrs.exported_post_linker_flags,
linkables = linkables,
),
)
prof_link_infos[link_style] = LinkInfos(
default = LinkInfo(
pre_flags = ctx.attrs.exported_linker_flags,
post_flags = ctx.attrs.exported_post_linker_flags,
linkables = prof_linkables,
),
)
haskell_link_infos = HaskellLinkInfo(
info = hlinkinfos,
prof_info = prof_hlinkinfos,
)
haskell_lib_provider = HaskellLibraryProvider(
lib = hlibinfos,
prof_lib = prof_hlibinfos,
)
# The link info that will be used when this library is a dependency of a non-Haskell
# target (e.g. a cxx_library()). We need to pick the profiling libs if we're in
# profiling mode.
default_link_infos = prof_link_infos if ctx.attrs.enable_profiling else link_infos
default_native_infos = prof_native_infos if ctx.attrs.enable_profiling else native_infos
merged_link_info = create_merged_link_info(
ctx,
# We don't have access to a CxxToolchain here (yet).
# Give that it's already built, this doesn't mean much, use a sane default.
pic_behavior = PicBehavior("supported"),
link_infos = {_to_lib_output_style(s): v for s, v in default_link_infos.items()},
exported_deps = default_native_infos,
)
prof_merged_link_info = create_merged_link_info(
ctx,
# We don't have access to a CxxToolchain here (yet).
# Give that it's already built, this doesn't mean much, use a sane default.
pic_behavior = PicBehavior("supported"),
link_infos = {_to_lib_output_style(s): v for s, v in prof_link_infos.items()},
exported_deps = prof_native_infos,
)
solibs = {}
for soname, lib in ctx.attrs.shared_libs.items():
solibs[soname] = LinkedObject(output = lib, unstripped_output = lib)
shared_libs = create_shared_libraries(ctx, solibs)
linkable_graph = create_linkable_graph(
ctx,
node = create_linkable_graph_node(
ctx,
linkable_node = create_linkable_node(
ctx = ctx,
exported_deps = ctx.attrs.deps,
link_infos = {_to_lib_output_style(s): v for s, v in link_infos.items()},
shared_libs = shared_libs,
default_soname = None,
),
),
deps = ctx.attrs.deps,
)
inherited_pp_info = cxx_inherited_preprocessor_infos(ctx.attrs.deps)
own_pp_info = CPreprocessor(
args = CPreprocessorArgs(args = flatten([["-isystem", d] for d in ctx.attrs.cxx_header_dirs])),
)
return [
DefaultInfo(),
haskell_lib_provider,
cxx_merge_cpreprocessors(ctx.actions, [own_pp_info], inherited_pp_info),
merge_shared_libraries(
ctx.actions,
shared_libs,
shared_library_infos,
),
merge_link_group_lib_info(deps = ctx.attrs.deps),
haskell_link_infos,
merged_link_info,
HaskellProfLinkInfo(
prof_infos = prof_merged_link_info,
),
linkable_graph,
]
def _srcs_to_objfiles(ctx: AnalysisContext, odir: Artifact, osuf: str) -> list[Artifact]:
objfiles = []
for src, _ in srcs_to_pairs(ctx.attrs.srcs):
# Don't link boot sources, as they're only meant to be used for compiling.
if is_haskell_src(src):
objfiles.append(odir.project(paths.replace_extension(src, "." + osuf)))
return objfiles
_REGISTER_PACKAGE = """\
set -eu
GHC_PKG=$1
DB=$2
PKGCONF=$3
ALWAYS_USE_CACHE=$4
"$GHC_PKG" init "$DB"
"$GHC_PKG" register --package-conf "$DB" --no-expand-pkgroot $ALWAYS_USE_CACHE "$PKGCONF"
"""
# Create a package
#
# The way we use packages is a bit strange. We're not using them
# at link time at all: all the linking info is in the
# HaskellLibraryInfo and we construct linker command lines
# manually. Packages are used for:
#
# - finding .hi files at compile time
#
# - symbol namespacing (so that modules with the same name in
# different libraries don't clash).
#
# - controlling module visibility: only dependencies that are
# directly declared as dependencies may be used
#
# - Template Haskell: the compiler needs to load libraries itself
# at compile time, so it uses the package specs to find out
# which libraries and where.
def _make_package(
ctx: AnalysisContext,
link_style: LinkStyle,
pkgname: str,
libname: str,
hlis: list[HaskellLibraryInfo],
hi: dict[bool, Artifact],
lib: dict[bool, Artifact],
enable_profiling: bool,
) -> Artifact:
artifact_suffix = get_artifact_suffix(link_style, enable_profiling)
# Don't expose boot sources, as they're only meant to be used for compiling.
modules = [src_to_module_name(x) for x, _ in srcs_to_pairs(ctx.attrs.srcs) if is_haskell_src(x)]
if enable_profiling:
# Add the `-p` suffix otherwise ghc will look for objects
# following this logic (https://fburl.com/code/3gmobm5x) and will fail.
libname += "_p"
def mk_artifact_dir(dir_prefix: str, profiled: bool) -> str:
art_suff = get_artifact_suffix(link_style, profiled)
return '"${pkgroot}/' + dir_prefix + "-" + art_suff + '"'
import_dirs = [mk_artifact_dir("hi", profiled) for profiled in hi.keys()]
library_dirs = [mk_artifact_dir("lib", profiled) for profiled in hi.keys()]
conf = [
"name: " + pkgname,
"version: 1.0.0",
"id: " + pkgname,
"key: " + pkgname,
"exposed: False",
"exposed-modules: " + ", ".join(modules),
"import-dirs:" + ", ".join(import_dirs),
"library-dirs:" + ", ".join(library_dirs),
"extra-libraries: " + libname,
"depends: " + ", ".join([lib.id for lib in hlis]),
]
pkg_conf = ctx.actions.write("pkg-" + artifact_suffix + ".conf", conf, has_content_based_path = False)
db = ctx.actions.declare_output("db-" + artifact_suffix, has_content_based_path = False)
# While the list of hlis is unique, there may be multiple packages in the same db.
# Cutting down the GHC_PACKAGE_PATH significantly speeds up GHC.
db_deps = {x.db: None for x in hlis}.keys()
# So that ghc-pkg can find the DBs for the dependencies. We might
# be able to use flags for this instead, but this works.
ghc_package_path = cmd_args(
db_deps,
delimiter = ":",
)
haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
# --always-use-cache is a custom option to ghc-pkg that tells it to ignore the
# modification time on the package cache and use it anyway. This is useful in
# RE where file modification times can't be relied upon; without this option
# ghc-pkg will fall back to reading all the package configs which is much
# slower.
if haskell_toolchain.support_always_use_cache:
use_cache_arg = "--always-use-cache"
else:
use_cache_arg = ""
ctx.actions.run(
cmd_args(
[
"sh",
"-c",
_REGISTER_PACKAGE,
"",
haskell_toolchain.packager,
db.as_output(),
pkg_conf,
use_cache_arg,
],
# needs hi, because ghc-pkg checks that the .hi files exist
hidden = hi.values() + lib.values(),
),
category = "haskell_package_" + artifact_suffix.replace("-", "_"),
env = {"GHC_PACKAGE_PATH": ghc_package_path} if db_deps else {},
)
return db
HaskellLibBuildOutput = record(
hlib = HaskellLibraryInfo,
solibs = dict[str, LinkedObject],
link_infos = LinkInfos,
compiled = CompileResultInfo,
libs = list[Artifact],
)
def _get_haskell_shared_library_name_linker_flags(linker_type: LinkerType, soname: str) -> list[str]:
if linker_type == LinkerType("gnu"):
return ["-Wl,-soname,{}".format(soname)]
elif linker_type == LinkerType("darwin"):
# Passing `-install_name @rpath/...` or
# `-Xlinker -install_name -Xlinker @rpath/...` instead causes
# ghc-9.6.3: panic! (the 'impossible' happened)
return ["-Wl,-install_name,@rpath/{}".format(soname)]
else:
fail("Unknown linker type '{}'.".format(linker_type))
def _build_haskell_lib(
ctx,
libname: str,
pkgname: str,
hlis: list[HaskellLinkInfo], # haskell link infos from all deps
nlis: list[MergedLinkInfo], # native link infos from all deps
link_style: LinkStyle,
enable_profiling: bool,
# The non-profiling artifacts are also needed to build the package for
# profiling, so it should be passed when `enable_profiling` is True.
non_profiling_hlib: [HaskellLibBuildOutput, None] = None,
) -> HaskellLibBuildOutput:
linker_info = ctx.attrs._cxx_toolchain[CxxToolchainInfo].linker_info
# Link the objects into a library
haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
osuf, _hisuf = output_extensions(link_style, enable_profiling)
# Compile the sources
compiled = compile(
ctx,
link_style,
enable_profiling = enable_profiling,
pkgname = pkgname,
)
solibs = {}
artifact_suffix = get_artifact_suffix(link_style, enable_profiling)
libstem = libname
if link_style == LinkStyle("static_pic"):
libstem += "_pic"
dynamic_lib_suffix = "." + LINKERS[linker_info.type].default_shared_library_extension
static_lib_suffix = "_p.a" if enable_profiling else ".a"
libfile = "lib" + libstem + (dynamic_lib_suffix if link_style == LinkStyle("shared") else static_lib_suffix)
lib_short_path = paths.join("lib-{}".format(artifact_suffix), libfile)
linfos = [x.prof_info if enable_profiling else x.info for x in hlis]
# only gather direct dependencies
uniq_infos = [x[link_style].value for x in linfos]
objfiles = _srcs_to_objfiles(ctx, compiled.objects, osuf)
if link_style == LinkStyle("shared"):
lib = ctx.actions.declare_output(lib_short_path, has_content_based_path = False)
link = cmd_args(
[haskell_toolchain.linker]
+ [haskell_toolchain.linker_flags]
+ [ctx.attrs.linker_flags]
+ ["-o", lib.as_output()]
+ [
"-package-env=-",
get_shared_library_flags(linker_info.type),
"-dynamic",
cmd_args(
_get_haskell_shared_library_name_linker_flags(linker_info.type, libfile),
prepend = "-optl",
),
]
+ [objfiles],
hidden = compiled.stubs,
)
infos = get_link_args_for_strategy(
ctx.actions,
ctx.label,
linker_info,
nlis,
to_link_strategy(link_style),
prefer_stripped = False,
transformation_spec_context = None,
)
link.add(cmd_args(unpack_link_args(infos), prepend = "-optl"))
ctx.actions.run(
link,
category = "haskell_link" + artifact_suffix.replace("-", "_"),
)
solibs[libfile] = LinkedObject(output = lib, unstripped_output = lib)
libs = [lib]
link_infos = LinkInfos(
default = LinkInfo(linkables = [SharedLibLinkable(lib = lib)]),
)
else: # static flavours
# TODO: avoid making an archive for a single object, like cxx does
# (but would that work with Template Haskell?)
# TODO: Opt haskell actions into content based paths.
archive = make_archive(ctx, lib_short_path, objfiles, force_disable_content_based_path = True)
lib = archive.artifact
libs = [lib] + (archive.external_objects if archive.archive_contents_type == ArchiveContentsType("thin") else [])
link_infos = LinkInfos(
default = LinkInfo(
linkables = [
ArchiveLinkable(
archive = archive,
linker_type = linker_info.type,
link_whole = ctx.attrs.link_whole,
),
],
),
)
if enable_profiling and link_style != LinkStyle("shared"):
if not non_profiling_hlib:
fail("Non-profiling HaskellLibBuildOutput wasn't provided when building profiling lib")
import_artifacts = {
True: compiled.hi,
False: non_profiling_hlib.compiled.hi,
}
library_artifacts = {
True: lib,
False: non_profiling_hlib.libs[0],
}
all_libs = libs + non_profiling_hlib.libs
stub_dirs = [compiled.stubs] + [non_profiling_hlib.compiled.stubs]
else:
import_artifacts = {
False: compiled.hi,
}
library_artifacts = {
False: lib,
}
all_libs = libs
stub_dirs = [compiled.stubs]
db = _make_package(
ctx,
link_style,
pkgname,
libstem,
uniq_infos,
import_artifacts,
library_artifacts,
enable_profiling = enable_profiling,
)
hlib = HaskellLibraryInfo(
name = pkgname,
db = db,
id = pkgname,
import_dirs = import_artifacts,
stub_dirs = stub_dirs,
libs = all_libs,
version = "1.0.0",
is_prebuilt = False,
profiling_enabled = enable_profiling,
)
return HaskellLibBuildOutput(
hlib = hlib,
solibs = solibs,
link_infos = link_infos,
compiled = compiled,
libs = libs,
)
def haskell_library_impl(ctx: AnalysisContext) -> list[Provider]:
preferred_linkage = _attr_preferred_linkage(ctx)
if ctx.attrs.enable_profiling and preferred_linkage == Linkage("any"):
preferred_linkage = Linkage("static")
# Get haskell and native link infos from all deps
hlis = attr_deps_haskell_link_infos_sans_template_deps(ctx)
nlis = attr_deps_merged_link_infos(ctx)
prof_nlis = attr_deps_profiling_link_infos(ctx)
shared_library_infos = attr_deps_shared_library_infos(ctx)
solibs = {}
link_infos = {}
prof_link_infos = {}
hlib_infos = {}
hlink_infos = {}
prof_hlib_infos = {}
prof_hlink_infos = {}
indexing_tsets = {}
sub_targets = {}
libname = repr(ctx.label.path).replace("//", "_").replace("/", "_") + "_" + ctx.label.name
pkgname = libname.replace("_", "-")
# The non-profiling library is also needed to build the package with
# profiling enabled, so we need to keep track of it for each link style.
non_profiling_hlib = {}
for enable_profiling in [False, True]:
for output_style in get_output_styles_for_linkage(preferred_linkage):
link_style = legacy_output_style_to_link_style(output_style)
if link_style == LinkStyle("shared") and enable_profiling:
# Profiling isn't support with dynamic linking
continue
hlib_build_out = _build_haskell_lib(
ctx,
libname,
pkgname,
hlis = hlis,
nlis = nlis,
link_style = link_style,
enable_profiling = enable_profiling,
non_profiling_hlib = non_profiling_hlib.get(link_style),
)
if not enable_profiling:
non_profiling_hlib[link_style] = hlib_build_out
hlib = hlib_build_out.hlib
solibs.update(hlib_build_out.solibs)
compiled = hlib_build_out.compiled
libs = hlib_build_out.libs
if enable_profiling:
prof_hlib_infos[link_style] = hlib
prof_hlink_infos[link_style] = ctx.actions.tset(
HaskellLibraryInfoTSet,
value = hlib,
children = [li.prof_info[link_style] for li in hlis],
)
prof_link_infos[link_style] = hlib_build_out.link_infos
else:
hlib_infos[link_style] = hlib
hlink_infos[link_style] = ctx.actions.tset(
HaskellLibraryInfoTSet,
value = hlib,
children = [li.info[link_style] for li in hlis],
)
link_infos[link_style] = hlib_build_out.link_infos
# Build the indices and create subtargets only once, with profiling
# enabled or disabled based on what was set in the library's
# target.
if ctx.attrs.enable_profiling == enable_profiling:
if compiled.producing_indices:
tset = derive_indexing_tset(
ctx.actions,
link_style,
compiled.hi,
attr_deps(ctx),
)
indexing_tsets[link_style] = tset
sub_targets[link_style.value.replace("_", "-")] = [
DefaultInfo(
default_outputs = libs,
)
]
pic_behavior = ctx.attrs._cxx_toolchain[CxxToolchainInfo].pic_behavior
link_style = cxx_toolchain_link_style(ctx)
output_style = get_lib_output_style(
to_link_strategy(link_style),
preferred_linkage,
pic_behavior,
)
shared_libs = create_shared_libraries(ctx, solibs)
# TODO(cjhopman): this haskell implementation does not consistently handle LibOutputStyle
# and LinkStrategy as expected and it's hard to tell what the intent of the existing code is
# and so we currently just preserve its existing use of the legacy LinkStyle type and just
# naively convert it at the boundaries of other code. This needs to be cleaned up by someone
# who understands the intent of the code here.
actual_link_style = legacy_output_style_to_link_style(output_style)
if preferred_linkage != Linkage("static"):
# Profiling isn't support with dynamic linking, but `prof_link_infos`
# needs entries for all link styles.
# We only need to set the shared link_style in both `prof_link_infos`
# and `link_infos` if the target doesn't force static linking.
prof_link_infos[LinkStyle("shared")] = link_infos[LinkStyle("shared")]
default_link_infos = prof_link_infos if ctx.attrs.enable_profiling else link_infos
default_native_infos = prof_nlis if ctx.attrs.enable_profiling else nlis
merged_link_info = create_merged_link_info(
ctx,
pic_behavior = pic_behavior,
link_infos = {_to_lib_output_style(s): v for s, v in default_link_infos.items()},
preferred_linkage = preferred_linkage,
exported_deps = default_native_infos,
)
prof_merged_link_info = create_merged_link_info(
ctx,
pic_behavior = pic_behavior,
link_infos = {_to_lib_output_style(s): v for s, v in prof_link_infos.items()},
preferred_linkage = preferred_linkage,
exported_deps = prof_nlis,
)
linkable_graph = create_linkable_graph(
ctx,
node = create_linkable_graph_node(
ctx,
linkable_node = create_linkable_node(
ctx = ctx,
preferred_linkage = preferred_linkage,
exported_deps = ctx.attrs.deps,
link_infos = {_to_lib_output_style(s): v for s, v in link_infos.items()},
shared_libs = shared_libs,
# TODO(cjhopman): this should be set to non-None
default_soname = None,
),
),
deps = ctx.attrs.deps,
)
default_output = hlib_infos[actual_link_style].libs
inherited_pp_info = cxx_inherited_preprocessor_infos(attr_deps(ctx))
# We would like to expose the generated _stub.h headers to C++
# compilations, but it's hard to do that without overbuilding. Which
# link_style should we pick below? If we pick a different link_style from
# the one being used by the root rule, we'll end up building all the
# Haskell libraries multiple times.
#
# pp = [CPreprocessor(
# args =
# flatten([["-isystem", dir] for dir in hlib_infos[actual_link_style].stub_dirs]),
# )]
pp = []
providers = [
DefaultInfo(
default_outputs = default_output,
sub_targets = sub_targets,
),
HaskellLibraryProvider(
lib = hlib_infos,
prof_lib = prof_hlib_infos,
),
HaskellLinkInfo(
info = hlink_infos,
prof_info = prof_hlink_infos,
),
merged_link_info,
HaskellProfLinkInfo(
prof_infos = prof_merged_link_info,
),
linkable_graph,
cxx_merge_cpreprocessors(ctx.actions, pp, inherited_pp_info),
merge_shared_libraries(
ctx.actions,
shared_libs,
shared_library_infos,
),
haskell_haddock_lib(ctx, pkgname),
]
if indexing_tsets:
providers.append(HaskellIndexInfo(info = indexing_tsets))
# TODO(cjhopman): This code is for templ_vars is duplicated from cxx_library
templ_vars = {}
# Add in ldflag macros.
for link_style in (LinkStyle("static"), LinkStyle("static_pic")):
name = "ldflags-" + link_style.value.replace("_", "-")
args = cmd_args()
linker_info = ctx.attrs._cxx_toolchain[CxxToolchainInfo].linker_info
args.add(linker_info.linker_flags)
args.add(
unpack_link_args(
get_link_args_for_strategy(
ctx.actions,
ctx.label,
linker_info,
[merged_link_info],
to_link_strategy(link_style),
prefer_stripped = False,
transformation_spec_context = None,
),
)
)
templ_vars[name] = args
# TODO(T110378127): To implement `$(ldflags-shared ...)` properly, we'd need
# to setup a symink tree rule for all transitive shared libs. Since this
# currently would be pretty costly (O(N^2)?), and since it's not that
# commonly used anyway, just use `static-pic` instead. Longer-term, once
# v1 is gone, macros that use `$(ldflags-shared ...)` (e.g. Haskell's
# hsc2hs) can move to a v2 rules-based API to avoid needing this macro.
templ_vars["ldflags-shared"] = templ_vars["ldflags-static-pic"]
providers.append(TemplatePlaceholderInfo(keyed_variables = templ_vars))
providers.append(merge_link_group_lib_info(deps = attr_deps(ctx)))
return providers
# TODO(cjhopman): should this be LibOutputType or LinkStrategy?
def derive_indexing_tset(actions: AnalysisActions, link_style: LinkStyle, value: Artifact | None, children: list[Dependency]) -> HaskellIndexingTSet:
index_children = []
for dep in children:
li = dep.get(HaskellIndexInfo)
if li:
if link_style in li.info:
index_children.append(li.info[link_style])
return actions.tset(
HaskellIndexingTSet,
value = value,
children = index_children,
)
def haskell_binary_impl(ctx: AnalysisContext) -> list[Provider]:
enable_profiling = ctx.attrs.enable_profiling
# Decide what kind of linking we're doing
link_style = attr_link_style(ctx)
# Link Groups
link_group_info = get_link_group_info(
ctx,
filter_and_map_idx(LinkableGraph, attr_deps(ctx)),
to_link_strategy(link_style),
)
# Profiling doesn't support shared libraries
if enable_profiling and link_style == LinkStyle("shared"):
link_style = LinkStyle("static")
compiled = compile(
ctx,
link_style,
enable_profiling = enable_profiling,
)
haskell_toolchain = ctx.attrs._haskell_toolchain[HaskellToolchainInfo]
output = ctx.actions.declare_output(ctx.attrs.name, has_content_based_path = False)
link = cmd_args(
[haskell_toolchain.compiler] + ["-o", output.as_output()] + [haskell_toolchain.linker_flags] + [ctx.attrs.linker_flags],
hidden = compiled.stubs,
)
link_args = cmd_args("-package-env=-")
osuf, _hisuf = output_extensions(link_style, enable_profiling)
objfiles = _srcs_to_objfiles(ctx, compiled.objects, osuf)
link_args.add(objfiles)
indexing_tsets = {}
if compiled.producing_indices:
tset = derive_indexing_tset(ctx.actions, link_style, compiled.hi, attr_deps(ctx))
indexing_tsets[link_style] = tset
slis = []
for lib in attr_deps(ctx):
li = lib.get(SharedLibraryInfo)
if li != None:
slis.append(li)
shlib_info = merge_shared_libraries(
ctx.actions,
deps = slis,
)
sos = []
link_strategy = to_link_strategy(link_style)
if link_group_info != None:
own_binary_link_flags = []
auto_link_groups = {}
link_group_libs = {}
link_deps = linkables(attr_deps(ctx))
reduced_linkable_graph = reduce_linkable_graph(link_group_info.graph)
linkable_graph_node_map = reduced_linkable_graph.nodes
link_group_preferred_linkage = get_link_group_preferred_linkage(link_group_info.groups.values())
# If we're using auto-link-groups, where we generate the link group links
# in the prelude, the link group map will give us the link group libs.
# Otherwise, pull them from the `LinkGroupLibInfo` provider from out deps.
auto_link_group_specs = get_auto_link_group_specs(ctx, link_group_info)
executable_deps = [d.linkable_graph.nodes.value.label for d in link_deps if d.linkable_graph != None]
public_nodes = get_public_link_group_nodes(
linkable_graph_node_map,
link_group_info.mappings,
executable_deps,
None,
)
if auto_link_group_specs != None:
linked_link_groups = create_link_groups(
ctx = ctx,
link_strategy = link_strategy,
linkable_graph = reduced_linkable_graph,
link_group_mappings = link_group_info.mappings,
link_group_preferred_linkage = link_group_preferred_linkage,