lib/phlex/compiler/method_compiler.rb

Lines

93%

531 of 567 covered

Branches

78%

267 of 340 covered

Methods

95%

93 of 97 covered

Not run
52-5356-5774354367414438470-471505507509519-521539-540551599781834850860867971103710411055105710841103116111631170
Never called
1# frozen_string_literal: true
2
31module Phlex::Compiler
4 # Rewrites one method so that the element and helper calls it makes become
5 # output nodes in its tree, which the Emitter then lowers to buffer appends.
61 class MethodCompiler < Refract::MutationVisitor
71 include Builder
8
91 Attributes = Data.define(:hoisted, :parts)
101 NO_ATTRIBUTES = Attributes.new(hoisted: [], parts: [])
11
12 # A part of the opening tag that runs a serialiser, which can raise.
131 Serialized = Data.define(:node)
14
15 # How a value is serialised, as cases tested in order: each a condition
16 # and an outcome, with an outcome for when none holds. An outcome is a
17 # Value, whose text goes between the attribute's name and closing quote,
18 # Text, which is the attribute's whole text, or further Cases.
191 Typed = Data.define(:name, :cases)
201 Cases = Data.define(:cases, :otherwise)
211 Value = Data.define(:node)
221 Text = Data.define(:node)
23
241 TokenChoice = Data.define(:condition, :truthy, :falsy)
251 TOKEN_CONDITIONS_LIMIT = 3
26
271 UNINLINABLE_BLOCK = "it has parameters or contains a return, break, next or local assignment"
281 GUARDED_BLOCK_DEPTH_LIMIT = 4
29
301 def initialize(environment, path, diagnostics: Diagnostics.new(path))
31240 super()
32240 @environment = environment
33240 @path = path
34240 @diagnostics = diagnostics
35240 @locals = Locals.new
36240 @preamble = []
37240 @appends = 0
38240 @guarded_blocks = 0
39240 @compiling_calls = true
40 end
41
42 # Returns nil when there's nothing to compile, unless the method is being
43 # recompiled, when the definition must still replace the compiled one.
441 def compile(node, keep_uncompiled: false)
45238 tree = visit(node)
46238 return tree if @appends == 0 && keep_uncompiled
47227 return nil if @appends == 0
48
49157 Emitter.new(@locals).visit(tree)
50 end
51
520 visit Refract::ClassNode do |node|
530 node
54 end
55
560 visit Refract::ModuleNode do |node|
570 node
58 end
59
601 visit Refract::LambdaNode do |node|
6122 without_compiling_calls { super(node) }
62 end
63
64 # A modifier form guards a single statement, so once its body compiles to
65 # several it has to become a block form. A `begin` body already holds
66 # several, and turning `begin … end while` into `while` would change it
67 # from a post-test loop to a pre-test loop.
681 [Refract::IfNode, Refract::UnlessNode, Refract::WhileNode, Refract::UntilNode].each do |modifier_node|
694 visit modifier_node do |node|
70196 appends = @appends
71196 result = super(node)
72
73196 if node.inline && @appends > appends && !(node.statements in Refract::StatementsNode[body: [Refract::BeginNode]])
740 result.copy(inline: false)then never taken
75 else
76196 result
77 end
78 end
79 end
80
81 # Compiled code is evaluated under a path of its own, so `__FILE__` must
82 # keep naming the real file.
831 visit Refract::SourceFileNode do |node|
8416 string(@path)
85 end
86
87 # Generated locals all start with `__phlex_`, so a method that already uses
88 # a name like that is refused rather than risk a collision. Parameter
89 # defaults run before the body, so before the state local exists, so
90 # element calls in them stay as calls.
911 visit Refract::DefNode do |node|
92239 return node unless @stack.size == 1
93
94472 if (reserved = (LocalsScanner.names(node) | BareCallScanner.names(node)).find { |name| name.start_with?("__phlex_") })
952 @diagnostics.refuse(node, "#{reserved} is a name the compiler reserves for locals; names starting with __phlex_ can't be used")
962 return node
97 end
98
99472 parameters = without_compiling_calls(because: "it's in a parameter default") { visit(node.parameters) }
100236 body = visit(node.body)
101
102236 node.copy(
103 parameters:,
104 body: mapping_exceptions([*@preamble, body])
105 )
106 end
107
1081 visit Refract::CallNode do |node|
1091375 if @compiling_calls
1101191 if statement?(node) && node.receiver.nil? && (compiled = compile_call(node))
111316 return compiled
112 end
113184 elsif @uncompiled_because && node.receiver.nil? && (@environment.element(node.name) || @environment.helper?(node.name))
1141 keep_call(node, @uncompiled_because)
115 end
116
1171059 super(node)
118 end
119
120 # A block passed to a method we don't know about might be evaluated against a
121 # different receiver, so the compiled body is only used when self is
122 # unchanged, and the original is kept for when it isn't. Each level of
123 # nesting repeats the original bodies inside it, so past a few levels the
124 # calls are left alone.
125 #
126 # The block may outlive the method or be built before rendering starts, so
127 # the compiled body reads the state afresh rather than trusting the one
128 # read on entry, and the block maps its own exceptions, as the method's
129 # rescue may no longer be on the stack.
1301 visit Refract::BlockNode do |node|
131186 return super(node) unless @compiling_calls
132112 return without_compiling_calls { super(node) } unless node.bodythen never taken
133
134112 if @guarded_blocks == GUARDED_BLOCK_DEPTH_LIMIT
1351 @diagnostics.report(node, "calls in this block are left to the runtime because it's nested #{GUARDED_BLOCK_DEPTH_LIMIT} blocks deep")
1362 return mapping_block_exceptions(without_compiling_calls { super(node) })
137 end
138
139111 if (conflict = ReparseScanner.conflict(node))
1401 @diagnostics.report(node, "calls in this block are left to the runtime because #{conflict}")
1412 return mapping_block_exceptions(without_compiling_calls { super(node) })
142 end
143
144110 appends = @appends
145110 @guarded_blocks += 1
146110 compiled = visit(node.body)
147110 @guarded_blocks -= 1
148186 return mapping_block_exceptions(without_compiling_calls { super(node) }) if appends == @appends
149
15068 original = without_compiling_calls { visit(node.body) }
151
15234 node.copy(
15334 parameters: without_compiling_calls(because: "it's in a parameter default") { visit(node.parameters) },
154 body: statements([
155 mapping_exceptions([
156 if_node(
157 call(read(self_local), :__phlex_equal__?, Refract::SelfNode.new),
158 [write(Locals::STATE, Refract::InstanceVariableReadNode.new(name: :@_state)), compiled],
159 else_body: [original]
160 ),
161 ]),
162 ])
163 )
164 end
165
1661 private def mapping_block_exceptions(block)
16778 block.copy(body: statements([mapping_exceptions([block.body])]))
168 end
169
1701 private def mapping_exceptions(body)
171348 begin_node(
172 body,
173 rescue_clause: rescue_node(
174 [constant("Exception")],
175 Refract::LocalVariableTargetNode.new(name: Locals::EXCEPTION, depth: nil),
176 [call(constant("Kernel"), :raise, call(constant("Phlex"), :__map_exception__, read(Locals::EXCEPTION)))]
177 )
178 )
179 end
180
1811 private def statement?(node)
1821191 Refract::StatementsNode === @stack[-2]
183 end
184
185 # Visits code whose calls must stay as they are, so only `__FILE__` is
186 # rewritten. Element and helper calls found there are reported with the
187 # reason, unless the code is a copy of something compiled elsewhere.
1881 private def without_compiling_calls(because: nil)
189429 compiling_calls, uncompiled_because = @compiling_calls, @uncompiled_because
190429 @compiling_calls = false
191429 @uncompiled_because = because
192429 yield
193 ensure
194429 @compiling_calls, @uncompiled_because = compiling_calls, uncompiled_because
195 end
196
197 # A call lowered to output, or kept with output compiled inside its block,
198 # relies on the method meaning what it did at compile time. A call kept
199 # as it was, with nothing compiled inside, doesn't.
2001 private def compile_call(node)
201522 appends = @appends
202
203522 compiled = if (element = @environment.element(node.name))
204263 element.void ? compile_void_element(node, element.tag) : compile_standard_element(node, element.tag)
205259 elsif @environment.helper?(node.name)
206163 case node.name
20733 in :plain then compile_plain(node)
2086 in :raw then compile_raw(node)
2094 in :whitespace then compile_whitespace(node)
2101 in :doctype then compile_doctype(node)
2113 in :comment then compile_comment(node)
21217 in :fragment then compile_fragment(node)
21322 in :svg then compile_inline_svg(node)
21477 else nil
215 end
216 end
217
218522 @environment.inlined << node.name if compiled && (@appends > appends || !(Refract::CallNode === compiled))
219522 compiled
220 end
221
222 # The runtime closes the element however its content exits, which the
223 # enclosure reproduces. Only the method's own block is forwarded inline,
224 # since another expression is evaluated, and may be nil, when the
225 # element is called.
2261 private def compile_standard_element(node, tag)
227247 if Refract::BlockArgumentNode === node.block
2284 return compile_forwarded_element(node, tag) if node.block.expression.nil? && tag != "head"
229
2303 return compile_call_with_content(node, because: "its block is forwarded")
231 end
232
233 # A `break` returns from the element method, skipping what follows it.
234243 if (Refract::BlockNode === node.block) && breaks?(node.block)
2353 return compile_call_with_content(node, because: "its block has a break of its own")
236 end
237
238240 attributes = compile_attributes(node, node.block ? ">" : "></#{tag}>")
239240 return compile_call_with_content(node, because: "it has positional arguments") unless attributes
240
241237 @environment.inlined << :block_given?
242
243237 statements([
244 *attributes.hoisted,
245 append(literal("<#{tag}"), *attributes.parts, literal(">")),
246 Output::Enclosed.new(body: compile_content(node, element: true), closing: "</#{tag}>"),
247 raw("</#{tag}>"),
248237 *(flush_after_head if tag == "head"),
249 ])
250 end
251
252 # An element given the method's block, as the element method does it: the
253 # buffer and whether to render are read when it's called, the block is
254 # only yielded if there is one, and without one the element is empty.
2551 private def compile_forwarded_element(node, tag)
2561 attributes = compile_attributes(node, ">")
2571 return compile_call_with_content(node, because: "it has positional arguments") unless attributesthen never taken
258
2591 buffer = @locals.fresh(:buffer)
2601 length = @locals.fresh(:content_length)
2611 content = @locals.fresh(:content)
2622 empty = attributes.parts.map { |part| (Output::Guarded === part) ? part.with(closing: "></#{tag}>") : part }else never taken
263
2641 statements([
265 *attributes.hoisted,
266 write(buffer, call(read(state_local), :buffer)),
267 if_node(
268 call(nil, :block_given?),
269 [
270 if_node(
271 should_render,
272 [
273 opening(buffer, literal("<#{tag}"), *attributes.parts, literal(">")),
274 begin_node(
275 [
276 write(length, call(read(state_local), :output_bytesize)),
277 write(content, yield_self),
278 if_node(call(read(length), :==, call(read(state_local), :output_bytesize)), [element_value_output(read(content), read(buffer))]),
279 ],
280 ensure_clause: ensure_node([call(read(buffer), :<<, string("</#{tag}>"))])
281 ),
282 ],
283 else_body: [yield_self]
284 ),
285 ],
286 else_body: [if_node(should_render, [opening(buffer, literal("<#{tag}"), *empty, literal("></#{tag}>"))])]
287 ),
288 Refract::NilNode.new,
289 ])
290 end
291
2921 private def yield_self
2932 Refract::YieldNode.new(arguments: Refract::ArgumentsNode.new(arguments: [Refract::SelfNode.new]))
294 end
295
296 # How an element method outputs its block's value.
2971 private def element_value_output(content, buffer)
29898 formatted = @locals.fresh(:formatted)
299
30098 elsif_chain(
301 [call(constant("Phlex::SGML::SafeObject"), :===, content), call(read(state_local), :append, call(content, :to_s))],
302 [call(constant("String"), :===, content), call(buffer, :<<, escaped(content))],
303 [call(constant("Symbol"), :===, content), call(buffer, :<<, escaped(call(content, :name)))],
304 [call(Refract::NilNode.new, :===, content), Refract::NilNode.new],
305 otherwise: if_node(write(formatted, call(nil, :format_object, content)), [call(buffer, :<<, escaped(read(formatted)))])
306 )
307 end
308
309 # `svg { |s| s.path(d: "…") }` renders a Phlex::SVG around its block. When
310 # the block only calls Phlex::SVG's elements on its parameter, with
311 # static attributes and literal content, nothing it runs can tell the
312 # Phlex::SVG apart from text, so the whole element is serialised now.
3131 private def compile_inline_svg(node)
31422 return unless (svg = @environment.svg_environment)
31515 return unless node.block in Refract::BlockNode[
316 parameters: Refract::BlockParametersNode[
317 locals: [],
318 parameters: Refract::ParametersNode[requireds: [Refract::RequiredParameterNode => parameter], optionals: [], rest: nil, posts: [], keywords: [], keyword_rest: nil, block: nil],
319 ],
320 ]
321
32214 used = Set.new
32314 return unless (body = svg_body(node.block.body, parameter.name, svg, used))
32411 return unless (attributes = compile_attributes(node, ">"))then never taken
325
32611 @environment.inlined.merge(%i[block_given? render])
32711 @environment.inlined_svg.merge(used).merge(Environment::SVG_DEPENDENCIES)
328
32911 statements([
330 *attributes.hoisted,
331 append(literal("<svg"), *attributes.parts, literal(">#{body}</svg>")),
332 ])
333 end
334
3351 private def svg_body(body, parameter, svg, used)
33615 return "" if body.nil?
33714 return unless Refract::StatementsNode === bodythen never taken
338
33931 elements = body.body.map { |statement| svg_element(statement, parameter, svg, used) }
34014 elements.join unless elements.include?(nil)
341 end
342
343 # An element called on the block's parameter, serialised as Phlex::SVG
344 # serialises it, or nil if it isn't static.
3451 private def svg_element(node, parameter, svg, used)
34617 return unless node in Refract::CallNode[receiver: Refract::LocalVariableReadNode[name: ^parameter], block: nil | Refract::BlockNode[parameters: nil]]then never taken
34717 return unless (element = svg.public_element(node.name)) && !element.void
348 # A registered `head` flushes after closing.
34915 return if element.tag == "head" || Phlex::SGML::Elements::ATTRIBUTE_NORMALIZERS.key?(node.name)then never taken
350
35115 attributes = case node.arguments&.arguments
3522 in nil then {}
35313 in [Refract::KeywordHashNode => keyword_hash] then static_attributes(keyword_hash) or return
3540 else returnelse never taken
355 end
356
35714 content = case node.blockelse never taken
35811 in nil | Refract::BlockNode[body: nil] then ""
3592 in Refract::BlockNode[body: Refract::StatementsNode[body: [Refract::StringNode | Refract::SymbolNode => text]]] then Phlex::Escape.html_escape(text.unescaped)
3601 in Refract::BlockNode[body:] then svg_body(body, parameter, svg, used) or return
361 end
362
36314 used << node.name
36414 "<#{element.tag}#{Phlex::SGML::Attributes.generate_attributes(attributes)}>#{content}</#{element.tag}>"
365 rescue Phlex::ArgumentError, ::ArgumentError, EncodingError
366 # The runtime raises these when rendering, if it reaches the element.
3670 nil
368 end
369
3701 private def compile_void_element(node, tag)
37116 return compile_call_with_content(node, because: "it's a void element given a block") if node.block
372
37314 attributes = compile_attributes(node, ">")
37414 return compile_call_with_content(node, because: "it has positional arguments") unless attributesthen never taken
375
37614 statements([
377 *attributes.hoisted,
378 append(literal("<#{tag}"), *attributes.parts, literal(">")),
379 ])
380 end
381
3821 private def flush_after_head
3831 [if_node(should_render, [call(nil, :flush)], inline: true)]
384 end
385
386 # Keeps the runtime call, but still compiles inside its block. Only for
387 # methods that yield without changing self.
3881 private def compile_call_with_content(node, because: nil)
38928 keep_call(node, because) if because
390
39128 node.copy(
392 arguments: visit(node.arguments),
393 block: compile_block_unguarded(node.block)
394 )
395 end
396
3971 private def compile_block_unguarded(block)
39842 case block
39942 in Refract::BlockNode if block.body
40036 block.copy(
40136 parameters: without_compiling_calls(because: "it's in a parameter default") { visit(block.parameters) },
402 body: visit(block.body)
403 )
404 else
4056 visit(block)
406 end
407 end
408
4091 private def compile_content(node, element: false)
410239 case node.blockelse never taken
411 in nil
41226 []
413 in Refract::BlockNode[parameters: nil, body: nil]
4140 []in never taken
415 in Refract::BlockNode => block if inlinable?(block)
416199 case block.body
417 in Refract::StatementsNode[body:] if returns_nil?(body.last)
41815 [visit(block.body)]
419172 in Refract::StatementsNode[body: [statement]] if (content = compile_literal_content(statement))
42099 [content]
421 in Refract::StatementsNode[body: [Refract::LocalVariableReadNode | Refract::InstanceVariableReadNode => variable]] if element
42218 [content_output(variable, element:)]
423 in Refract::StatementsNode[body: [statement]] if pure?(statement) && element
42410 content = @locals.fresh(:content)
42510 [write(content, statement), content_output(read(content), element:)]
426 in Refract::StatementsNode[body: [statement]] if pure?(statement)
4271 [implicit_output(statement)]
428 else
42956 measured_content(Refract::ParenthesesNode.new(body: visit(block.body)), element:)
430 end
431 in Refract::BlockNode => block
43214 @diagnostics.report(node, "#{node.name}'s block is yielded at runtime because #{UNINLINABLE_BLOCK}")
43314 block = compile_block_unguarded(block)
434
43514 if element
43614 measured_content(call(constant("Phlex::Compiler"), :yield_component, Refract::SelfNode.new, block:), element:)
437 else
4380 [yield_content(block)]else never taken
439 end
440 end
441 end
442
443 # The runtime outputs a block's value only if the block wrote nothing.
4441 private def measured_content(value, element:)
44570 length = @locals.fresh(:content_length)
44670 content = @locals.fresh(:content)
447
448 [
44970 write(length, call(read(state_local), :output_bytesize)),
450 write(content, value),
451 if_node(call(read(length), :==, call(read(state_local), :output_bytesize)), [content_output(read(content), element:)]),
452 ]
453 end
454
455 # An element method outputs its block's value itself, while other
456 # helpers call __implicit_output__.
4571 private def content_output(content, element:)
45898 if element
45997 @appends += 1
46097 if_node(should_render, [element_value_output(content, buffer)])
461 else
4621 implicit_output(content)
463 end
464 end
465
4661 private def implicit_output(node)
4672 call(nil, :__implicit_output__, node)
468 end
469
4700 private def yield_content(block)
4710 call(nil, :__yield_content__, block:)
472 end
473
4741 private def inlinable?(block)
475216 block.parameters.nil? && InlineScanner.inlinable?(block.body)
476 end
477
478 # Whether a statement's value is known to be nil, so the runtime's implicit
479 # output of a block's return value can be skipped. The elements and
480 # helpers that answer is built on are recorded as relied on, but only
481 # when the answer is yes, since otherwise nothing is built on them.
4821 private def returns_nil?(node)
483198 relied = []
484198 known = nil_valued?(node, relied)
485198 @environment.inlined.merge(relied) if known
486198 known
487 end
488
4891 private def nil_valued?(node, relied)
490200 case node
491 in nil | Refract::NilNode
4921 true
493199 in Refract::CallNode if node.receiver.nil?
494 # A `break` in its block returns from the call with its value.
49538 known = !((Refract::BlockNode === node.block) && breaks?(node.block)) && (
49637 @environment.element(node.name) ||
49724 (@environment.helper?(node.name) && node.name in :plain | :whitespace | :doctype | :comment | :fragment | :raw) ||
498 render_returns_nil?(node)
499 )
50038 relied << node.name if known
50138 known
502 in Refract::IfNode
5032 nil_valued?(node.statements&.body&.last, relied) && nil_valued?(node.subsequent, relied)receiver never nilreceiver never nil
504 in Refract::UnlessNode
5050 nil_valued?(node.statements&.body&.last, relied) && nil_valued?(node.else_clause, relied)in never taken
506 in Refract::ElseNode
5070 nil_valued?(node.statements&.body&.last, relied)in never taken
508 in Refract::CaseNode | Refract::CaseMatchNode
5090 node.conditions.all? { |condition| nil_valued?(condition.statements&.body&.last, relied) } && nil_valued?(node.else_clause, relied)in never taken
510 else
511159 false
512 end
513 end
514
515 # `render` returns nil, unless a `break` in its block, or in a default for
516 # one of the block's parameters, returns from it.
5171 private def render_returns_nil?(node)
51823 node.name == :render && @environment.helper?(:render) && case node.block
5190 in nil then true
5200 in Refract::BlockNode => block then !breaks?(block)
5210 else false
522 end
523 end
524
525 # Whether a `break` in the block, or in a default for one of its
526 # parameters, would return from the call it's passed to.
5271 private def breaks?(block)
528466 [block.parameters, block.body].compact.any? { |part| BreakScanner.breaks?(part) }
529 end
530
531 # An interpolation that writes to the buffer changes what the runtime does
532 # with the string, so only pure interpolations are compiled. They're
533 # escaped as one expression, so the whole string is built before any of
534 # it is appended, as at runtime. A conditional over literals is escaped
535 # branch by branch.
5361 private def compile_literal_content(node)
537172 case node
53898 in Refract::StringNode | Refract::SymbolNode then plain(node.unescaped)
5390 in Refract::InterpolatedStringNode if pure?(node) then append(expression(escaped(node)))in never taken
5400 in Refract::NilNode then statements([])in never taken
541 in Refract::IfNode | Refract::UnlessNode
5426 folded = fold_conditional(node) { |leaf| literal_content(leaf) }
5432 append(Output::Conditional.new(folded)) if folded && pure?(folded.predicate)
54472 else nil
545 end
546 end
547
5481 private def literal_content(node)
5494 case node
5503 in Refract::StringNode | Refract::SymbolNode then string(Phlex::Escape.html_escape(node.unescaped))
5510 in Refract::NilNode then string("")in never taken
5521 else nil
553 end
554 end
555
5561 private def compile_attributes(node, closing)
557266 arguments = node.arguments&.arguments
558266 return NO_ATTRIBUTES if arguments.nil? || arguments.empty?
55962 return nil unless arguments in [Refract::KeywordHashNode => keyword_hash]
560
56159 if (static = static_attributes(keyword_hash))
562 begin
56315 normalize_attributes(node.name, static)
56415 return Attributes.new(hoisted: [], parts: [literal(Phlex::SGML::Attributes.generate_attributes(static))])
565 rescue => e
566 # Left to the runtime to raise, in case this code is never reached.
5671 @diagnostics.report(node, "#{node.name}'s attributes are serialised at runtime because serialising them now raised #{e.class}: #{e.message}")
5681 return compile_attribute_hash(node.name, keyword_hash, closing)
569 end
570 end
571
57244 compile_attribute_pieces(node, keyword_hash, closing) || compile_attribute_hash(node.name, keyword_hash, closing)
573 end
574
575 # Serialises each attribute on its own when every key is a literal. Static
576 # values are serialised now, and each dynamic value goes to the helper for
577 # its key with the name checks already done. The runtime evaluates every
578 # value before serialising any, so every value up to the last impure one
579 # is hoisted, and so is every dynamic value when there's more than one,
580 # since serialising one could change what another reads.
5811 private def compile_attribute_pieces(node, keyword_hash, closing)
58244 normalized_keys = Phlex::SGML::Elements::NORMALIZED_ATTRIBUTES[node.name]
58344 elements = keyword_hash.elements
584101 last_impure = elements.rindex { |assoc| !(Refract::AssocNode === assoc) || !pure?(attribute_value(assoc)) }
585110 several_dynamic = elements.count { |assoc| !(Refract::AssocNode === assoc) || !static_attribute_value(attribute_value(assoc)) } > 1
58644 keys = Set.new
58744 hoisted = []
588
58944 pieces = catch(:together) do
59044 elements.each_with_index.map do |assoc, index|
59165 throw :together, "a key is splatted or isn't a literal" unless assoc in Refract::AssocNode[key: Refract::StringNode | Refract::SymbolNode => key]
592
59359 key_value = static_value(key)
59459 throw :together, "#{key_value} is rewritten by the element's attribute normaliser" if normalized_keys&.include?(key_value)
59558 throw :together, "#{key_value} is repeated" unless keys.add?(key_value)then never taken
596
59758 attribute_piece(key, key_value, attribute_value(assoc), hoisted, hoist: several_dynamic || (last_impure && index <= last_impure))
598 rescue Phlex::ArgumentError => e
5990 throw :together, "#{key_value} raised #{e.class}: #{e.message}"
600 end
601 end
602
60344 case pieceselse never taken
604 in String => reason
6057 @diagnostics.report(node, "#{node.name}'s attributes are serialised together because #{reason}")
6067 nil
607 in Array
60837 Attributes.new(hoisted:, parts: attribute_parts(pieces.flatten(1), closing))
609 end
610 end
611
612 # Shorthand `title:` wraps its value in an ImplicitNode, which the
613 # formatter prints as nothing when it's taken out of the hash.
6141 private def attribute_value(assoc)
615174 (Refract::ImplicitNode === assoc.value) ? assoc.value.value : assoc.valuethen never taken
616 end
617
618 # One attribute's parts of the opening tag.
6191 private def attribute_piece(key, key_value, value, hoisted, hoist:)
62058 if (static = static_attribute_value(value))
6219 return [literal(serialized_attribute(key_value, static[0]))]
622 end
623
62449 name = Phlex::SGML::Attributes.attribute_name(key_value)
62549 Phlex::SGML::Attributes.validate_attribute_name(key_value, name)
626
62757 if (folded = fold_conditional(value) { |leaf| (static = static_attribute_value(leaf)) && string(serialized_attribute(key_value, static[0])) })
6284 return [hoist ? expression(hoisted_local(folded, hoisted)) : Output::Conditional.new(folded)]else never taken
629 end
630
63145 if (tokens = token_list(key_value, value, hoisted))
6321 return [Output::Conditional.new(tokens)]
633 end
634
63544 reference = Phlex::SGML::Attributes.reference_attribute?(name)
636
63744 if !reference && (nested = nested_attributes(key_value, name, value, hoisted))
6383 return nested
639 end
640
641 # An interpolation is always a String, so it only needs its quotes
642 # escaped. That can raise, as for a string that isn't ASCII-compatible,
643 # or on TruffleRuby one that isn't valid, so it's done inside the guard.
64441 quotable = Refract::InterpolatedStringNode === value
64541 safe_prefix = reference && quotable && safe_reference_prefix?(value)
64641 value = hoisted_local(value, hoisted) if hoist || (quotable && !reference) || safe_prefix
647
64841 if quotable && !reference
6494 return [literal(" #{name}=\""), Serialized.new(quoted(value)), literal('"')]
650 end
651
65237 if safe_prefix
6532 serialized = call(constant("Phlex::SGML::Attributes"), :reference_attribute, key, string(name), value)
6542 return [Typed.new(name:, cases: Cases.new(cases: [[decodable(value), Value.new(quoted(value))]], otherwise: Text.new(serialized)))]
655 end
656
65735 if reference
6585 return [Serialized.new(call(constant("Phlex::SGML::Attributes"), :reference_attribute, key, string(name), value))]
659 end
660
66130 value = hoisted_local(value, hoisted) unless hoist
66260 [typed_attribute(value, name) { call(constant("Phlex::SGML::Attributes"), :attribute, key, string(name), value) }]
663 end
664
665 # Whether an interpolated reference starts with text that rules out a
666 # `javascript:` URL, whatever follows it. The runtime decodes character
667 # references and keeps only letters and colons before checking, so the
668 # text mustn't contain anything decoding could change, and what's left of
669 # it must differ from `javascript:` before either ends.
6701 private def safe_reference_prefix?(node)
6713 prefix = node.parts.first
6723 return false unless Refract::StringNode === prefix
673
6742 text = prefix.unescaped
6752 return false unless text.ascii_only? && !text.include?("&") && !text.include?('"')then never taken
676
6772 normalized = text.downcase.delete("^a-z:")
6782 !normalized.empty? && !normalized.start_with?("javascript:") && !"javascript:".start_with?(normalized)
679 end
680
681 # Whether decoding the string's character references can't raise.
6821 private def decodable(node)
6832 Refract::OrNode.new(
684 left: call(node, :ascii_only?),
685 operator: "||",
686 right: Refract::AndNode.new(left: call(constant("Encoding::UTF_8"), :equal?, call(node, :encoding)), operator: "&&", right: call(node, :valid_encoding?))
687 )
688 end
689
690 # A String only needs its quotes escaped, a Symbol its name too with
691 # underscores as dashes, and a number is written as it is. Anything else
692 # is serialised as the serialiser does, without calling it for true, nil
693 # or false, which come first as they do there. The value is read more
694 # than once, so it must be a local of the compiler's, which a String's
695 # methods can't reassign.
6961 private def typed_attribute(value, name)
69734 number = Refract::OrNode.new(left: call(constant("Integer"), :===, value), operator: "||", right: call(constant("Float"), :===, value))
698
69934 truthy = Cases.new(
700 cases: [
701 [call(constant("Symbol"), :===, value), Value.new(call(constant("Phlex::Compiler"), :symbol_value, value))],
702 [number, Value.new(call(value, :to_s))],
703 ],
704 otherwise: Text.new(yield)
705 )
706
70734 cases = Cases.new(
708 cases: [
709 [call(constant("String"), :===, value), Value.new(quoted(value))],
710 [call(Refract::TrueNode.new, :===, value), Text.new(string(" #{name}"))],
711 [value, truthy],
712 ],
713 otherwise: Text.new(string(""))
714 )
715
71634 Typed.new(name:, cases:)
717 end
718
719 # Writes the value's text in the guard, to be appended as it is, which is
720 # only safe for the last value serialised: a later serialiser could change
721 # a String in place.
7221 private def choice(typed)
72329 escaped = @locals.fresh(:escaped)
72429 text = @locals.fresh(:text)
725
72629 statement = lower_cases(typed.cases) do |outcome|
727170 case outcomeelse never taken
72885 in Value[node] then [write(escaped, node)]
72985 in Text[node] then [write(escaped, Refract::NilNode.new), write(text, node)]
730 end
731 end
732
73329 [statement, Output::Choice.new(escaped:, text:, prefix: " #{typed.name}=\"", suffix: '"')]
734 end
735
736 # Builds the attribute's text in the guard, as the serialiser builds it.
7371 private def built(typed)
7387 lower_cases(typed.cases) do |outcome|
73938 case outcomeelse never taken
74019 in Value[node] then call(call(call(string(" #{typed.name}=\""), :+@), :<<, node), :<<, string('"'))
74119 in Text[node] then node
742 end
743 end
744 end
745
7461 private def lower_cases(outcome, &)
747278 case outcome
748 in Cases[cases:, otherwise:]
749242 elsif_chain(*cases.map { |condition, nested| [condition, lower_cases(nested, &)] }, otherwise: lower_cases(otherwise, &))
750 else
751208 yield outcome
752 end
753 end
754
755 # A hash of nested attributes with literal keys, such as `data:`, is
756 # serialised entry by entry. Static entries are serialised now, and each
757 # dynamic value is evaluated into a local where the hash is, then
758 # serialised in order. A `style:` hash is serialised as styles, so it's
759 # left to the serialiser.
7601 private def nested_attributes(key_value, name, value, hoisted)
76137 return unless Refract::HashNode === value && key_value != :style
762
7633 base = "#{name}-"
7648 return unless value.elements.all? { |assoc| assoc in Refract::AssocNode[key: Refract::StringNode | Refract::SymbolNode] }then never taken
765
7668 entries = value.elements.map { |assoc| [static_value(assoc.key), assoc.key, attribute_value(assoc)] }
7673 return unless entries.map(&:first).uniq.length == entries.lengththen never taken
768
769 begin
7703 entries = entries.map do |(nested_key_value, nested_key, nested_value)|
7715 nested_name = Phlex::Compiler.nested_attributes(nested_key_value, true, base).delete_prefix(" ")
772
7735 if (static = static_attribute_value(nested_value))
7741 [:static, Phlex::Compiler.nested_attributes(nested_key_value, static[0], base)]
775 else
7764 [:dynamic, nested_key, nested_name, nested_value]
777 end
778 end
779 rescue
780 # Left to the serialiser, which skips a key whose value is nil or false.
7810 return
782 end
783
7843 entries.map do |entry|
7855 case entryelse never taken
786 in [:static, text]
7871 literal(text)
788 in [:dynamic, nested_key, nested_name, nested_value]
7894 nested_value = hoisted_local(nested_value, hoisted)
7908 typed_attribute(nested_value, nested_name) { call(constant("Phlex::Compiler"), :nested_attributes, nested_key, nested_value, string(base)) }
791 end
792 end
793 end
794
795 # Each body is a node, or an array of statements.
7961 private def elsif_chain(*branches, otherwise:)
797168 branches.reverse.reduce(Refract::ElseNode.new(statements: statements(Array(otherwise)))) do |subsequent, (predicate, body)|
798564 Refract::IfNode.new(inline: false, predicate:, statements: statements(Array(body)), subsequent:)
799 end
800 end
801
802 # A list of literal tokens, some chosen by conditions, is serialised now
803 # for every combination of the conditions. Each condition is tested once,
804 # in order, where the runtime evaluates it, and stays in condition
805 # position, where some expressions mean something else. Only ASCII text is
806 # chosen this way, since appending it can't fail whatever the buffer holds.
8071 private def token_list(key_value, value, hoisted)
80845 return unless Refract::ArrayNode === value
809
81012 tokens = catch(:dynamic) { value.elements.map { |element| token_choice(element) } }
8113 choices = tokens&.grep(TokenChoice)
8123 return unless choices&.length&.between?(1, TOKEN_CONDITIONS_LIMIT)
813
8141 texts = token_texts(key_value, tokens, choices.length)
8151 return unless textsthen never taken
816
8171 conditions = choices.map do |choice|
8182 hoisted_local(if_node(choice.condition, [Refract::TrueNode.new], else_body: [Refract::FalseNode.new]), hoisted)
819 end
820
8211 token_tree(conditions, texts)
822 end
823
824 # The serialised text for each combination of the conditions.
8251 private def token_texts(key_value, tokens, conditions)
8261 texts = [true, false].repeated_permutation(conditions).to_h do |picks|
8274 pick = picks.each
82816 chosen = tokens.map { |token| (TokenChoice === token) ? (pick.next ? token.truthy : token.falsy) : token }
8294 [picks, serialized_attribute(key_value, chosen)]
830 end
831
8321 texts if texts.each_value.all?(&:ascii_only?)else never taken
833 rescue
8340 nil
835 end
836
8371 private def token_tree(conditions, texts, picks = [])
8387 return string(texts.fetch(picks)) if picks.length == conditions.length
839
8403 if_node(conditions[picks.length], [token_tree(conditions, texts, [*picks, true])], else_body: [token_tree(conditions, texts, [*picks, false])])
841 end
842
843 # A literal token, or a condition choosing between two.
8441 private def token_choice(node)
8458 case node
8462 in Refract::ParenthesesNode[body: Refract::StatementsNode[body: [inner]]] then token_choice(inner)
847 in Refract::IfNode[subsequent: nil | Refract::ElseNode]
8482 TokenChoice.new(condition: node.predicate, truthy: branch_token(node.statements), falsy: branch_token(node.subsequent&.statements))
849 in Refract::UnlessNode
8500 TokenChoice.new(condition: node.predicate, truthy: branch_token(node.else_clause&.statements), falsy: branch_token(node.statements))in never taken
851 else
8524 token_literal(node)
853 end
854 end
855
8561 private def branch_token(branch)
8574 case branch
8581 in nil then nil
8593 in Refract::StatementsNode[body: [statement]] then token_literal(statement)
8600 else throw :dynamicelse never taken
861 end
862 end
863
8641 private def token_literal(node)
8657 case node
8665 in Refract::StringNode | Refract::SymbolNode | Refract::IntegerNode | Refract::FloatNode | Refract::NilNode | Refract::FalseNode then static_value(node)
8670 in Refract::ArrayNode then node.elements.map { |element| token_literal(element) }in never taken
8682 else throw :dynamic
869 end
870 end
871
872 # The runtime only copies the string if it has quotes to escape.
8731 private def quoted(node)
87440 parenthesized([
875 if_node(call(node, :include?, string('"')), [call(constant("Phlex::Compiler"), :escape_quotes, node)], else_body: [node]),
876 ])
877 end
878
8791 private def hoisted_local(node, hoisted)
88057 local = @locals.fresh(:value)
88157 hoisted << write(local, visit(node))
88257 read(local)
883 end
884
8851 private def serialized_attribute(key, value)
88621 Phlex::SGML::Attributes.generate_attributes({ key => value })
887 end
888
889 # The runtime builds the whole attribute string before appending any of
890 # it, so if a value is invalid the tag closes empty. Serialisations are
891 # all evaluated into locals in the first part, and appended after.
8921 private def attribute_parts(parts, closing)
89337 writes = []
894
89583 last = parts.rindex { |part| part in Serialized | Typed }
896
89737 parts = parts.each_with_index.map do |part, index|
89866 part = Serialized.new(built(part)) if Typed === part && index != last
899
90066 case part
901 in Serialized[node]
90216 local = @locals.fresh(:attribute)
90316 writes << write(local, node)
90416 expression(read(local))
905 in Typed
90629 statement, choice = choice(part)
90729 writes << statement
90829 choice
909 else
91021 part
911 end
912 end
913
91437 return parts if writes.empty?
915
916 # A choice is appended as statements, so the guard can't return it.
91736 parts.unshift(literal("")) if Output::Choice === parts.first
91836 parts[0] = Output::Guarded.new(statements: writes, result: parts[0], closing:)
91936 parts
920 end
921
9221 private def compile_attribute_hash(element, keyword_hash, closing)
9238 hash = case keyword_hash.elements
9246 in [*, Refract::AssocSplatNode, *] then call(constant("Phlex::Compiler"), :keywords, keyword_hash)
9252 else Refract::HashNode.new(elements: keyword_hash.elements)
926 end
9278 hoisted = []
9288 hash = hoisted_local(hash, hoisted)
9298 attributes = @locals.fresh(:attributes)
930
931 # Element methods only serialise a hash that has something in it.
9328 serialized = if_node(
933 call(call(hash, :length), :>, Refract::IntegerNode.new(value: 0)),
934 [*normalize_call(element, hash), cached_attributes(hash)],
935 else_body: [string("")]
936 )
937
9388 Attributes.new(
939 hoisted:,
940 parts: [
941 Output::Guarded.new(
942 statements: [write(attributes, serialized)],
943 result: expression(read(attributes)),
944 closing:
945 ),
946 ]
947 )
948 end
949
950 # As the element method serialises them, through the attribute cache.
9511 private def cached_attributes(hash)
9528 call(
953 call(read(state_local), :attribute_cache),
954 :fetch,
955 hash,
956 block: Refract::BlockNode.new(parameters: nil, body: statements([call(constant("Phlex::SGML::Attributes"), :generate_attributes, hash)]))
957 )
958 end
959
960 # Normalizers rewrite the hash in place.
9611 private def normalize_call(element, hash)
9628 if (normalizer = attribute_normalizer(element))
9631 [call(constant("Phlex::SGML::Elements"), normalizer, hash)]
964 else
9657 []
966 end
967 end
968
9691 private def normalize_attributes(element, attributes)
97015 if (normalizer = attribute_normalizer(element))
9710 Phlex::SGML::Elements.public_send(normalizer, attributes)then never taken
972 end
973 end
974
9751 private def attribute_normalizer(element)
97623 Phlex::SGML::Elements::ATTRIBUTE_NORMALIZERS[element]
977 end
978
9791 private def static_attributes(keyword_hash)
980144 catch(:dynamic) { static_hash(keyword_hash.elements) }
981 end
982
983 # The value wrapped in an array, since a static value can be nil.
9841 private def static_attribute_value(node)
985262 catch(:dynamic) { [static_value(node)] }
986 end
987
9881 private def static_hash(elements)
98980 elements.to_h do |element|
990102 throw :dynamic unless Refract::AssocNode === element
99196 throw :dynamic unless element.key in Refract::StringNode | Refract::SymbolNodethen never taken
99296 [static_value(element.key), static_value(element.value)]
993 end
994 end
995
9961 private def static_value(node)
997423 case node
99868 in Refract::StringNode then node.unescaped
999162 in Refract::SymbolNode then node.unescaped.to_sym
100021 in Refract::IntegerNode | Refract::FloatNode then node.value
10011 in Refract::TrueNode then true
10021 in Refract::FalseNode then false
10036 in Refract::NilNode then nil
100432 in Refract::ArrayNode then node.elements.map { |element| static_value(element) }
10058 in Refract::HashNode then static_hash(node.elements)
100613 in Refract::CallNode if set_literal?(node) then Set.new(node.arguments.arguments.map { |element| static_value(element) })
1007142 else throw :dynamic
1008 end
1009 end
1010
10111 private def set_literal?(node)
101240 node.name == :[] && node.block.nil? && node.arguments && (
10139 (Refract::ConstantReadNode === node.receiver && node.receiver.name == :Set && @environment.standard_set?) ||
10147 (Refract::ConstantPathNode === node.receiver && node.receiver.parent.nil? && node.receiver.name == :Set)
1015 )
1016 end
1017
1018 # Rebuilds a conditional with each literal branch replaced by the block's
1019 # result, or returns nil if a branch isn't a literal the block handles or
1020 # a nested condition isn't pure. The outermost condition is left for the
1021 # caller to check, since the whole conditional can be hoisted. A branch
1022 # that's missing evaluates to nil, so it gets a nil leaf, which is why a
1023 # modifier form becomes a block form.
10241 private def fold_conditional(node, &leaf)
102553 case node
102612 in Refract::IfNode | Refract::UnlessNode then catch(:dynamic) { fold(node, &leaf) }
10272 in Refract::ParenthesesNode[body: Refract::StatementsNode[body: [inner]]] then fold_conditional(inner, &leaf)
102845 else nil
1029 end
1030 end
1031
10321 private def fold(node, &leaf)
103324 case node
1034 in Refract::IfNode
10356 node.copy(inline: false, statements: fold_branch(node.statements, &leaf), subsequent: fold_else(node.subsequent, &leaf))
1036 in Refract::UnlessNode
10370 node.copy(inline: false, statements: fold_branch(node.statements, &leaf), else_clause: fold_else(node.else_clause, &leaf))in never taken
1038 in Refract::ElseNode
10396 node.copy(statements: fold_branch(node.statements, &leaf))
1040 in Refract::ParenthesesNode[body: Refract::StatementsNode[body: [inner]]]
10410 node.copy(body: statements([fold_nested(inner, &leaf)]))in never taken
1042 else
104312 leaf.call(node) || throw(:dynamic)
1044 end
1045 end
1046
10471 private def fold_nested(node, &leaf)
104818 throw :dynamic if node in Refract::IfNode | Refract::UnlessNode and !pure?(node.predicate)then never taken
1049
105018 fold(node, &leaf)
1051 end
1052
10531 private def fold_branch(branch, &leaf)
105412 case branch
10550 in nil then statements([fold(Refract::NilNode.new, &leaf)])in never taken
105612 in Refract::StatementsNode[body: [statement]] then statements([fold_nested(statement, &leaf)])
10570 else throw :dynamicelse never taken
1058 end
1059 end
1060
10611 private def fold_else(node, &leaf)
10626 node ? fold_nested(node, &leaf) : Refract::ElseNode.new(statements: fold_branch(nil, &leaf))else never taken
1063 end
1064
1065 # Whether evaluating the node can't have side effects or raise, so it's
1066 # safe to evaluate it inside an append that may be skipped. Constants are
1067 # excluded: reading one can autoload or raise NameError. So are
1068 # interpolations and splats, which call to_s and to_hash, and hash keys
1069 # that could have a `hash` method of their own. Conditionals over pure
1070 # operands are pure, since they only choose between them.
10711 private def pure?(node)
1072223 case node
1073 in nil | Refract::StringNode | Refract::SymbolNode | Refract::IntegerNode | Refract::FloatNode |
1074 Refract::RationalNode | Refract::ImaginaryNode | Refract::RegularExpressionNode |
1075 Refract::TrueNode | Refract::FalseNode | Refract::NilNode | Refract::SelfNode |
1076 Refract::LocalVariableReadNode | Refract::InstanceVariableReadNode | Refract::EmbeddedVariableNode
107762 true
107820 in Refract::ArrayNode | Refract::HashNode | Refract::KeywordHashNode then node.elements.all? { |element| pure?(element) }
10795 in Refract::AssocNode[key: Refract::StringNode | Refract::SymbolNode | Refract::IntegerNode | Refract::FloatNode | Refract::NilNode | Refract::TrueNode | Refract::FalseNode] then pure?(node.value)
108025 in Refract::InterpolatedStringNode then node.parts.all? { |part| Refract::StringNode === part }
10815 in Refract::ParenthesesNode then pure?(node.body)
108236 in Refract::StatementsNode then node.body.all? { |statement| pure?(statement) }
10838 in Refract::IfNode then pure?(node.predicate) && pure?(node.statements) && pure?(node.subsequent)
10840 in Refract::UnlessNode then pure?(node.predicate) && pure?(node.statements) && pure?(node.else_clause)in never taken
10856 in Refract::ElseNode then pure?(node.statements)
10861 in Refract::AndNode | Refract::OrNode then pure?(node.left) && pure?(node.right)
1087101 else false
1088 end
1089 end
1090
1091 # An interpolation is built, calling to_s on its parts, before the runtime
1092 # checks whether it's rendering, so it's evaluated into a local first.
10931 private def compile_plain(node)
1094 # Keep runtime block rejection and evaluation of forwarded block expressions.
109533 return keep_call(node, "it has a block") if node.blockthen never taken
109633 return keep_call(node, "__text__ is overridden") unless @environment.helper?(:__text__)then never taken
1097
109833 compiled = case node.arguments&.argumentsreceiver never nil
109917 in [Refract::StringNode | Refract::SymbolNode => text] then plain(text.unescaped)
1100 in [Refract::InterpolatedStringNode => interpolated]
11014 text = @locals.fresh(:text)
11024 statements([write(text, visit(interpolated)), append(expression(escaped(read(text))))])
11030 in [Refract::NilNode] then Refract::NilNode.newin never taken
110412 else return keep_call(node, "its argument isn't a literal or an interpolation")
1105 end
1106
110721 @environment.inlined.merge(%i[__text__ block_given?])
110821 compiled
1109 end
1110
1111 # `raw safe("…")` is a literal that skips escaping.
11121 private def compile_raw(node)
1113 # Keep evaluation of forwarded block expressions, which may raise.
11146 return keep_call(node, "it has a block") if node.blockthen never taken
1115
11166 case node.arguments&.argumentsreceiver never nil
1117 in [Refract::CallNode[receiver: nil, name: :safe, block: nil, arguments: Refract::ArgumentsNode[arguments: [Refract::StringNode => text]]]] if @environment.helper?(:safe)
11181 @environment.inlined << :safe
11191 raw(text.unescaped)
1120 else
11215 keep_call(node, "its argument isn't safe with a string literal")
1122 end
1123 end
1124
11251 private def compile_whitespace(node)
11264 return keep_call(node, "it has arguments") if node.arguments
1127
11283 if node.block.nil?
11291 @environment.inlined << :block_given?
11301 return raw(" ")
1131 end
1132
11332 compile_wrapped_content(node, " ", " ")
1134 end
1135
11361 private def compile_comment(node)
11373 return keep_call(node, "it has arguments") if node.argumentsthen never taken
1138
11393 compile_wrapped_content(node, "<!-- ", " -->")
1140 end
1141
1142 # Unlike an element, the runtime has no `ensure`, so a jump out of the
1143 # block skips the closing text, and only a block that can be inlined is
1144 # compiled. A forwarded block, which may be nil, keeps the runtime call too.
1145 # The runtime yields with __yield_content__, so its content is only
1146 # inlined while that's Phlex's.
11471 private def compile_wrapped_content(node, opening, closing)
11485 unless @environment.helper?(:__yield_content__) && @environment.helper?(:__implicit_output__)
1149 # The block may be yielded with another `self`, so calls in it are compiled behind a check.
11502 return keep_call(node, "__yield_content__ or __implicit_output__ is overridden")
1151 end
1152
11533 return compile_call_with_content(node, because: "its block is forwarded or #{UNINLINABLE_BLOCK}") unless inlinable_content?(node.block)
1154
11552 @environment.inlined.merge(%i[__yield_content__ __implicit_output__ block_given?])
11562 statements([raw(opening), *compile_content(node), raw(closing)])
1157 end
1158
11591 private def inlinable_content?(block)
11603 case block
11610 in nil | Refract::BlockNode[parameters: nil, body: nil] then truein never taken
11623 in Refract::BlockNode then inlinable?(block)
11630 else falseelse never taken
1164 end
1165 end
1166
11671 private def compile_doctype(node)
11681 return keep_call(node, "it has arguments or a block") if node.arguments || node.blockelse never taken
1169
11700 raw("<!doctype html>")
1171 end
1172
1173 # A fragment always keeps its call, since it drives the render check, but
1174 # the content is still compiled.
11751 private def compile_fragment(node)
117617 return keep_call(node, "its block has parameters or is forwarded") unless node.block in Refract::BlockNode[parameters: nil]
1177
117816 compile_call_with_content(node)
1179 end
1180
11811 private def keep_call(node, because)
118235 @diagnostics.report(node, "#{node.name} keeps its call because #{because}")
118335 nil
1184 end
1185
11861 private def escaped(node)
1187298 call(constant("Phlex::Escape"), :html_escape, node)
1188 end
1189
11901 private def plain(text)
1191115 raw(Phlex::Escape.html_escape(text))
1192 end
1193
11941 private def raw(text)
1195358 append(literal(text))
1196 end
1197
11981 private def literal(text)
1199938 text => String
1200
1201938 Output::Literal.new(text)
1202 end
1203
12041 private def expression(node)
120532 Output::Expression.new(node)
1206 end
1207
12081 private def append(*parts)
1209625 @appends += 1
1210625 state_local
1211
1212625 Output::Append.new(parts:)
1213 end
1214
12151 private def opening(buffer, *parts)
12162 @appends += 1
12172 state_local
1218
12192 Output::Opening.new(parts:, buffer:)
1220 end
1221
1222 # Guarded blocks read the state themselves, so only output outside them
1223 # needs it read on entry.
12241 private def state_local
12251073 unless @state_local_set || @guarded_blocks > 0
1226148 @preamble << write(Locals::STATE, Refract::InstanceVariableReadNode.new(name: :@_state))
1227148 @state_local_set = true
1228 end
1229
12301073 Locals::STATE
1231 end
1232
12331 private def self_local
123434 unless @self_local_set
123518 @preamble << write(Locals::SELF, Refract::SelfNode.new)
123618 @self_local_set = true
1237 end
1238
123934 Locals::SELF
1240 end
1241 end
1242end