-
Notifications
You must be signed in to change notification settings - Fork 81
/
cabal.bzl
2764 lines (2526 loc) · 105 KB
/
cabal.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
"""Cabal packages"""
load("@bazel_skylib//lib:dicts.bzl", "dicts")
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe", "read_netrc", "use_netrc")
load("//vendor/bazel_json/lib:json_parser.bzl", "json_parse")
load("@bazel_tools//tools/cpp:lib_cc_configure.bzl", "get_cpu_value")
load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cc_toolchain", "use_cc_toolchain")
load(":cc.bzl", "cc_interop_info", "ghc_cc_program_args")
load(":private/actions/info.bzl", "library_info_output_groups")
load(":private/actions/link.bzl", "darwin_flags_for_linking_indirect_cc_deps")
load(":private/context.bzl", "haskell_context")
load(":private/dependencies.bzl", "gather_dep_info")
load(":private/expansions.bzl", "expand_make_variables")
load(":private/mode.bzl", "is_profiling_enabled")
load(
":private/path_utils.bzl",
"create_rpath_entry",
"join_path_list",
"relative_rpath_prefix",
"truly_relativize",
)
load("@bazel_skylib//lib:sets.bzl", "sets")
load(":private/validate_attrs.bzl", "typecheck_stackage_extradeps")
load(":haddock.bzl", "generate_unified_haddock_info")
load(
":private/workspace_utils.bzl",
_execute_or_fail_loudly = "execute_or_fail_loudly",
)
load(
":providers.bzl",
"HaddockInfo",
"HaskellInfo",
"HaskellLibraryInfo",
"all_dependencies_package_ids",
)
load(
":private/cc_libraries.bzl",
"get_cc_libraries",
"get_ghci_library_files",
"get_library_files",
"haskell_cc_libraries_aspect",
)
load(":private/versions.bzl", "check_bazel_version")
def _get_auth(ctx, urls):
"""Find the .netrc file and obtain the auth dict for the required URLs.
Refer to the [authentication in downloads proposal][auth-proposal] and the
[`http_archive` API documentation][http-archive] for a definition of the
auth dict.
[auth-proposal]: https://github.com/bazelbuild/proposals/blob/master/designs/2019-05-27-auth.md
[http-archive]: https://docs.bazel.build/versions/master/repo/http.html#http_archive-auth_patterns
"""
auth_patterns = {"api.github.com": "Bearer <password>"}
# Taken from @bazel_tools//tools/build_defs/repo:http.bzl
if ctx.attr.netrc:
netrc = read_netrc(ctx, ctx.attr.netrc)
return use_netrc(netrc, urls, auth_patterns)
if "HOME" in ctx.os.environ and not ctx.os.name.startswith("windows"):
netrcfile = "%s/.netrc" % (ctx.os.environ["HOME"])
if ctx.execute(["test", "-f", netrcfile]).return_code == 0:
netrc = read_netrc(ctx, netrcfile)
return use_netrc(netrc, urls, auth_patterns)
if "USERPROFILE" in ctx.os.environ and ctx.os.name.startswith("windows"):
netrcfile = "%s/.netrc" % (ctx.os.environ["USERPROFILE"])
if ctx.path(netrcfile).exists:
netrc = read_netrc(ctx, netrcfile)
return use_netrc(netrc, urls, auth_patterns)
return {}
def _so_extension(hs):
return "dylib" if hs.toolchain.is_darwin else "so"
def _dirname(file):
return file.dirname
def _version(name):
"""Return the version component of a package name."""
return name.rpartition("-")[2]
def _has_version(name):
"""Check whether a package identifier has a version component."""
return name.rpartition("-")[2].replace(".", "").isdigit()
def _chop_version(name):
"""Remove any version component from the given package name."""
return name.rpartition("-")[0]
def _find_cabal(srcs):
"""Check that a .cabal file exists. Choose the root one."""
cabal = None
for f in srcs:
if f.extension == "cabal":
if not cabal or f.dirname < cabal.dirname:
cabal = f
if not cabal:
fail("A .cabal file was not found in the srcs attribute.")
return cabal
def _find_setup(hs, cabal, srcs):
"""Check that a Setup script exists. If not, create a default one."""
setup = None
for f in srcs:
if f.basename in ["Setup.hs", "Setup.lhs"]:
if not setup or f.dirname < setup.dirname:
setup = f
if not setup:
setup = hs.actions.declare_file("Setup.hs", sibling = cabal)
hs.actions.write(
output = setup,
content = """
module Main where
import Distribution.Simple
main :: IO ()
main = defaultMain
""",
)
return setup
_CABAL_TOOLS = ["alex", "c2hs", "cpphs", "doctest", "happy"]
# Some old packages are empty compatibility shims. Empty packages
# cause Cabal to not produce the outputs it normally produces. Instead
# of detecting that, we blacklist the offending packages, on the
# assumption that such packages are old and rare.
#
# TODO: replace this with a more general solution.
_EMPTY_PACKAGES_BLACKLIST = [
"bytestring-builder",
"fail",
"ghc-byteorder",
"haskell-gi-overloading",
"mtl-compat",
"nats",
]
def _cabal_tool_flag(tool):
"""Return a --with-PROG=PATH flag if input is a recognized Cabal tool. None otherwise."""
if tool.basename in _CABAL_TOOLS:
return "--with-{}={}".format(tool.basename, tool.path)
def _binary_paths(binaries):
return [binary.dirname for binary in binaries.to_list()]
def _concat(sequences):
return [item for sequence in sequences for item in sequence]
def _uniquify(xs):
return depset(xs).to_list()
def _cabal_toolchain_info(hs, cc, workspace_name, runghc):
"""Yields a struct containing the toolchain information needed by the cabal wrapper"""
# If running on darwin but XCode is not installed (i.e., only the Command
# Line Tools are available), then Bazel will make ar_executable point to
# "/usr/bin/libtool". Since we call ar directly, override it.
# TODO: remove this if Bazel fixes its behavior.
# Upstream ticket: https://github.com/bazelbuild/bazel/issues/5127.
ar = cc.tools.ar
if ar.find("libtool") >= 0:
ar = "/usr/bin/ar"
return struct(
ghc = hs.tools.ghc.path,
ghc_pkg = hs.tools.ghc_pkg.path,
hsc2hs = hs.tools.hsc2hs.path,
runghc = runghc.path,
ar = ar,
cc = cc.tools.cc,
ld = cc.tools.ld,
strip = cc.tools.strip,
is_windows = hs.toolchain.is_windows,
workspace = workspace_name,
ghc_cc_args = ghc_cc_program_args(hs, "$CC", "$LD"),
)
def _prepare_cabal_inputs(
hs,
cc,
posix,
workspace_name,
dep_info,
cc_info,
direct_cc_info,
component,
package_id,
tool_inputs,
tool_input_manifests,
cabal,
setup,
setup_deps,
setup_dep_info,
srcs,
cabalopts,
flags,
generate_haddock,
cabal_wrapper,
runghc,
package_database,
verbose,
transitive_haddocks,
generate_paths_module,
is_library = False, # @unused
dynamic_file = None):
"""Compute Cabal wrapper, arguments, inputs."""
with_profiling = is_profiling_enabled(hs)
# Fail if generate_paths_module and profiling are active at the
# same time. For now, the build fails in profiling mode if a
# haskell_cabal_library depends on a normal haskell_library.
# Which is the case with the generate_paths_module
if with_profiling and generate_paths_module:
fail("The generate_paths_module options of haskell_cabal_library/haskell_cabal_binary are not compatible with the profiling mode yet.")
# Haskell library dependencies or indirect C library dependencies are
# already covered by their corresponding package-db entries. We only need
# to add libraries and headers for direct C library dependencies to the
# command line.
direct_libs = get_ghci_library_files(hs, cc.cc_libraries_info, cc.cc_libraries)
# The regular Haskell rules perform mostly static linking, i.e. where
# possible all C library dependencies are linked statically. Cabal has no
# such mode, and since we have to provide dynamic C libraries for
# compilation, they will also be used for linking. Hence, we need to add
# RUNPATH flags for all dynamic C library dependencies. Cabal also produces
# a dynamic and a static Haskell library in one go. The dynamic library
# will link other Haskell libraries dynamically. For those we need to also
# provide RUNPATH flags for dynamic Haskell libraries.
(_, dynamic_libs) = get_library_files(
hs,
cc.cc_libraries_info,
cc.transitive_libraries,
dynamic = True,
)
# Executables built by Cabal will link Haskell libraries statically, so we
# only need to include dynamic C libraries in the runfiles tree.
(_, runfiles_libs) = get_library_files(
hs,
cc.cc_libraries_info,
get_cc_libraries(cc.cc_libraries_info, cc.transitive_libraries),
dynamic = True,
)
# Setup dependencies are loaded by runghc.
setup_libs = get_ghci_library_files(hs, cc.cc_libraries_info, cc.setup_libraries)
# The regular Haskell rules have separate actions for linking and
# compilation to which we pass different sets of libraries as inputs. The
# Cabal rules, in contrast, only have a single action for compilation and
# linking, so we must provide both sets of libraries as inputs to the same
# action.
transitive_compile_libs = get_ghci_library_files(hs, cc.cc_libraries_info, cc.transitive_libraries)
transitive_link_libs = _concat(get_library_files(hs, cc.cc_libraries_info, cc.transitive_libraries))
env = dicts.add(hs.env, cc.env)
env["PATH"] = join_path_list(
hs.toolchain.is_windows,
_binary_paths(tool_inputs) + posix.paths + hs.tools_config.path_for_cabal,
)
if hs.toolchain.is_darwin:
env["SDKROOT"] = "macosx" # See haskell/private/actions/link.bzl
if verbose:
env["CABAL_VERBOSE"] = "True"
package_databases = dep_info.package_databases
transitive_headers = cc_info.compilation_context.headers
direct_include_dirs = depset(transitive = [
direct_cc_info.compilation_context.includes,
direct_cc_info.compilation_context.quote_includes,
direct_cc_info.compilation_context.system_includes,
])
direct_lib_dirs = [file.dirname for file in direct_libs]
runghc_args = [
"--ghc-arg=" + arg
for package_id in setup_deps
for arg in ["-package-id", package_id]
] + [
"--ghc-arg=" + arg
for package_db in setup_dep_info.package_databases.to_list()
for arg in ["-package-db", "./" + _dirname(package_db)]
]
extra_args = ["--flags=" + " ".join(flags)]
ghc_version = [int(x) for x in hs.toolchain.version.split(".")]
if dynamic_file:
# See Note [No PIE when linking] in haskell/private/actions/link.bzl
if not (hs.toolchain.is_darwin or hs.toolchain.is_windows):
if ghc_version < [8, 10]:
extra_args.append("--ghc-option=-optl-no-pie")
extra_args.extend(hs.toolchain.cabalopts + cabalopts)
if dynamic_file:
extra_args.extend(_uniquify(
[
"--ghc-option=-optl-Wl,-rpath," + create_rpath_entry(
binary = dynamic_file,
dependency = lib,
keep_filename = False,
prefix = relative_rpath_prefix(hs.toolchain.is_darwin),
)
for lib in dynamic_libs
],
))
# When building in a static context, we need to make sure that Cabal passes
# a couple of options that ensure any static code it builds can be linked
# correctly.
#
# * If we are using a static runtime, we need to ensure GHC generates
# position-independent code (PIC). On Unix we need to pass GHC both
# `-fPIC` and `-fexternal-dynamic-refs`: with `-fPIC` alone, GHC will
# generate `R_X86_64_PC32` relocations on Unix, which prevent loading its
# static libraries as PIC.
#
# * If we are building fully-statically-linked binaries, we need to ensure that
# we pass arguments to `hsc2hs` such that objects it builds are statically
# linked, otherwise we'll get dynamic linking errors when trying to
# execute those objects to generate code as part of the build. Since the
# static configuration should ensure that all the objects involved are
# themselves statically built, this is just a case of passing `-static` to
# the linker used by `hsc2hs` (which will be our own wrapper script which
# eventually calls `gcc`, etc.).
if hs.toolchain.static_runtime:
extra_args.append("--ghc-option=-fPIC")
if not hs.toolchain.is_windows:
extra_args.append("--ghc-option=-fexternal-dynamic-refs")
if hs.toolchain.fully_static_link:
extra_args.append("--hsc2hs-option=--lflag=-static")
if hs.features.fully_static_link:
extra_args.append("--ghc-option=-optl-static")
path_args = [
"--extra-include-dirs=" + d
for d in direct_include_dirs.to_list()
] + _uniquify(["--extra-lib-dirs=" + d for d in direct_lib_dirs])
if with_profiling:
extra_args.append("--enable-profiling")
extra_ldflags_file = darwin_flags_for_linking_indirect_cc_deps(hs, cc, posix, hs.name, dynamic = True)
# Redundant with _binary_paths() above, but better be explicit when we can.
path_args.extend([_cabal_tool_flag(tool_flag) for tool_flag in tool_inputs.to_list() if _cabal_tool_flag(tool_flag)])
args = struct(
component = component,
pkg_name = package_id,
generate_haddock = generate_haddock,
setup_path = setup.path,
pkg_dir = cabal.dirname,
package_db_path = package_database.dirname,
runghc_args = runghc_args,
extra_args = extra_args,
path_args = path_args,
toolchain_info = _cabal_toolchain_info(hs, cc, workspace_name, runghc),
generate_paths_module = generate_paths_module,
ghc_version = ghc_version,
cabal_basename = cabal.basename,
cabal_dirname = cabal.dirname,
extra_ldflags_file = extra_ldflags_file.path if extra_ldflags_file else None,
package_databases = [p.path for p in package_databases.to_list()],
)
ghc_files = hs.toolchain.bindir + hs.toolchain.libdir
if generate_haddock:
ghc_files.extend(hs.toolchain.docdir)
input_files = [setup, hs.tools.ghc, hs.tools.ghc_pkg, hs.tools.hsc2hs]
if extra_ldflags_file:
input_files.append(extra_ldflags_file)
inputs = depset(
input_files,
transitive = [
depset(srcs),
depset(cc.files),
depset(ghc_files),
package_databases,
setup_dep_info.package_databases,
transitive_headers,
depset(setup_libs),
depset(transitive_compile_libs),
depset(transitive_link_libs),
transitive_haddocks,
setup_dep_info.interface_dirs,
setup_dep_info.hs_libraries,
dep_info.interface_dirs,
dep_info.hs_libraries,
tool_inputs,
],
)
input_manifests = tool_input_manifests + hs.toolchain.cc_wrapper.manifests
return struct(
cabal_wrapper = cabal_wrapper,
args = args,
inputs = inputs,
input_manifests = input_manifests,
env = env,
runfiles = depset(direct = runfiles_libs),
)
def _gather_transitive_haddocks(deps):
transitive_haddocks_list = []
for dep in deps:
if HaddockInfo in dep:
for haddock_files in dep[HaddockInfo].transitive_haddocks.values():
transitive_haddocks_list.extend(haddock_files)
return depset(
direct = transitive_haddocks_list,
)
def _shorten_library_symlink(dynamic_library):
prefix = dynamic_library.owner.workspace_root.replace("_", "_U").replace("/", "_S")
basename = dynamic_library.basename
return paths.join(prefix, basename)
def _haskell_cabal_library_impl(ctx):
hs = haskell_context(ctx)
dep_info = gather_dep_info(ctx.attr.name, ctx.attr.deps)
setup_dep_info = gather_dep_info(ctx.attr.name, ctx.attr.setup_deps)
setup_deps = all_dependencies_package_ids(ctx.attr.setup_deps)
cc = cc_interop_info(
ctx,
override_cc_toolchain = hs.tools_config.maybe_exec_cc_toolchain,
)
# All C and Haskell library dependencies.
cc_info = cc_common.merge_cc_infos(
cc_infos = [dep[CcInfo] for dep in ctx.attr.deps if CcInfo in dep],
)
# Separate direct C library dependencies.
direct_cc_info = cc_common.merge_cc_infos(
cc_infos = [
dep[CcInfo]
for dep in ctx.attr.deps
if CcInfo in dep and not HaskellInfo in dep
],
)
posix = ctx.toolchains["@rules_sh//sh/posix:toolchain_type"]
package_name = ctx.attr.package_name if ctx.attr.package_name else hs.label.name
package_id = "{}-{}{}".format(
package_name,
ctx.attr.version,
"-{}".format(ctx.attr.sublibrary_name) if ctx.attr.sublibrary_name else "",
)
with_profiling = is_profiling_enabled(hs)
user_cabalopts = _expand_make_variables("cabalopts", ctx, ctx.attr.cabalopts)
if ctx.attr.compiler_flags:
fail("ERROR: `compiler_flags` attribute was removed. Use `cabalopts` with `--ghc-option` instead.")
cabal = _find_cabal(ctx.files.srcs)
setup = _find_setup(hs, cabal, ctx.files.srcs)
package_database = hs.actions.declare_file(
"_install/{}.conf.d/package.cache".format(package_id),
sibling = cabal,
)
interfaces_dir = hs.actions.declare_directory(
"_install/{}_iface".format(package_id),
sibling = cabal,
)
data_dir = hs.actions.declare_directory(
"_install/{}_data".format(package_id),
sibling = cabal,
)
with_haddock = ctx.attr.haddock and hs.tools_config.supports_haddock
if with_haddock:
haddock_file = hs.actions.declare_file(
"_install/{}_haddock/{}.haddock".format(package_id, package_name),
sibling = cabal,
)
haddock_html_dir = hs.actions.declare_directory(
"_install/{}_haddock_html".format(package_id),
sibling = cabal,
)
else:
haddock_file = None
haddock_html_dir = None
vanilla_library = hs.actions.declare_file(
"_install/lib/libHS{}.a".format(package_id),
sibling = cabal,
)
if with_profiling:
profiling_library = hs.actions.declare_file(
"_install/lib/libHS{}_p.a".format(package_id),
sibling = cabal,
)
static_library = profiling_library
else:
profiling_library = None
static_library = vanilla_library
if hs.toolchain.static_runtime:
dynamic_library = None
else:
dynamic_library = hs.actions.declare_file(
"_install/lib/libHS{}-ghc{}.{}".format(
package_id,
hs.toolchain.version,
_so_extension(hs),
),
sibling = cabal,
)
(tool_inputs, tool_input_manifests) = ctx.resolve_tools(tools = ctx.attr.tools)
c = _prepare_cabal_inputs(
hs,
cc,
posix,
ctx.workspace_name,
dep_info,
cc_info,
direct_cc_info,
component = "lib:{}".format(ctx.attr.sublibrary_name or ctx.attr.package_name or hs.label.name),
package_id = package_id,
tool_inputs = tool_inputs,
tool_input_manifests = tool_input_manifests,
cabal = cabal,
setup = setup,
setup_deps = setup_deps,
setup_dep_info = setup_dep_info,
srcs = ctx.files.srcs,
cabalopts = user_cabalopts,
flags = ctx.attr.flags,
generate_haddock = with_haddock,
cabal_wrapper = ctx.executable._cabal_wrapper,
runghc = ctx.executable._runghc,
package_database = package_database,
verbose = ctx.attr.verbose,
is_library = True,
generate_paths_module = ctx.attr.generate_paths_module,
dynamic_file = dynamic_library,
transitive_haddocks = _gather_transitive_haddocks(ctx.attr.deps) if with_haddock else depset([]),
)
outputs = [
package_database,
interfaces_dir,
vanilla_library,
data_dir,
]
if with_haddock:
outputs.extend([haddock_file, haddock_html_dir])
if dynamic_library != None:
outputs.append(dynamic_library)
if with_profiling:
outputs.append(profiling_library)
(_, runghc_manifest) = ctx.resolve_tools(tools = [ctx.attr._runghc])
json_args = ctx.actions.declare_file("{}_cabal_wrapper_args.json".format(ctx.label.name))
ctx.actions.write(json_args, json.encode(c.args))
ctx.actions.run(
executable = c.cabal_wrapper,
arguments = [json_args.path],
inputs = depset([json_args], transitive = [c.inputs]),
input_manifests = c.input_manifests + runghc_manifest,
tools = [c.cabal_wrapper, ctx.executable._runghc] + hs.tools_config.tools_for_ghc,
outputs = outputs,
env = c.env,
mnemonic = "HaskellCabalLibrary",
progress_message = "HaskellCabalLibrary {}".format(hs.label),
)
default_info = DefaultInfo(
files = depset([static_library] + ([dynamic_library] if dynamic_library != None else [])),
runfiles = ctx.runfiles(
files = [data_dir],
collect_default = True,
),
)
hs_info = HaskellInfo(
package_databases = depset([package_database], transitive = [dep_info.package_databases]),
empty_lib_package_databases = dep_info.empty_lib_package_databases,
version_macros = sets.make(),
source_files = depset(),
boot_files = depset(),
module_names = depset(),
extra_source_files = depset(),
import_dirs = sets.make(),
hs_libraries = depset(
direct = [lib for lib in [vanilla_library, dynamic_library, profiling_library] if lib],
transitive = [dep_info.hs_libraries],
order = "topological",
),
deps_hs_libraries = depset(
transitive = [dep_info.deps_hs_libraries],
order = "topological",
),
empty_hs_libraries = dep_info.empty_hs_libraries,
interface_dirs = depset([interfaces_dir], transitive = [dep_info.interface_dirs]),
deps_interface_dirs = dep_info.deps_interface_dirs,
compile_flags = [],
user_compile_flags = [],
user_repl_flags = [],
)
lib_info = HaskellLibraryInfo(package_id = package_id, version = None, exports = [])
if with_haddock:
doc_info = generate_unified_haddock_info(
this_package_id = package_id,
this_package_html = haddock_html_dir,
this_package_haddock = haddock_file,
deps = ctx.attr.deps,
)
else:
doc_info = None
cc_toolchain = find_cc_toolchain(ctx)
feature_configuration = cc_common.configure_features(
ctx = ctx,
cc_toolchain = cc_toolchain,
requested_features = ctx.features,
unsupported_features = ctx.disabled_features,
)
linker_input = cc_common.create_linker_input(
owner = ctx.label,
libraries = depset(direct = [
cc_common.create_library_to_link(
actions = ctx.actions,
feature_configuration = feature_configuration,
dynamic_library = dynamic_library,
dynamic_library_symlink_path =
_shorten_library_symlink(dynamic_library) if dynamic_library and ctx.attr.unique_name else "",
static_library = static_library,
cc_toolchain = cc_toolchain,
),
]),
)
compilation_context = cc_common.create_compilation_context()
linking_context = cc_common.create_linking_context(
linker_inputs = depset(direct = [linker_input]),
)
cc_info = cc_common.merge_cc_infos(
cc_infos = [
CcInfo(
compilation_context = compilation_context,
linking_context = linking_context,
),
cc_info,
],
)
output_group_info = OutputGroupInfo(**library_info_output_groups(
name = ctx.label.name,
hs = hs,
hs_info = hs_info,
lib_info = lib_info,
))
result = [default_info, hs_info, cc_info, lib_info, output_group_info]
if with_haddock:
result.append(doc_info)
return result
haskell_cabal_library = rule(
_haskell_cabal_library_impl,
attrs = {
"package_name": attr.string(
doc = "Cabal package name. Defaults to name attribute.",
),
"version": attr.string(
doc = "Version of the Cabal package.",
mandatory = True,
),
"sublibrary_name": attr.string(
doc = "sublibrary of the Cabal package to build",
),
"haddock": attr.bool(
default = True,
doc = "Whether to generate haddock documentation.",
),
"srcs": attr.label_list(
allow_files = True,
doc = "All files required to build the package, including the Cabal file.",
),
"deps": attr.label_list(
aspects = [haskell_cc_libraries_aspect],
doc = "Package build dependencies. Note, setup dependencies need to be declared separately using `setup_deps`.",
),
"setup_deps": attr.label_list(
aspects = [haskell_cc_libraries_aspect],
doc = "Dependencies for custom setup Setup.hs.",
),
"cabalopts": attr.string_list(
doc = """Additional flags to pass to `Setup.hs configure`. Subject to make variable expansion.
Use `--ghc-option=OPT` to configure additional compiler flags.
Use `--haddock-option=--optghc=OPT` if these flags are required for haddock generation as well.
""",
),
"compiler_flags": attr.string_list(
doc = """REMOVED. Use `cabalopts` with `--ghc-option` instead.
Flags to pass to Haskell compiler, in addition to those defined the cabal file. Subject to Make variable substitution.""",
),
"tools": attr.label_list(
cfg = "exec",
allow_files = True,
doc = """Tool dependencies. They are built using the host configuration, since
the tools are executed as part of the build.""",
),
"generate_paths_module": attr.bool(
doc = """ If True the rule will generate a [Paths_{pkgname}](https://cabal.readthedocs.io/en/3.4/cabal-package.html#accessing-data-files-from-package-code) module based on the haskell_runfiles library.
In that case, the `@rules_haskell//tools/runfiles` target should also be added to the deps attribute,
and the `runfiles` package should be added to the component's `build-depends` section of the `.cabal` file.
WARNING: this is not supported in profiling mode yet.
""",
default = False,
),
"flags": attr.string_list(
doc = "List of Cabal flags, will be passed to `Setup.hs configure --flags=...`.",
),
"_cabal_wrapper": attr.label(
executable = True,
cfg = "exec",
default = Label("@rules_haskell//haskell:cabal_wrapper"),
),
"_runghc": attr.label(
executable = True,
cfg = "exec",
default = Label("@rules_haskell//haskell:runghc"),
),
"_cc_toolchain": attr.label(
default = Label("@rules_cc//cc:current_cc_toolchain"),
),
"verbose": attr.bool(
default = True,
doc = "Whether to show the output of the build",
),
"unique_name": attr.bool(
default = False,
doc = """Whether the library name is known to be unique within the
workspace. This is used by `stack_snapshot` where library names are
known to be unique within the snapshot. If true, then the dynamic
library symlink underneath `_solib_<cpu>` will be shortened to
avoid exceeding the MACH-O header size limit on MacOS.""",
),
},
toolchains = use_cc_toolchain() + [
"@rules_haskell//haskell:toolchain",
"@rules_sh//sh/posix:toolchain_type",
],
fragments = ["cpp"],
doc = """\
Use Cabal to build a library.
### Examples
```bzl
haskell_cabal_library(
name = "lib-0.1.0.0",
srcs = ["lib.cabal", "Lib.hs", "Setup.hs"],
)
haskell_toolchain_library(name = "base")
haskell_binary(
name = "bin",
deps = [":base", ":lib-0.1.0.0"],
srcs = ["Main.hs"],
)
```
This rule does not use `cabal-install`. It calls the package's
`Setup.hs` script directly if one exists, or the default one if not.
All sources files that would have been part of a Cabal sdist need to
be listed in `srcs` (crucially, including the `.cabal` file).
A `haskell_cabal_library` can be substituted for any
`haskell_library`. The two are interchangeable in most contexts.
However, using a plain `haskell_library` sometimes leads to better
build times, and does not require drafting a `.cabal` file.
""",
)
def _haskell_cabal_binary_impl(ctx):
hs = haskell_context(ctx)
dep_info = gather_dep_info(ctx.attr.name, ctx.attr.deps)
setup_dep_info = gather_dep_info(ctx.attr.name, ctx.attr.setup_deps)
setup_deps = all_dependencies_package_ids(ctx.attr.setup_deps)
cc = cc_interop_info(
ctx,
override_cc_toolchain = hs.tools_config.maybe_exec_cc_toolchain,
)
# All C and Haskell library dependencies.
cc_info = cc_common.merge_cc_infos(
cc_infos = [dep[CcInfo] for dep in ctx.attr.deps if CcInfo in dep],
)
# Separate direct C library dependencies.
direct_cc_info = cc_common.merge_cc_infos(
cc_infos = [
dep[CcInfo]
for dep in ctx.attr.deps
if CcInfo in dep and not HaskellInfo in dep
],
)
posix = ctx.toolchains["@rules_sh//sh/posix:toolchain_type"]
exe_name = ctx.attr.exe_name if ctx.attr.exe_name else hs.label.name
user_cabalopts = _expand_make_variables("cabalopts", ctx, ctx.attr.cabalopts)
if ctx.attr.compiler_flags:
fail("ERROR: `compiler_flags` attribute was removed. Use `cabalopts` with `--ghc-option` instead.")
cabal = _find_cabal(ctx.files.srcs)
setup = _find_setup(hs, cabal, ctx.files.srcs)
package_database = hs.actions.declare_file(
"_install/{}.conf.d/package.cache".format(hs.label.name),
sibling = cabal,
)
binary = hs.actions.declare_file(
"_install/bin/{name}{ext}".format(
name = exe_name,
ext = ".exe" if hs.toolchain.is_windows else "",
),
sibling = cabal,
)
data_dir = hs.actions.declare_directory(
"_install/{}_data".format(hs.label.name),
sibling = cabal,
)
(tool_inputs, tool_input_manifests) = ctx.resolve_tools(tools = ctx.attr.tools)
c = _prepare_cabal_inputs(
hs,
cc,
posix,
ctx.workspace_name,
dep_info,
cc_info,
direct_cc_info,
component = "exe:{}".format(exe_name),
package_id = hs.label.name,
tool_inputs = tool_inputs,
tool_input_manifests = tool_input_manifests,
cabal = cabal,
setup = setup,
setup_deps = setup_deps,
setup_dep_info = setup_dep_info,
srcs = ctx.files.srcs,
cabalopts = user_cabalopts,
flags = ctx.attr.flags,
generate_haddock = False,
cabal_wrapper = ctx.executable._cabal_wrapper,
runghc = ctx.executable._runghc,
package_database = package_database,
verbose = ctx.attr.verbose,
generate_paths_module = ctx.attr.generate_paths_module,
dynamic_file = binary,
transitive_haddocks = _gather_transitive_haddocks(ctx.attr.deps) if hs.tools_config.supports_haddock else depset([]),
)
(_, runghc_manifest) = ctx.resolve_tools(tools = [ctx.attr._runghc])
json_args = ctx.actions.declare_file("{}_cabal_wrapper_args.json".format(ctx.label.name))
ctx.actions.write(json_args, json.encode(c.args))
ctx.actions.run(
executable = c.cabal_wrapper,
arguments = [json_args.path],
inputs = depset([json_args], transitive = [c.inputs]),
input_manifests = c.input_manifests + runghc_manifest,
outputs = [
package_database,
binary,
data_dir,
],
tools = [c.cabal_wrapper, ctx.executable._runghc] + hs.tools_config.tools_for_ghc,
env = c.env,
mnemonic = "HaskellCabalBinary",
progress_message = "HaskellCabalBinary {}".format(hs.label),
)
hs_info = HaskellInfo(
package_databases = dep_info.package_databases,
empty_lib_package_databases = dep_info.empty_lib_package_databases,
version_macros = sets.make(),
source_files = depset(),
boot_files = depset(),
extra_source_files = depset(),
import_dirs = sets.make(),
hs_libraries = dep_info.hs_libraries,
deps_hs_libraries = dep_info.deps_hs_libraries,
empty_hs_libraries = dep_info.empty_hs_libraries,
interface_dirs = dep_info.interface_dirs,
deps_interface_dirs = dep_info.deps_interface_dirs,
compile_flags = [],
user_compile_flags = [],
user_repl_flags = [],
)
default_info = DefaultInfo(
files = depset([binary]),
executable = binary,
runfiles = ctx.runfiles(
files = [data_dir],
transitive_files = c.runfiles,
collect_default = True,
),
)
return [hs_info, cc_info, default_info]
haskell_cabal_binary = rule(
_haskell_cabal_binary_impl,
executable = True,
attrs = {
"exe_name": attr.string(
doc = "Cabal executable component name. Defaults to the value of the name attribute.",
),
"srcs": attr.label_list(
allow_files = True,
doc = "All files required to build the package, including the Cabal file.",
),
"deps": attr.label_list(
aspects = [haskell_cc_libraries_aspect],
doc = "Package build dependencies. Note, setup dependencies need to be declared separately using `setup_deps`.",
),
"setup_deps": attr.label_list(
aspects = [haskell_cc_libraries_aspect],
doc = "Dependencies for custom setup Setup.hs.",
),
"cabalopts": attr.string_list(
doc = """Additional flags to pass to `Setup.hs configure`. Subject to make variable expansion.
Use `--ghc-option=OPT` to configure additional compiler flags.
Use `--haddock-option=--optghc=OPT` if these flags are required for haddock generation as well.
""",
),
"compiler_flags": attr.string_list(
doc = """DEPRECATED. Use `cabalopts` with `--ghc-option` instead.
Flags to pass to Haskell compiler, in addition to those defined the cabal file. Subject to Make variable substitution.""",
),
"tools": attr.label_list(
cfg = "exec",
allow_files = True,
doc = """Tool dependencies. They are built using the host configuration, since
the tools are executed as part of the build.""",
),
"generate_paths_module": attr.bool(
doc = """ If True the rule will generate a [Paths_{pkgname}](https://cabal.readthedocs.io/en/3.4/cabal-package.html#accessing-data-files-from-package-code) module based on the haskell_runfiles library.
In that case, the `@rules_haskell//tools/runfiles` target should also be added to the deps attribute,
and the `runfiles` package should be added to the component's `build-depends` section of the `.cabal` file.
WARNING: this is not supported in profiling mode yet.
""",
default = False,
),
"flags": attr.string_list(
doc = "List of Cabal flags, will be passed to `Setup.hs configure --flags=...`.",
),
"_cabal_wrapper": attr.label(
executable = True,
cfg = "exec",
default = Label("@rules_haskell//haskell:cabal_wrapper"),
),
"_runghc": attr.label(
executable = True,
cfg = "exec",
default = Label("@rules_haskell//haskell:runghc"),
),
"_cc_toolchain": attr.label(
default = Label("@rules_cc//cc:current_cc_toolchain"),
),
"verbose": attr.bool(
default = True,
doc = "Whether to show the output of the build",
),
},
toolchains = use_cc_toolchain() + [
"@rules_haskell//haskell:toolchain",
"@rules_sh//sh/posix:toolchain_type",
],
fragments = ["cpp"],
doc = """\
Use Cabal to build a binary.
### Examples
```bzl
haskell_cabal_binary(
name = "happy",
srcs = glob(["**"]),
)
```
This rule assumes that the .cabal file defines a single executable
with the same name as the package.
This rule does not use `cabal-install`. It calls the package's
`Setup.hs` script directly if one exists, or the default one if not.
All sources files that would have been part of a Cabal sdist need to
be listed in `srcs` (crucially, including the `.cabal` file).
""",
)
_STACK_DEFAULT_VERSION = "2.7.5"
# minimum required version