/
tag_engine.ex
1356 lines (1110 loc) · 42 KB
/
tag_engine.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 Phoenix.LiveView.TagEngine do
@moduledoc """
An EEx engine that understands tags.
This cannot be directly used by Phoenix applications.
Instead, it is the building block by engines such as
`Phoenix.LiveView.HTMLEngine`.
It is typically invoked like this:
EEx.compile_string(source,
engine: Phoenix.LiveView.TagEngine,
line: 1,
file: path,
caller: __CALLER__,
source: source,
tag_handler: FooBarEngine
)
Where `:tag_handler` implements the behaviour defined by this module.
"""
@doc """
Classify the tag type from the given binary.
This must return a tuple containing the type of the tag and the name of tag.
For instance, for LiveView which uses HTML as default tag handler this would
return `{:tag, 'div'}` in case the given binary is identified as HTML tag.
You can also return {:error, "reason"} so that the compiler will display this
error.
"""
@callback classify_type(name :: binary()) :: {type :: atom(), name :: binary()}
@doc """
Returns if the given binary is either void or not.
That's mainly useful for HTML tags and used internally by the compiler. You
can just implement as `def void?(_), do: false` if you want to ignore this.
"""
@callback void?(name :: binary()) :: boolean()
@doc """
Implements processing of attributes.
It returns a quoted expression or attributes. If attributes are returned,
the second element is a list where each element in the list represents
one attribute.If the list element is a two-element tuple, it is assumed
the key is the name to be statically written in the template. The second
element is the value which is also statically written to the template whenever
possible (such as binaries or binaries inside a list).
"""
@callback handle_attributes(ast :: Macro.t(), meta :: keyword) ::
{:attributes, [{binary(), Macro.t()} | Macro.t()]} | {:quoted, Macro.t()}
@doc """
Callback invoked to add annotations around the whole body of a template.
"""
@callback annotate_body(caller :: Macro.Env.t()) :: {String.t(), String.t()} | nil
@doc """
Callback invoked to add caller annotations before a function component is invoked.
"""
@callback annotate_caller(file :: String.t(), line :: integer()) :: String.t() | nil
@doc """
Renders a component defined by the given function.
This function is rarely invoked directly by users. Instead, it is used by `~H`
and other engine implementations to render `Phoenix.Component`s. For example,
the following:
<MyApp.Weather.city name="Kraków" />
Is the same as:
<%= component(
&MyApp.Weather.city/1,
[name: "Kraków"],
{__ENV__.module, __ENV__.function, __ENV__.file, __ENV__.line}
) %>
"""
def component(func, assigns, caller)
when (is_function(func, 1) and is_list(assigns)) or is_map(assigns) do
assigns =
case assigns do
%{__changed__: _} -> assigns
_ -> assigns |> Map.new() |> Map.put_new(:__changed__, nil)
end
case func.(assigns) do
%Phoenix.LiveView.Rendered{} = rendered ->
%{rendered | caller: caller}
%Phoenix.LiveView.Component{} = component ->
component
other ->
raise RuntimeError, """
expected #{inspect(func)} to return a %Phoenix.LiveView.Rendered{} struct
Ensure your render function uses ~H to define its template.
Got:
#{inspect(other)}
"""
end
end
@doc """
Define a inner block, generally used by slots.
This macro is mostly used by custom HTML engines that provide
a `slot` implementation and rarely called directly. The
`name` must be the assign name the slot/block will be stored
under.
If you're using HEEx templates, you should use its higher
level `<:slot>` notation instead. See `Phoenix.Component`
for more information.
"""
defmacro inner_block(name, do: do_block) do
__inner_block__(do_block, name)
end
@doc false
# TODO: Make me private once Phoenix.LiveView.Helpers are removed
def __inner_block__([{:->, meta, _} | _] = do_block, key) do
inner_fun = {:fn, meta, do_block}
quote do
fn parent_changed, arg ->
var!(assigns) =
unquote(__MODULE__).__assigns__(var!(assigns), unquote(key), parent_changed)
_ = var!(assigns)
unquote(inner_fun).(arg)
end
end
end
def __inner_block__(do_block, key) do
quote do
fn parent_changed, arg ->
var!(assigns) =
unquote(__MODULE__).__assigns__(var!(assigns), unquote(key), parent_changed)
_ = var!(assigns)
unquote(do_block)
end
end
end
@doc false
def __assigns__(assigns, key, parent_changed) do
# If the component is in its initial render (parent_changed == nil)
# or the slot/block key is in parent_changed, then we render the
# function with the assigns as is.
#
# Otherwise, we will set changed to an empty list, which is the same
# as marking everything as not changed. This is correct because
# parent_changed will always be marked as changed whenever any of the
# assigns it references inside is changed. It will also be marked as
# changed if it has any variable (such as the ones coming from let).
if is_nil(parent_changed) or Map.has_key?(parent_changed, key) do
assigns
else
Map.put(assigns, :__changed__, %{})
end
end
alias Phoenix.LiveView.Tokenizer
alias Phoenix.LiveView.Tokenizer.ParseError
@behaviour EEx.Engine
@impl true
def init(opts) do
{subengine, opts} = Keyword.pop(opts, :subengine, Phoenix.LiveView.Engine)
tag_handler = Keyword.fetch!(opts, :tag_handler)
%{
cont: :text,
tokens: [],
subengine: subengine,
substate: subengine.init(opts),
file: Keyword.get(opts, :file, "nofile"),
indentation: Keyword.get(opts, :indentation, 0),
caller: Keyword.fetch!(opts, :caller),
previous_token_slot?: false,
source: Keyword.fetch!(opts, :source),
tag_handler: tag_handler
}
end
## These callbacks return AST
@impl true
def handle_body(state) do
%{tokens: tokens, file: file, cont: cont, source: source, caller: caller} = state
tokens = Tokenizer.finalize(tokens, file, cont, source)
token_state =
state
|> token_state(nil)
|> handle_tokens(tokens)
|> validate_unclosed_tags!("template")
opts = [root: token_state.root || false]
opts =
if body_annotation = caller && has_tags?(tokens) && state.tag_handler.annotate_body(caller) do
[body_annotation: body_annotation] ++ opts
else
opts
end
ast = invoke_subengine(token_state, :handle_body, [opts])
quote do
require Phoenix.LiveView.TagEngine
unquote(ast)
end
end
defp has_tags?(tokens) do
Enum.any?(tokens, fn
{:text, _, _} -> false
{:expr, _, _} -> false
_ -> true
end)
end
defp validate_unclosed_tags!(%{tags: []} = state, _context) do
state
end
defp validate_unclosed_tags!(%{tags: [tag | _]} = state, context) do
{_type, _name, _attrs, meta} = tag
message = "end of #{context} reached without closing tag for <#{meta.tag_name}>"
raise_syntax_error!(message, meta, state)
end
@impl true
def handle_end(state) do
state
|> token_state(false)
|> handle_tokens(Enum.reverse(state.tokens))
|> validate_unclosed_tags!("do-block")
|> invoke_subengine(:handle_end, [])
end
defp token_state(
%{
subengine: subengine,
substate: substate,
file: file,
caller: caller,
source: source,
indentation: indentation,
tag_handler: tag_handler
},
root
) do
%{
subengine: subengine,
substate: substate,
source: source,
file: file,
stack: [],
tags: [],
slots: [],
caller: caller,
root: root,
previous_token_slot?: false,
indentation: indentation,
tag_handler: tag_handler
}
end
defp handle_tokens(token_state, tokens) do
Enum.reduce(tokens, token_state, &handle_token/2)
end
## These callbacks update the state
@impl true
def handle_begin(state) do
update_subengine(%{state | tokens: []}, :handle_begin, [])
end
@impl true
def handle_text(state, meta, text) do
%{file: file, indentation: indentation, tokens: tokens, cont: cont, source: source} = state
tokenizer_state = Tokenizer.init(indentation, file, source, state.tag_handler)
{tokens, cont} = Tokenizer.tokenize(text, meta, tokens, cont, tokenizer_state)
%{
state
| tokens: tokens,
cont: cont,
source: state.source
}
end
@impl true
def handle_expr(%{tokens: tokens} = state, marker, expr) do
%{state | tokens: [{:expr, marker, expr} | tokens]}
end
## Helpers
defp push_substate_to_stack(%{substate: substate, stack: stack} = state) do
%{state | stack: [{:substate, substate} | stack]}
end
defp pop_substate_from_stack(%{stack: [{:substate, substate} | stack]} = state) do
%{state | stack: stack, substate: substate}
end
defp invoke_subengine(%{subengine: subengine, substate: substate}, fun, args) do
apply(subengine, fun, [substate | args])
end
defp update_subengine(state, fun, args) do
%{state | substate: invoke_subengine(state, fun, args), previous_token_slot?: false}
end
defp init_slots(state) do
%{state | slots: [[] | state.slots]}
end
defp add_inner_block({roots?, attrs, locs}, ast, tag_meta) do
{roots?, [{:inner_block, ast} | attrs], [line_column(tag_meta) | locs]}
end
defp add_slot(state, slot_name, slot_assigns, slot_info, tag_meta, special_attrs) do
%{slots: [slots | other_slots]} = state
slot = {slot_name, slot_assigns, special_attrs, {tag_meta, slot_info}}
%{state | slots: [[slot | slots] | other_slots], previous_token_slot?: true}
end
defp validate_slot!(%{tags: [{type, _, _, _} | _]}, _name, _tag_meta)
when type in [:remote_component, :local_component],
do: :ok
defp validate_slot!(state, slot_name, meta) do
message =
"invalid slot entry <:#{slot_name}>. A slot entry must be a direct child of a component"
raise_syntax_error!(message, meta, state)
end
defp pop_slots(%{slots: [slots | other_slots]} = state) do
# Perform group_by by hand as we need to group two distinct maps.
{acc_assigns, acc_info, specials} =
Enum.reduce(slots, {%{}, %{}, %{}}, fn {key, assigns, special, info},
{acc_assigns, acc_info, specials} ->
special? = Map.has_key?(special, ":if") or Map.has_key?(special, ":for")
specials = Map.update(specials, key, special?, &(&1 or special?))
case acc_assigns do
%{^key => existing_assigns} ->
acc_assigns = %{acc_assigns | key => [assigns | existing_assigns]}
%{^key => existing_info} = acc_info
acc_info = %{acc_info | key => [info | existing_info]}
{acc_assigns, acc_info, specials}
%{} ->
{Map.put(acc_assigns, key, [assigns]), Map.put(acc_info, key, [info]), specials}
end
end)
acc_assigns =
Enum.into(acc_assigns, %{}, fn {key, assigns_ast} ->
cond do
# No special entry, return it as a list
not Map.fetch!(specials, key) ->
{key, assigns_ast}
# We have a special entry and multiple entries, we have to flatten
match?([_, _ | _], assigns_ast) ->
{key, quote(do: List.flatten(unquote(assigns_ast)))}
# A single special entry is guaranteed to return a list from the expression
true ->
{key, hd(assigns_ast)}
end
end)
{Map.to_list(acc_assigns), Map.to_list(acc_info), %{state | slots: other_slots}}
end
defp push_tag(state, token) do
%{state | tags: [token | state.tags]}
end
defp pop_tag!(
%{tags: [{type, tag_name, _attrs, _meta} = tag | tags]} = state,
{:close, type, tag_name, _}
) do
{tag, %{state | tags: tags}}
end
defp pop_tag!(
%{tags: [{type, tag_open_name, _attrs, tag_open_meta} | _]} = state,
{:close, type, tag_close_name, tag_close_meta}
) do
hint = closing_void_hint(tag_close_name, state)
message = """
unmatched closing tag. Expected </#{tag_open_name}> for <#{tag_open_name}> \
at line #{tag_open_meta.line}, got: </#{tag_close_name}>#{hint}\
"""
raise_syntax_error!(message, tag_close_meta, state)
end
defp pop_tag!(state, {:close, _type, tag_name, tag_meta}) do
hint = closing_void_hint(tag_name, state)
message = "missing opening tag for </#{tag_name}>#{hint}"
raise_syntax_error!(message, tag_meta, state)
end
defp closing_void_hint(tag_name, state) do
if state.tag_handler.void?(tag_name) do
" (note <#{tag_name}> is a void tag and cannot have any content)"
else
""
end
end
## handle_token
# Expr
defp handle_token({:expr, marker, expr}, state) do
state
|> set_root_on_not_tag()
|> update_subengine(:handle_expr, [marker, expr])
end
# Text
defp handle_token({:text, text, %{line_end: line, column_end: column}}, state) do
text = if state.previous_token_slot?, do: String.trim_leading(text), else: text
if text == "" do
state
else
state
|> set_root_on_not_tag()
|> update_subengine(:handle_text, [[line: line, column: column], text])
end
end
# Remote function component (self close)
defp handle_token(
{:remote_component, name, attrs, %{closing: :self} = tag_meta},
state
) do
attrs = remove_phx_no_break(attrs)
{mod_ast, mod_size, fun} = decompose_remote_component_tag!(name, tag_meta, state)
%{line: line, column: column} = tag_meta
{assigns, attr_info} =
build_self_close_component_assigns({"remote component", name}, attrs, tag_meta.line, state)
mod = expand_with_line(mod_ast, line, state.caller)
store_component_call({mod, fun}, attr_info, [], line, state)
meta = [line: line, column: column + mod_size]
call = {{:., meta, [mod_ast, fun]}, meta, []}
ast =
quote line: tag_meta.line do
Phoenix.LiveView.TagEngine.component(
&(unquote(call) / 1),
unquote(assigns),
{__MODULE__, __ENV__.function, __ENV__.file, unquote(tag_meta.line)}
)
end
case pop_special_attrs!(attrs, tag_meta, state) do
{false, _tag_meta, _attrs} ->
state
|> set_root_on_not_tag()
|> maybe_anno_caller(meta, state.file, line)
|> update_subengine(:handle_expr, ["=", ast])
{true, new_meta, _new_attrs} ->
state
|> push_substate_to_stack()
|> update_subengine(:handle_begin, [])
|> set_root_on_not_tag()
|> maybe_anno_caller(meta, state.file, line)
|> update_subengine(:handle_expr, ["=", ast])
|> handle_special_expr(new_meta)
end
end
# Remote function component (with inner content)
defp handle_token({:remote_component, name, attrs, tag_meta}, state) do
mod_fun = decompose_remote_component_tag!(name, tag_meta, state)
tag_meta = Map.put(tag_meta, :mod_fun, mod_fun)
case pop_special_attrs!(attrs, tag_meta, state) do
{false, tag_meta, attrs} ->
state
|> set_root_on_not_tag()
|> push_tag({:remote_component, name, attrs, tag_meta})
|> init_slots()
|> push_substate_to_stack()
|> update_subengine(:handle_begin, [])
{true, new_meta, new_attrs} ->
state
|> set_root_on_not_tag()
|> push_tag({:remote_component, name, new_attrs, new_meta})
|> init_slots()
|> push_substate_to_stack()
|> update_subengine(:handle_begin, [])
|> push_substate_to_stack()
|> update_subengine(:handle_begin, [])
end
end
defp handle_token({:close, :remote_component, _name, _tag_close_meta} = token, state) do
{{:remote_component, name, attrs, tag_meta}, state} = pop_tag!(state, token)
%{mod_fun: {mod_ast, mod_size, fun}, line: line, column: column} = tag_meta
mod = expand_with_line(mod_ast, line, state.caller)
attrs = remove_phx_no_break(attrs)
{assigns, attr_info, slot_info, state} =
build_component_assigns({"remote component", name}, attrs, line, tag_meta, state)
store_component_call({mod, fun}, attr_info, slot_info, line, state)
meta = [line: line, column: column + mod_size]
call = {{:., meta, [mod_ast, fun]}, meta, []}
ast =
quote line: line do
Phoenix.LiveView.TagEngine.component(
&(unquote(call) / 1),
unquote(assigns),
{__MODULE__, __ENV__.function, __ENV__.file, unquote(line)}
)
end
|> tag_slots(slot_info)
state
|> pop_substate_from_stack()
|> maybe_anno_caller(meta, state.file, line)
|> update_subengine(:handle_expr, ["=", ast])
|> handle_special_expr(tag_meta)
end
# Slot (self close)
defp handle_token(
{:slot, slot_name, attrs, %{closing: :self} = tag_meta},
state
) do
slot_name = String.to_atom(slot_name)
validate_slot!(state, slot_name, tag_meta)
attrs = remove_phx_no_break(attrs)
%{line: line} = tag_meta
{special, roots, attrs, attr_info} = split_component_attrs({"slot", slot_name}, attrs, state)
let = special[":let"]
with {_, let_meta} <- let do
message = "cannot use :let on a slot without inner content"
raise_syntax_error!(message, let_meta, state)
end
attrs = [__slot__: slot_name, inner_block: nil] ++ attrs
assigns = wrap_special_slot(special, merge_component_attrs(roots, attrs, line))
add_slot(state, slot_name, assigns, attr_info, tag_meta, special)
end
# Slot (with inner content)
defp handle_token({:slot, slot_name, _attrs, tag_meta} = token, state) do
validate_slot!(state, slot_name, tag_meta)
state
|> push_tag(token)
|> push_substate_to_stack()
|> update_subengine(:handle_begin, [])
end
defp handle_token({:close, :slot, slot_name, _tag_close_meta} = token, state) do
slot_name = String.to_atom(slot_name)
{{:slot, _name, attrs, %{line: line} = tag_meta}, state} = pop_tag!(state, token)
attrs = remove_phx_no_break(attrs)
{special, roots, attrs, attr_info} = split_component_attrs({"slot", slot_name}, attrs, state)
clauses = build_component_clauses(special[":let"], state)
ast =
quote line: line do
Phoenix.LiveView.TagEngine.inner_block(unquote(slot_name), do: unquote(clauses))
end
attrs = [__slot__: slot_name, inner_block: ast] ++ attrs
assigns = wrap_special_slot(special, merge_component_attrs(roots, attrs, line))
inner = add_inner_block(attr_info, ast, tag_meta)
state
|> add_slot(slot_name, assigns, inner, tag_meta, special)
|> pop_substate_from_stack()
end
# Local function component (self close)
defp handle_token({:local_component, name, attrs, %{closing: :self} = tag_meta}, state) do
fun = String.to_atom(name)
%{line: line, column: column} = tag_meta
attrs = remove_phx_no_break(attrs)
{assigns, attr_info} =
build_self_close_component_assigns({"local component", fun}, attrs, line, state)
mod = actual_component_module(state.caller, fun)
store_component_call({mod, fun}, attr_info, [], line, state)
meta = [line: line, column: column]
call = {fun, meta, __MODULE__}
ast =
quote line: line do
Phoenix.LiveView.TagEngine.component(
&(unquote(call) / 1),
unquote(assigns),
{__MODULE__, __ENV__.function, __ENV__.file, unquote(line)}
)
end
case pop_special_attrs!(attrs, tag_meta, state) do
{false, _tag_meta, _attrs} ->
state
|> set_root_on_not_tag()
|> maybe_anno_caller(meta, state.file, line)
|> update_subengine(:handle_expr, ["=", ast])
{true, new_meta, _new_attrs} ->
state
|> push_substate_to_stack()
|> update_subengine(:handle_begin, [])
|> set_root_on_not_tag()
|> maybe_anno_caller(meta, state.file, line)
|> update_subengine(:handle_expr, ["=", ast])
|> handle_special_expr(new_meta)
end
end
# Local function component (with inner content)
defp handle_token({:local_component, name, attrs, tag_meta} = token, state) do
case pop_special_attrs!(attrs, tag_meta, state) do
{false, _tag_meta, _attrs} ->
state
|> set_root_on_not_tag()
|> push_tag(token)
|> init_slots()
|> push_substate_to_stack()
|> update_subengine(:handle_begin, [])
{true, new_meta, new_attrs} ->
state
|> set_root_on_not_tag()
|> push_tag({:local_component, name, new_attrs, new_meta})
|> init_slots()
|> push_substate_to_stack()
|> update_subengine(:handle_begin, [])
|> push_substate_to_stack()
|> update_subengine(:handle_begin, [])
end
end
defp handle_token({:close, :local_component, _name, _tag_close_meta} = token, state) do
{{:local_component, name, attrs, tag_meta}, state} = pop_tag!(state, token)
fun = String.to_atom(name)
%{line: line, column: column} = tag_meta
attrs = remove_phx_no_break(attrs)
mod = actual_component_module(state.caller, fun)
{assigns, attr_info, slot_info, state} =
build_component_assigns({"local component", fun}, attrs, line, tag_meta, state)
store_component_call({mod, fun}, attr_info, slot_info, line, state)
meta = [line: line, column: column]
call = {fun, meta, __MODULE__}
ast =
quote line: line do
Phoenix.LiveView.TagEngine.component(
&(unquote(call) / 1),
unquote(assigns),
{__MODULE__, __ENV__.function, __ENV__.file, unquote(line)}
)
end
|> tag_slots(slot_info)
state
|> pop_substate_from_stack()
|> maybe_anno_caller(meta, state.file, line)
|> update_subengine(:handle_expr, ["=", ast])
|> handle_special_expr(tag_meta)
end
# HTML element (self close)
defp handle_token({:tag, name, attrs, %{closing: closing} = tag_meta}, state) do
suffix = if closing == :void, do: ">", else: "></#{name}>"
attrs = remove_phx_no_break(attrs)
validate_phx_attrs!(attrs, tag_meta, state)
case pop_special_attrs!(attrs, tag_meta, state) do
{false, tag_meta, attrs} ->
state
|> set_root_on_tag()
|> handle_tag_and_attrs(name, attrs, suffix, to_location(tag_meta))
{true, new_meta, new_attrs} ->
state
|> push_substate_to_stack()
|> update_subengine(:handle_begin, [])
|> set_root_on_not_tag()
|> handle_tag_and_attrs(name, new_attrs, suffix, to_location(new_meta))
|> handle_special_expr(new_meta)
end
end
# HTML element
defp handle_token({:tag, name, attrs, tag_meta} = token, state) do
validate_phx_attrs!(attrs, tag_meta, state)
attrs = remove_phx_no_break(attrs)
case pop_special_attrs!(attrs, tag_meta, state) do
{false, tag_meta, attrs} ->
state
|> set_root_on_tag()
|> push_tag(token)
|> handle_tag_and_attrs(name, attrs, ">", to_location(tag_meta))
{true, new_meta, new_attrs} ->
state
|> push_substate_to_stack()
|> update_subengine(:handle_begin, [])
|> set_root_on_not_tag()
|> push_tag({:tag, name, new_attrs, new_meta})
|> handle_tag_and_attrs(name, new_attrs, ">", to_location(new_meta))
end
end
defp handle_token({:close, :tag, name, tag_meta} = token, state) do
{{:tag, _name, _attrs, tag_open_meta}, state} = pop_tag!(state, token)
state
|> update_subengine(:handle_text, [to_location(tag_meta), "</#{name}>"])
|> handle_special_expr(tag_open_meta)
end
# Pop the given attr from attrs. Raises if the given attr is duplicated within
# attrs.
#
# Examples:
#
# attrs = [{":for", {...}}, {"class", {...}}]
# pop_special_attrs!(state, ":for", attrs, %{}, state)
# => {%{for: parsed_ast}}, {{":for", {...}}, [{"class", {...}]}}
#
# attrs = [{"class", {...}}]
# pop_special_attrs!(state, ":for", attrs, %{}, state)
# => {%{}, []}
defp pop_special_attrs!(attrs, tag_meta, state) do
Enum.reduce([for: ":for", if: ":if"], {false, tag_meta, attrs}, fn
{attr, string_attr}, {special_acc, meta_acc, attrs_acc} ->
attrs_acc
|> List.keytake(string_attr, 0)
|> raise_if_duplicated_special_attr!(state)
|> case do
{{^string_attr, {:expr, _, _} = expr, meta}, attrs} ->
parsed_expr = parse_expr!(expr, state.file)
validate_quoted_special_attr!(string_attr, parsed_expr, meta, state)
{true, Map.put(meta_acc, attr, parsed_expr), attrs}
{{^string_attr, _expr, meta}, _attrs} ->
message = "#{string_attr} must be an expression between {...}"
raise_syntax_error!(message, meta, state)
nil ->
{special_acc, meta_acc, attrs_acc}
end
end)
end
defp raise_if_duplicated_special_attr!({{attr, _expr, _meta}, attrs} = result, state) do
case List.keytake(attrs, attr, 0) do
{{attr, _expr, meta}, _attrs} ->
message =
"cannot define multiple #{inspect(attr)} attributes. Another #{inspect(attr)} has already been defined at line #{meta.line}"
raise_syntax_error!(message, meta, state)
nil ->
result
end
end
defp raise_if_duplicated_special_attr!(nil, _state), do: nil
# Root tracking
defp set_root_on_not_tag(%{root: root, tags: tags} = state) do
if tags == [] and root != false do
%{state | root: false}
else
state
end
end
defp set_root_on_tag(state) do
case state do
%{root: nil, tags: []} -> %{state | root: true}
%{root: true, tags: []} -> %{state | root: false}
%{root: bool} when is_boolean(bool) -> state
end
end
## handle_tag_and_attrs
defp handle_tag_and_attrs(state, name, attrs, suffix, meta) do
state
|> update_subengine(:handle_text, [meta, "<#{name}"])
|> handle_tag_attrs(meta, attrs)
|> update_subengine(:handle_text, [meta, suffix])
end
defp handle_tag_attrs(state, meta, attrs) do
Enum.reduce(attrs, state, fn
{:root, {:expr, _, _} = expr, _attr_meta}, state ->
ast = parse_expr!(expr, state.file)
# If we have a map of literal keys, we unpack it as a list
# to simplify the downstream check.
ast =
with {:%{}, _meta, pairs} <- ast,
true <- literal_keys?(pairs) do
pairs
else
_ -> ast
end
handle_tag_expr_attrs(state, meta, ast)
{name, {:expr, _, _} = expr, _attr_meta}, state ->
handle_tag_expr_attrs(state, meta, [{name, parse_expr!(expr, state.file)}])
{name, {:string, value, %{delimiter: ?"}}, _attr_meta}, state ->
update_subengine(state, :handle_text, [meta, ~s( #{name}="#{value}")])
{name, {:string, value, %{delimiter: ?'}}, _attr_meta}, state ->
update_subengine(state, :handle_text, [meta, ~s( #{name}='#{value}')])
{name, nil, _attr_meta}, state ->
update_subengine(state, :handle_text, [meta, " #{name}"])
end)
end
defp handle_tag_expr_attrs(state, meta, ast) do
# It is safe to List.wrap/1 because if we receive nil,
# it would become the interpolation of nil, which is an
# empty string anyway.
case state.tag_handler.handle_attributes(ast, meta) do
{:attributes, attrs} ->
Enum.reduce(attrs, state, fn
{name, value}, state ->
state = update_subengine(state, :handle_text, [meta, ~s( #{name}=")])
state =
value
|> List.wrap()
|> Enum.reduce(state, fn
binary, state when is_binary(binary) ->
update_subengine(state, :handle_text, [meta, binary])
expr, state ->
update_subengine(state, :handle_expr, ["=", expr])
end)
update_subengine(state, :handle_text, [meta, ~s(")])
quoted, state ->
update_subengine(state, :handle_expr, ["=", quoted])
end)
{:quoted, quoted} ->
update_subengine(state, :handle_expr, ["=", quoted])
end
end
defp parse_expr!({:expr, value, %{line: line, column: col}}, file) do
Code.string_to_quoted!(value, line: line, column: col, file: file)
end
defp literal_keys?([{key, _value} | rest]) when is_atom(key) or is_binary(key),
do: literal_keys?(rest)
defp literal_keys?([]), do: true
defp literal_keys?(_other), do: false
defp handle_special_expr(state, tag_meta) do
ast =
case tag_meta do
%{for: for_expr, if: if_expr} ->
quote do
for unquote(for_expr), unquote(if_expr),
do: unquote(invoke_subengine(state, :handle_end, []))
end
%{for: for_expr} ->
quote do
for unquote(for_expr), do: unquote(invoke_subengine(state, :handle_end, []))
end
%{if: if_expr} ->
quote do
if unquote(if_expr), do: unquote(invoke_subengine(state, :handle_end, []))
end
%{} ->
nil
end
if ast do
state
|> pop_substate_from_stack()
|> update_subengine(:handle_expr, ["=", ast])
else
state
end
end
## build_self_close_component_assigns/build_component_assigns
defp build_self_close_component_assigns(type_component, attrs, line, state) do
{special, roots, attrs, attr_info} = split_component_attrs(type_component, attrs, state)
raise_if_let!(special[":let"], state.file)
{merge_component_attrs(roots, attrs, line), attr_info}
end
defp build_component_assigns(type_component, attrs, line, tag_meta, state) do
{special, roots, attrs, attr_info} = split_component_attrs(type_component, attrs, state)
clauses = build_component_clauses(special[":let"], state)
inner_block =
quote line: line do
Phoenix.LiveView.TagEngine.inner_block(:inner_block, do: unquote(clauses))
end
inner_block_assigns =
quote line: line do
%{
__slot__: :inner_block,
inner_block: unquote(inner_block)
}
end
{slot_assigns, slot_info, state} = pop_slots(state)
slot_info = [
{:inner_block, [{tag_meta, add_inner_block({false, [], []}, inner_block, tag_meta)}]}
| slot_info
]
attrs = attrs ++ [{:inner_block, [inner_block_assigns]} | slot_assigns]
{merge_component_attrs(roots, attrs, line), attr_info, slot_info, state}
end
defp split_component_attrs(type_component, attrs, state) do
{special, roots, attrs, locs} =
attrs
|> Enum.reverse()
|> Enum.reduce(
{%{}, [], [], []},
&split_component_attr(&1, &2, state, type_component)
)
{special, roots, attrs, {roots != [], attrs, locs}}
end
defp split_component_attr(
{:root, {:expr, value, %{line: line, column: col}}, _attr_meta},
{special, r, a, locs},