-
Notifications
You must be signed in to change notification settings - Fork 23
/
extension.ex
2282 lines (1938 loc) · 65.7 KB
/
extension.ex
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
defmodule Spark.Dsl.Extension do
@moduledoc """
An extension to the Spark DSL.
This allows configuring custom DSL components, whose configurations
can then be read back. This guide is still a work in progress, but should
serve as a decent example of what is possible. Open issues on Github if you
have any issues/something is unclear.
The example at the bottom shows how you might build a (not very contextually
relevant) DSL extension that would be used like so:
defmodule MyApp.Vehicle do
use Spark.Dsl
end
defmodule MyApp.MyResource do
use MyApp.Vehicle,
extensions: [MyApp.CarExtension]
cars do
car :ford, :focus, trim: :sedan
car :toyota, :corolla
end
end
The extension:
defmodule MyApp.CarExtension do
@car_schema [
make: [
type: :atom,
required: true,
doc: "The make of the car"
],
model: [
type: :atom,
required: true,
doc: "The model of the car"
],
type: [
type: :atom,
required: true,
doc: "The type of the car",
default: :sedan
]
]
@car %Spark.Dsl.Entity{
name: :car,
describe: "Adds a car",
examples: [
"car :ford, :focus"
],
target: MyApp.Car,
args: [:make, :model],
schema: @car_schema
}
@cars %Spark.Dsl.Section{
name: :cars, # The DSL constructor will be `cars`
describe: \"\"\"
Configure what cars are available.
More, deeper explanation. Always have a short one liner explanation,
an empty line, and then a longer explanation.
\"\"\",
entities: [
@car # See `Spark.Dsl.Entity` docs
],
schema: [
default_manufacturer: [
type: :atom,
doc: "The default manufacturer"
]
]
}
use Spark.Dsl.Extension, sections: [@cars]
end
Often, we will need to do complex validation/validate based on the configuration
of other resources. Due to the nature of building compile time DSLs, there are
many restrictions around that process. To support these complex use cases, extensions
can include `transformers` which can validate/transform the DSL state after all basic
sections/entities have been created. See `Spark.Dsl.Transformer` for more information.
Transformers are provided as an option to `use`, like so:
use Spark.Dsl.Extension, sections: [@cars], transformers: [
MyApp.Transformers.ValidateNoOverlappingMakesAndModels
]
By default, the generated modules will have names like `__MODULE__.SectionName.EntityName`, and that could
potentially conflict with modules you are defining, so you can specify the `module_prefix` option, which would allow
you to prefix the modules with something like `__MODULE__.Dsl`, so that the module path generated might be something like
`__MODULE__.Dsl.SectionName.EntityName`, and you could then have the entity struct be `__MODULE__.SectionName.EntityName`
without conflicts.
To expose the configuration of your DSL, define functions that use the
helpers like `get_entities/2` and `get_opt/3`. For example:
defmodule MyApp.Cars do
def cars(resource) do
Spark.Dsl.Extension.get_entities(resource, [:cars])
end
end
MyApp.Cars.cars(MyResource)
# [%MyApp.Car{...}, %MyApp.Car{...}]
See the documentation for `Spark.Dsl.Section` and `Spark.Dsl.Entity` for more information
"""
@type t :: module
@callback sections() :: [Spark.Dsl.section()]
@callback module_imports() :: [module]
@callback transformers() :: [module]
@callback verifiers() :: [module]
@callback persisters() :: [module]
@callback explain(map) :: String.t() | nil
@callback add_extensions() :: [module]
@optional_callbacks explain: 1
defp persisted!(resource, key, default) do
resource.persisted(key, default)
rescue
_ in [UndefinedFunctionError, ArgumentError] ->
try do
Map.get(Module.get_attribute(resource, :persisted) || %{}, key)
rescue
ArgumentError ->
try do
resource.persisted(key)
rescue
_ ->
reraise ArgumentError,
"""
`#{inspect(resource)}` is not a Spark DSL module.
""",
__STACKTRACE__
end
end
end
@doc "Get the entities configured for a given section"
def get_entities(map, nil), do: get_entities(map, [])
def get_entities(%struct{}, path) do
get_entities(struct, path)
end
def get_entities(map, path) when not is_list(path), do: get_entities(map, [path])
def get_entities(map, path) when is_map(map) do
Spark.Dsl.Transformer.get_entities(map, path) || []
end
def get_entities(resource, path) do
resource.entities(path)
rescue
_ in [UndefinedFunctionError, ArgumentError] ->
try do
dsl = Module.get_attribute(resource, :spark_dsl_config) || %{}
Spark.Dsl.Transformer.get_entities(dsl, path) || []
rescue
ArgumentError ->
try do
resource.entities(path)
rescue
_ ->
reraise ArgumentError,
"""
`#{inspect(resource)}` is not a Spark DSL module.
""",
__STACKTRACE__
end
end
end
@doc "Get a value that was persisted while transforming or compiling the resource, e.g `:primary_key`"
def get_persisted(resource, key, default \\ nil)
def get_persisted(%struct{}, key, default) do
get_persisted(struct, key, default)
end
def get_persisted(map, key, default) when is_map(map) do
Spark.Dsl.Transformer.get_persisted(map, key, default)
end
def get_persisted(resource, :module, _) when is_atom(resource) do
resource
end
def get_persisted(resource, key, default) do
persisted!(resource, key, default)
end
@doc """
Get an option value for a section at a given path.
Checks to see if it has been overridden via configuration.
"""
def get_opt(resource, path, value, default \\ nil, configurable? \\ false) do
case fetch_opt(resource, path, value, configurable?) do
{:ok, value} -> value
:error -> default
end
end
def fetch_opt(resource, path, value, configurable? \\ false)
def fetch_opt(%struct{}, path, value, configurable?) do
fetch_opt(struct, path, value, configurable?)
end
def fetch_opt(map, path, value, configurable?) when not is_list(path) do
fetch_opt(map, [path], value, configurable?)
end
def fetch_opt(map, path, value, configurable?) when is_map(map) do
if configurable? do
case get_opt_config(Spark.Dsl.Transformer.get_persisted(map, :module), path, value) do
{:ok, value} ->
{:ok, value}
_ ->
Spark.Dsl.Transformer.fetch_option(map, path, value)
end
else
Spark.Dsl.Transformer.fetch_option(map, path, value)
end
end
def fetch_opt(resource, path, key, configurable?) do
if configurable? do
case get_opt_config(resource, path, key) do
{:ok, value} ->
{:ok, value}
_ ->
do_fetch_opt(resource, path, key)
end
else
do_fetch_opt(resource, path, key)
end
end
defp do_fetch_opt(resource, path, key) do
resource.fetch_opt(path, key)
rescue
_ in [UndefinedFunctionError, ArgumentError] ->
try do
dsl = Module.get_attribute(resource, :spark_dsl_config) || %{}
Spark.Dsl.Transformer.fetch_option(dsl, path, key)
rescue
ArgumentError ->
try do
resource.fetch_opt(path, key)
rescue
_ ->
reraise ArgumentError,
"""
`#{inspect(resource)}` is not a Spark DSL module.
""",
__STACKTRACE__
end
end
end
defdelegate doc(sections, depth \\ 1), to: Spark.CheatSheet
defdelegate doc_index(sections, depth \\ 1), to: Spark.CheatSheet
@doc false
defdelegate doc_entity(entity, depth \\ 1), to: Spark.CheatSheet
@doc false
defdelegate doc_section(section, depth \\ 1), to: Spark.CheatSheet
def get_opt_config(resource, path, value) do
with otp_app when not is_nil(otp_app) <- get_persisted(resource, :otp_app),
{:ok, config} <- Application.fetch_env(otp_app, resource) do
path
|> List.wrap()
|> Kernel.++([value])
|> Enum.reduce_while({:ok, config}, fn key, {:ok, config} ->
if Keyword.keyword?(config) do
case Keyword.fetch(config, key) do
{:ok, value} -> {:cont, {:ok, value}}
:error -> {:halt, :error}
end
else
{:halt, :error}
end
end)
end
end
@doc false
defmacro __using__(opts) do
quote bind_quoted: [
sections: opts[:sections] || [],
transformers: opts[:transformers] || [],
verifiers: opts[:verifiers] || [],
persisters: opts[:persisters] || [],
dsl_patches: opts[:dsl_patches] || [],
imports: opts[:imports] || [],
module_prefix: opts[:module_prefix],
add_extensions: opts[:add_extensions] || []
],
generated: true do
alias Spark.Dsl.Extension
module_prefix = module_prefix || __MODULE__
@behaviour Extension
Extension.build(__MODULE__, module_prefix, sections, dsl_patches)
@_sections sections
@_transformers transformers
@_verifiers verifiers
@_persisters persisters
@_dsl_patches dsl_patches
@_imports imports
@_add_extensions add_extensions
@doc false
def sections, do: set_docs(@_sections)
@doc false
def verifiers, do: [Spark.Dsl.Verifiers.VerifyEntityUniqueness | @_verifiers]
@doc false
def persisters, do: @_persisters
@doc false
def module_imports, do: @_imports
@doc false
def module_prefix, do: unquote(module_prefix) || __MODULE__
@doc false
def transformers, do: @_transformers
@doc false
def dsl_patches, do: @_dsl_patches
@doc false
def add_extensions, do: @_add_extensions
defp set_docs(items) when is_list(items) do
Enum.map(items, &set_docs/1)
end
defp set_docs(%Spark.Dsl.Entity{} = entity) do
entity
|> Map.put(:docs, Spark.Dsl.Extension.doc_entity(entity))
|> Map.put(
:entities,
Enum.map(entity.entities || [], fn {key, value} -> {key, set_docs(value)} end)
)
end
defp set_docs(%Spark.Dsl.Section{} = section) do
section
|> Map.put(:entities, set_docs(section.entities))
|> Map.put(:sections, set_docs(section.sections))
|> Map.put(:docs, Spark.Dsl.Extension.doc_section(section))
end
end
end
@doc false
def explain(spark, opts, extensions, dsl_state) do
prefix =
case spark.explain(dsl_state, opts) do
nil ->
""
explanation ->
"""
#{explanation}
"""
end
extension_explanations =
extensions
|> Enum.filter(&function_exported?(&1, :explain, 1))
|> Enum.map(& &1.explain(dsl_state))
|> Enum.reject(fn docs -> docs in [nil, ""] end)
|> Enum.join("\n\n")
prefix <> extension_explanations
end
@doc false
def prepare(extensions) do
body =
quote generated: true, location: :keep do
@extensions unquote(extensions)
@persist {:spark_extensions, @extensions}
end
imports =
for extension <- extensions || [] do
extension = Macro.expand_once(extension, __ENV__)
sections =
try do
extension.sections()
rescue
_ -> []
end
only_sections =
sections
|> Enum.reject(& &1.top_level?)
|> Enum.map(&{&1.name, 1})
quote generated: true, location: :keep do
require Spark.Dsl.Extension
import unquote(extension), only: unquote(only_sections)
end
end
top_level_imports =
Enum.flat_map(extensions || [], fn extension ->
extension = Macro.expand_once(extension, __ENV__)
sections =
try do
extension.sections()
rescue
_ ->
[]
end
sections
|> Enum.filter(& &1.top_level?)
|> Enum.flat_map(fn section ->
section_mod_name =
Spark.Dsl.Extension.section_mod_name(extension.module_prefix(), [], section)
configured_imports =
for module <- section.imports do
quote generated: true do
import unquote(module)
end
end
entity_modules =
Enum.map(
section.entities,
&Spark.Dsl.Extension.entity_mod_name(section_mod_name, [], [], &1)
)
entity_imports =
for module <- entity_modules do
quote generated: true do
import unquote(module), only: :macros
end
end
section_imports =
for nested_section <- section.sections do
module =
Spark.Dsl.Extension.section_mod_name(
extension.module_prefix(),
[section.name],
nested_section
)
quote generated: true do
import unquote(module), only: :macros
end
end
opts_import =
if Map.get(section, :schema, []) == [] do
[]
else
opts_module = Spark.Dsl.Extension.module_concat([section_mod_name, Options])
[
quote generated: true do
import unquote(opts_module)
end
]
end
patch_modules =
extensions
|> Spark.Dsl.Extension.get_entity_dsl_patches([section.name])
|> Enum.reject(&(&1 in entity_modules))
patch_imports =
for module <- patch_modules do
quote generated: true do
import unquote(module), only: :macros
end
end
opts_import ++
section_imports ++ entity_imports ++ patch_imports ++ configured_imports
end)
end)
configured_imports =
extensions
|> Kernel.||([])
|> Enum.flat_map(fn extension ->
extension = Macro.expand_once(extension, __ENV__)
extension.module_imports()
end)
|> Enum.map(fn module ->
quote generated: true, location: :keep do
import unquote(module)
end
end)
[body | imports ++ configured_imports ++ top_level_imports]
end
@doc false
defmacro set_state(additional_persisted_data, fragments, transform? \\ true) do
quote generated: true,
location: :keep,
bind_quoted: [
additional_persisted_data: additional_persisted_data,
transform?: transform?,
fragments: fragments
] do
alias Spark.Dsl.Transformer
persist =
additional_persisted_data
|> Keyword.put(:extensions, @extensions || [])
|> Enum.into(%{})
spark_dsl_config =
{__MODULE__, :spark_sections}
|> Process.get([])
|> Enum.map(fn {_extension, section_path} ->
{section_path,
Process.get(
{__MODULE__, :spark, section_path},
[]
)}
end)
|> Enum.into(%{})
|> Map.update(
:persist,
persist,
&Map.merge(&1, persist)
)
|> Spark.Dsl.handle_fragments(fragments)
for {key, _value} <- Process.get() do
if is_tuple(key) and elem(key, 0) == __MODULE__ do
Process.delete(key)
end
end
transformers_to_run =
if transform? do
@extensions
|> Enum.flat_map(& &1.transformers())
|> Transformer.sort()
|> Enum.reject(& &1.after_compile?())
|> Enum.concat(Enum.flat_map(@extensions, & &1.persisters()))
else
[]
end
@spark_dsl_config __MODULE__
|> Spark.Dsl.Extension.run_transformers(
transformers_to_run,
spark_dsl_config,
__ENV__
)
|> Spark.Dsl.Extension.await_tasks()
end
end
@doc false
def await_tasks(dsl) do
Task.await_many(dsl[:persist][:spark_compile_tasks] || [], :infinity)
%{dsl | persist: Map.delete(dsl.persist, :spark_compile_tasks)}
end
def run_transformers(mod, transformers, spark_dsl_config, env) do
spark_dsl_config = Map.update!(spark_dsl_config, :persist, &Map.put(&1, :env, env))
Enum.reduce_while(transformers, spark_dsl_config, fn transformer, dsl ->
result =
try do
transformer.transform(dsl)
rescue
e in Spark.Error.DslError ->
reraise %{e | module: mod}, __STACKTRACE__
e ->
reraise "Exception in transformer #{inspect(transformer)} on #{inspect(mod)}: \n\n#{Exception.message(e)}",
__STACKTRACE__
end
case result do
:ok ->
{:cont, dsl}
:halt ->
{:halt, dsl}
{:warn, new_dsl, warnings} ->
warnings
|> List.wrap()
|> Enum.each(&IO.warn(&1, Macro.Env.stacktrace(env)))
{:cont, new_dsl}
{:ok, new_dsl} ->
{:cont, new_dsl}
{:error, %Spark.Error.DslError{} = e} ->
raise_transformer_error(transformer, %{e | module: mod})
{:error, error} ->
raise_transformer_error(transformer, error)
other ->
raise """
Invalid return from transformer: #{inspect(transformer)}
Expected one of:
* `:ok`
* `:halt`
* `{:warn, dsl_state, warnings}`
* `{:ok, dsl_state}`
* `{:error, error}`
Got:
#{inspect(other)}
"""
end
end)
end
defp raise_transformer_error(
_transformer,
%Spark.Error.DslError{stacktrace: %{stacktrace: stacktrace}} = error
)
when not is_nil(stacktrace) do
reraise error, stacktrace
end
defp raise_transformer_error(transformer, error) do
if is_exception(error) do
raise error
else
raise "Error while running transformer #{inspect(transformer)}: #{inspect(error)}"
end
end
@doc false
def all_section_paths(path, prior \\ [])
def all_section_paths(nil, _), do: []
def all_section_paths([], _), do: []
def all_section_paths(sections, prior) do
Enum.flat_map(sections, fn section ->
nested = all_section_paths(section.sections, [section.name, prior])
[Enum.reverse(prior) ++ [section.name] | nested]
end)
|> Enum.uniq()
end
@doc false
def all_section_config_paths(path, prior \\ [])
def all_section_config_paths(nil, _), do: []
def all_section_config_paths([], _), do: []
def all_section_config_paths(sections, prior) do
Enum.flat_map(sections, fn section ->
nested = all_section_config_paths(section.sections, [section.name, prior])
fields =
Enum.map(section.schema, fn {key, _} ->
{Enum.reverse(prior) ++ [section.name], key}
end)
fields ++ nested
end)
|> Enum.uniq()
end
@doc false
defmacro build(extension, module_prefix, sections, dsl_patches) do
quote generated: true,
bind_quoted: [
dsl_patches: dsl_patches,
sections: sections,
extension: extension,
module_prefix: module_prefix
] do
alias Spark.Dsl.Extension
{:ok, agent} = Agent.start_link(fn -> [] end)
agent_and_pid = {agent, self()}
# This won't work for nested recursive entities (that don't appear in the top level)
# but I'm not aware of anyone doing anything like that, and so I'm okay with it for now
all_recursive_entity_module_names =
sections
|> Enum.flat_map(fn section ->
section.entities
|> Enum.filter(& &1.recursive_as)
|> Enum.flat_map(fn entity ->
entity_mod_name =
Spark.Dsl.Extension.module_concat([
module_prefix,
Macro.camelize(to_string(section.name)),
Macro.camelize(to_string(entity.name))
])
mod_name =
Spark.Dsl.Extension.module_concat([
entity_mod_name,
Options
])
opts_mod_unimport =
quote generated: true do
import unquote(mod_name), only: []
end
entity_mod_unimports =
entity.entities
|> Enum.flat_map(fn {key, nested_entities} ->
nested_entities
|> List.wrap()
|> Enum.map(fn nested_entity ->
nested_entity_path = [section.name, key]
nested_entity_mod_name =
Spark.Dsl.Extension.entity_mod_name(
entity_mod_name,
nested_entity_path,
[],
nested_entity
)
quote do
import unquote(nested_entity_mod_name), only: []
end
end)
end)
[opts_mod_unimport | entity_mod_unimports]
end)
end)
top_level_unimports = Spark.Dsl.Extension.top_level_unimports(sections, module_prefix)
Enum.each(sections, fn section ->
top_level_unimports =
if section.top_level? do
[]
else
top_level_unimports
end
Spark.Dsl.Extension.async_compile(agent_and_pid, fn ->
Extension.build_section(
agent_and_pid,
extension,
section,
all_recursive_entity_module_names ++ top_level_unimports,
[],
module_prefix
)
end)
end)
Enum.each(dsl_patches, fn %Spark.Dsl.Patch.AddEntity{
section_path: section_path,
entity: entity
} ->
Spark.Dsl.Extension.async_compile(agent_and_pid, fn ->
Extension.build_entity(
agent_and_pid,
module_prefix,
extension,
section_path,
entity,
[],
[],
[]
)
end)
end)
Spark.Dsl.Extension.await_all_tasks(agent)
Agent.stop(agent)
end
end
@doc false
def top_level_unimports(sections, module_prefix, skip \\ nil) do
sections
|> Enum.filter(& &1.top_level?)
|> Enum.flat_map(fn section ->
section_mod_name = Spark.Dsl.Extension.section_mod_name(module_prefix, [], section)
configured_unimports =
for module <- section.imports do
quote generated: true do
import unquote(module), only: []
end
end
entity_unimports =
for entity <- section.entities,
Map.delete(entity, :docs) != Map.delete(skip || %{}, :docs) do
module = Spark.Dsl.Extension.entity_mod_name(section_mod_name, [], [], entity)
quote generated: true do
import unquote(module), only: []
end
end
section_unimports =
for nested_section <- section.sections do
module =
Spark.Dsl.Extension.section_mod_name(
module_prefix,
[section.name],
nested_section
)
quote generated: true do
import unquote(module), only: []
end
end
opts_unimport =
if Map.get(section, :schema, []) == [] do
[]
else
opts_module = Spark.Dsl.Extension.module_concat([section_mod_name, Options])
[
quote generated: true do
import unquote(opts_module), only: []
end
]
end
opts_unimport ++
section_unimports ++ entity_unimports ++ configured_unimports
end)
end
@doc false
defmacro build_section(
agent,
extension,
section,
unimports \\ [],
path \\ [],
module_prefix \\ nil
) do
quote bind_quoted: [
agent: agent,
section: section,
path: path,
extension: extension,
module_prefix: module_prefix,
unimports: unimports
],
generated: true do
alias Spark.Dsl
{section_modules, entity_modules, unimport_modules, opts_module} =
Dsl.Extension.do_build_section(
agent,
module_prefix,
extension,
section,
path,
unimports
)
@doc false
# This macro argument is only called `body` so that it looks nicer
# in the DSL docs
unless section.top_level? && path == [] do
@doc false
defmacro unquote(section.name)(body) do
opts_module = unquote(opts_module)
section_path = unquote(path ++ [section.name])
section = unquote(Macro.escape(section))
unimports = unquote(Macro.escape(unimports))
unimport_modules = unquote(Macro.escape(unimport_modules))
extension = unquote(extension)
configured_imports =
for module <- unquote(section.imports) do
quote generated: true do
import unquote(module)
end
end
entity_imports =
for module <- unquote(entity_modules) do
quote generated: true do
import unquote(module), only: :macros
end
end
section_imports =
for module <- unquote(section_modules) do
quote generated: true do
import unquote(module), only: :macros
end
end
opts_import =
if Map.get(unquote(Macro.escape(section)), :schema, []) == [] do
[]
else
[
quote generated: true do
import unquote(opts_module)
end
]
end
configured_unimports =
for module <- unquote(section.imports) do
quote generated: true do
import unquote(module), only: []
end
end
entity_unimports =
for module <- unquote(unimport_modules) do
quote generated: true do
import unquote(module), only: []
end
end
section_unimports =
for module <- unquote(section_modules) do
quote generated: true do
import unquote(module), only: []
end
end
opts_unimport =
if Map.get(unquote(Macro.escape(section)), :schema, []) == [] do
[]
else
[
quote generated: true do
import unquote(opts_module), only: []
end
]
end
entity_modules = unquote(entity_modules)
patch_modules =
__CALLER__.module
|> Module.get_attribute(:extensions, [])
|> Spark.Dsl.Extension.get_entity_dsl_patches(section_path)
|> Enum.reject(&(&1 in entity_modules))
patch_module_imports =
Enum.map(patch_modules, fn patch_module ->
quote do
import unquote(patch_module), only: :macros
end
end)
patch_module_unimports =
Enum.map(patch_modules, fn patch_module ->
quote do
import unquote(patch_module), only: []
end
end)
other_extension_unimports =
if unquote(path) == [] do
for extension <- Module.get_attribute(__CALLER__.module, :extensions) do
quote do
import unquote(extension), only: []
end
end
else
[]
end