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 | ||
| 3 | 1 | module 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. | |
| 6 | 1 | class MethodCompiler < Refract::MutationVisitor |
| 7 | 1 | include Builder |
| 8 | ||
| 9 | 1 | Attributes = Data.define(:hoisted, :parts) |
| 10 | 1 | NO_ATTRIBUTES = Attributes.new(hoisted: [], parts: []) |
| 11 | ||
| 12 | # A part of the opening tag that runs a serialiser, which can raise. | |
| 13 | 1 | 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. | |
| 19 | 1 | Typed = Data.define(:name, :cases) |
| 20 | 1 | Cases = Data.define(:cases, :otherwise) |
| 21 | 1 | Value = Data.define(:node) |
| 22 | 1 | Text = Data.define(:node) |
| 23 | ||
| 24 | 1 | TokenChoice = Data.define(:condition, :truthy, :falsy) |
| 25 | 1 | TOKEN_CONDITIONS_LIMIT = 3 |
| 26 | ||
| 27 | 1 | UNINLINABLE_BLOCK = "it has parameters or contains a return, break, next or local assignment" |
| 28 | 1 | GUARDED_BLOCK_DEPTH_LIMIT = 4 |
| 29 | ||
| 30 | 1 | def initialize(environment, path, diagnostics: Diagnostics.new(path)) |
| 31 | 240 | super() |
| 32 | 240 | @environment = environment |
| 33 | 240 | @path = path |
| 34 | 240 | @diagnostics = diagnostics |
| 35 | 240 | @locals = Locals.new |
| 36 | 240 | @preamble = [] |
| 37 | 240 | @appends = 0 |
| 38 | 240 | @guarded_blocks = 0 |
| 39 | 240 | @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. | |
| 44 | 1 | def compile(node, keep_uncompiled: false) |
| 45 | 238 | tree = visit(node) |
| 46 | 238 | return tree if @appends == 0 && keep_uncompiled |
| 47 | 227 | return nil if @appends == 0 |
| 48 | ||
| 49 | 157 | Emitter.new(@locals).visit(tree) |
| 50 | end | |
| 51 | ||
| 52 | 0 | visit Refract::ClassNode do |node| |
| 53 | 0 | node |
| 54 | end | |
| 55 | ||
| 56 | 0 | visit Refract::ModuleNode do |node| |
| 57 | 0 | node |
| 58 | end | |
| 59 | ||
| 60 | 1 | visit Refract::LambdaNode do |node| |
| 61 | 22 | 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. | |
| 68 | 1 | [Refract::IfNode, Refract::UnlessNode, Refract::WhileNode, Refract::UntilNode].each do |modifier_node| |
| 69 | 4 | visit modifier_node do |node| |
| 70 | 196 | appends = @appends |
| 71 | 196 | result = super(node) |
| 72 | ||
| 73 | 196 | if node.inline && @appends > appends && !(node.statements in Refract::StatementsNode[body: [Refract::BeginNode]]) |
| 74 | 0 | result.copy(inline: false)then never taken |
| 75 | else | |
| 76 | 196 | 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. | |
| 83 | 1 | visit Refract::SourceFileNode do |node| |
| 84 | 16 | 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. | |
| 91 | 1 | visit Refract::DefNode do |node| |
| 92 | 239 | return node unless @stack.size == 1 |
| 93 | ||
| 94 | 472 | if (reserved = (LocalsScanner.names(node) | BareCallScanner.names(node)).find { |name| name.start_with?("__phlex_") }) |
| 95 | 2 | @diagnostics.refuse(node, "#{reserved} is a name the compiler reserves for locals; names starting with __phlex_ can't be used") |
| 96 | 2 | return node |
| 97 | end | |
| 98 | ||
| 99 | 472 | parameters = without_compiling_calls(because: "it's in a parameter default") { visit(node.parameters) } |
| 100 | 236 | body = visit(node.body) |
| 101 | ||
| 102 | 236 | node.copy( |
| 103 | parameters:, | |
| 104 | body: mapping_exceptions([*@preamble, body]) | |
| 105 | ) | |
| 106 | end | |
| 107 | ||
| 108 | 1 | visit Refract::CallNode do |node| |
| 109 | 1375 | if @compiling_calls |
| 110 | 1191 | if statement?(node) && node.receiver.nil? && (compiled = compile_call(node)) |
| 111 | 316 | return compiled |
| 112 | end | |
| 113 | 184 | elsif @uncompiled_because && node.receiver.nil? && (@environment.element(node.name) || @environment.helper?(node.name)) |
| 114 | 1 | keep_call(node, @uncompiled_because) |
| 115 | end | |
| 116 | ||
| 117 | 1059 | 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. | |
| 130 | 1 | visit Refract::BlockNode do |node| |
| 131 | 186 | return super(node) unless @compiling_calls |
| 132 | 112 | return without_compiling_calls { super(node) } unless node.bodythen never taken |
| 133 | ||
| 134 | 112 | if @guarded_blocks == GUARDED_BLOCK_DEPTH_LIMIT |
| 135 | 1 | @diagnostics.report(node, "calls in this block are left to the runtime because it's nested #{GUARDED_BLOCK_DEPTH_LIMIT} blocks deep") |
| 136 | 2 | return mapping_block_exceptions(without_compiling_calls { super(node) }) |
| 137 | end | |
| 138 | ||
| 139 | 111 | if (conflict = ReparseScanner.conflict(node)) |
| 140 | 1 | @diagnostics.report(node, "calls in this block are left to the runtime because #{conflict}") |
| 141 | 2 | return mapping_block_exceptions(without_compiling_calls { super(node) }) |
| 142 | end | |
| 143 | ||
| 144 | 110 | appends = @appends |
| 145 | 110 | @guarded_blocks += 1 |
| 146 | 110 | compiled = visit(node.body) |
| 147 | 110 | @guarded_blocks -= 1 |
| 148 | 186 | return mapping_block_exceptions(without_compiling_calls { super(node) }) if appends == @appends |
| 149 | ||
| 150 | 68 | original = without_compiling_calls { visit(node.body) } |
| 151 | ||
| 152 | 34 | node.copy( |
| 153 | 34 | 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 | ||
| 166 | 1 | private def mapping_block_exceptions(block) |
| 167 | 78 | block.copy(body: statements([mapping_exceptions([block.body])])) |
| 168 | end | |
| 169 | ||
| 170 | 1 | private def mapping_exceptions(body) |
| 171 | 348 | 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 | ||
| 181 | 1 | private def statement?(node) |
| 182 | 1191 | 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. | |
| 188 | 1 | private def without_compiling_calls(because: nil) |
| 189 | 429 | compiling_calls, uncompiled_because = @compiling_calls, @uncompiled_because |
| 190 | 429 | @compiling_calls = false |
| 191 | 429 | @uncompiled_because = because |
| 192 | 429 | yield |
| 193 | ensure | |
| 194 | 429 | @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. | |
| 200 | 1 | private def compile_call(node) |
| 201 | 522 | appends = @appends |
| 202 | ||
| 203 | 522 | compiled = if (element = @environment.element(node.name)) |
| 204 | 263 | element.void ? compile_void_element(node, element.tag) : compile_standard_element(node, element.tag) |
| 205 | 259 | elsif @environment.helper?(node.name) |
| 206 | 163 | case node.name |
| 207 | 33 | in :plain then compile_plain(node) |
| 208 | 6 | in :raw then compile_raw(node) |
| 209 | 4 | in :whitespace then compile_whitespace(node) |
| 210 | 1 | in :doctype then compile_doctype(node) |
| 211 | 3 | in :comment then compile_comment(node) |
| 212 | 17 | in :fragment then compile_fragment(node) |
| 213 | 22 | in :svg then compile_inline_svg(node) |
| 214 | 77 | else nil |
| 215 | end | |
| 216 | end | |
| 217 | ||
| 218 | 522 | @environment.inlined << node.name if compiled && (@appends > appends || !(Refract::CallNode === compiled)) |
| 219 | 522 | 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. | |
| 226 | 1 | private def compile_standard_element(node, tag) |
| 227 | 247 | if Refract::BlockArgumentNode === node.block |
| 228 | 4 | return compile_forwarded_element(node, tag) if node.block.expression.nil? && tag != "head" |
| 229 | ||
| 230 | 3 | 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. | |
| 234 | 243 | if (Refract::BlockNode === node.block) && breaks?(node.block) |
| 235 | 3 | return compile_call_with_content(node, because: "its block has a break of its own") |
| 236 | end | |
| 237 | ||
| 238 | 240 | attributes = compile_attributes(node, node.block ? ">" : "></#{tag}>") |
| 239 | 240 | return compile_call_with_content(node, because: "it has positional arguments") unless attributes |
| 240 | ||
| 241 | 237 | @environment.inlined << :block_given? |
| 242 | ||
| 243 | 237 | 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}>"), | |
| 248 | 237 | *(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. | |
| 255 | 1 | private def compile_forwarded_element(node, tag) |
| 256 | 1 | attributes = compile_attributes(node, ">") |
| 257 | 1 | return compile_call_with_content(node, because: "it has positional arguments") unless attributesthen never taken |
| 258 | ||
| 259 | 1 | buffer = @locals.fresh(:buffer) |
| 260 | 1 | length = @locals.fresh(:content_length) |
| 261 | 1 | content = @locals.fresh(:content) |
| 262 | 2 | empty = attributes.parts.map { |part| (Output::Guarded === part) ? part.with(closing: "></#{tag}>") : part }else never taken |
| 263 | ||
| 264 | 1 | 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 | ||
| 292 | 1 | private def yield_self |
| 293 | 2 | Refract::YieldNode.new(arguments: Refract::ArgumentsNode.new(arguments: [Refract::SelfNode.new])) |
| 294 | end | |
| 295 | ||
| 296 | # How an element method outputs its block's value. | |
| 297 | 1 | private def element_value_output(content, buffer) |
| 298 | 98 | formatted = @locals.fresh(:formatted) |
| 299 | ||
| 300 | 98 | 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. | |
| 313 | 1 | private def compile_inline_svg(node) |
| 314 | 22 | return unless (svg = @environment.svg_environment) |
| 315 | 15 | 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 | ||
| 322 | 14 | used = Set.new |
| 323 | 14 | return unless (body = svg_body(node.block.body, parameter.name, svg, used)) |
| 324 | 11 | return unless (attributes = compile_attributes(node, ">"))then never taken |
| 325 | ||
| 326 | 11 | @environment.inlined.merge(%i[block_given? render]) |
| 327 | 11 | @environment.inlined_svg.merge(used).merge(Environment::SVG_DEPENDENCIES) |
| 328 | ||
| 329 | 11 | statements([ |
| 330 | *attributes.hoisted, | |
| 331 | append(literal("<svg"), *attributes.parts, literal(">#{body}</svg>")), | |
| 332 | ]) | |
| 333 | end | |
| 334 | ||
| 335 | 1 | private def svg_body(body, parameter, svg, used) |
| 336 | 15 | return "" if body.nil? |
| 337 | 14 | return unless Refract::StatementsNode === bodythen never taken |
| 338 | ||
| 339 | 31 | elements = body.body.map { |statement| svg_element(statement, parameter, svg, used) } |
| 340 | 14 | 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. | |
| 345 | 1 | private def svg_element(node, parameter, svg, used) |
| 346 | 17 | return unless node in Refract::CallNode[receiver: Refract::LocalVariableReadNode[name: ^parameter], block: nil | Refract::BlockNode[parameters: nil]]then never taken |
| 347 | 17 | return unless (element = svg.public_element(node.name)) && !element.void |
| 348 | # A registered `head` flushes after closing. | |
| 349 | 15 | return if element.tag == "head" || Phlex::SGML::Elements::ATTRIBUTE_NORMALIZERS.key?(node.name)then never taken |
| 350 | ||
| 351 | 15 | attributes = case node.arguments&.arguments |
| 352 | 2 | in nil then {} |
| 353 | 13 | in [Refract::KeywordHashNode => keyword_hash] then static_attributes(keyword_hash) or return |
| 354 | 0 | else returnelse never taken |
| 355 | end | |
| 356 | ||
| 357 | 14 | content = case node.blockelse never taken |
| 358 | 11 | in nil | Refract::BlockNode[body: nil] then "" |
| 359 | 2 | in Refract::BlockNode[body: Refract::StatementsNode[body: [Refract::StringNode | Refract::SymbolNode => text]]] then Phlex::Escape.html_escape(text.unescaped) |
| 360 | 1 | in Refract::BlockNode[body:] then svg_body(body, parameter, svg, used) or return |
| 361 | end | |
| 362 | ||
| 363 | 14 | used << node.name |
| 364 | 14 | "<#{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. | |
| 367 | 0 | nil |
| 368 | end | |
| 369 | ||
| 370 | 1 | private def compile_void_element(node, tag) |
| 371 | 16 | return compile_call_with_content(node, because: "it's a void element given a block") if node.block |
| 372 | ||
| 373 | 14 | attributes = compile_attributes(node, ">") |
| 374 | 14 | return compile_call_with_content(node, because: "it has positional arguments") unless attributesthen never taken |
| 375 | ||
| 376 | 14 | statements([ |
| 377 | *attributes.hoisted, | |
| 378 | append(literal("<#{tag}"), *attributes.parts, literal(">")), | |
| 379 | ]) | |
| 380 | end | |
| 381 | ||
| 382 | 1 | private def flush_after_head |
| 383 | 1 | [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. | |
| 388 | 1 | private def compile_call_with_content(node, because: nil) |
| 389 | 28 | keep_call(node, because) if because |
| 390 | ||
| 391 | 28 | node.copy( |
| 392 | arguments: visit(node.arguments), | |
| 393 | block: compile_block_unguarded(node.block) | |
| 394 | ) | |
| 395 | end | |
| 396 | ||
| 397 | 1 | private def compile_block_unguarded(block) |
| 398 | 42 | case block |
| 399 | 42 | in Refract::BlockNode if block.body |
| 400 | 36 | block.copy( |
| 401 | 36 | parameters: without_compiling_calls(because: "it's in a parameter default") { visit(block.parameters) }, |
| 402 | body: visit(block.body) | |
| 403 | ) | |
| 404 | else | |
| 405 | 6 | visit(block) |
| 406 | end | |
| 407 | end | |
| 408 | ||
| 409 | 1 | private def compile_content(node, element: false) |
| 410 | 239 | case node.blockelse never taken |
| 411 | in nil | |
| 412 | 26 | [] |
| 413 | in Refract::BlockNode[parameters: nil, body: nil] | |
| 414 | 0 | []in never taken |
| 415 | in Refract::BlockNode => block if inlinable?(block) | |
| 416 | 199 | case block.body |
| 417 | in Refract::StatementsNode[body:] if returns_nil?(body.last) | |
| 418 | 15 | [visit(block.body)] |
| 419 | 172 | in Refract::StatementsNode[body: [statement]] if (content = compile_literal_content(statement)) |
| 420 | 99 | [content] |
| 421 | in Refract::StatementsNode[body: [Refract::LocalVariableReadNode | Refract::InstanceVariableReadNode => variable]] if element | |
| 422 | 18 | [content_output(variable, element:)] |
| 423 | in Refract::StatementsNode[body: [statement]] if pure?(statement) && element | |
| 424 | 10 | content = @locals.fresh(:content) |
| 425 | 10 | [write(content, statement), content_output(read(content), element:)] |
| 426 | in Refract::StatementsNode[body: [statement]] if pure?(statement) | |
| 427 | 1 | [implicit_output(statement)] |
| 428 | else | |
| 429 | 56 | measured_content(Refract::ParenthesesNode.new(body: visit(block.body)), element:) |
| 430 | end | |
| 431 | in Refract::BlockNode => block | |
| 432 | 14 | @diagnostics.report(node, "#{node.name}'s block is yielded at runtime because #{UNINLINABLE_BLOCK}") |
| 433 | 14 | block = compile_block_unguarded(block) |
| 434 | ||
| 435 | 14 | if element |
| 436 | 14 | measured_content(call(constant("Phlex::Compiler"), :yield_component, Refract::SelfNode.new, block:), element:) |
| 437 | else | |
| 438 | 0 | [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. | |
| 444 | 1 | private def measured_content(value, element:) |
| 445 | 70 | length = @locals.fresh(:content_length) |
| 446 | 70 | content = @locals.fresh(:content) |
| 447 | ||
| 448 | [ | |
| 449 | 70 | 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__. | |
| 457 | 1 | private def content_output(content, element:) |
| 458 | 98 | if element |
| 459 | 97 | @appends += 1 |
| 460 | 97 | if_node(should_render, [element_value_output(content, buffer)]) |
| 461 | else | |
| 462 | 1 | implicit_output(content) |
| 463 | end | |
| 464 | end | |
| 465 | ||
| 466 | 1 | private def implicit_output(node) |
| 467 | 2 | call(nil, :__implicit_output__, node) |
| 468 | end | |
| 469 | ||
| 470 | 0 | private def yield_content(block) |
| 471 | 0 | call(nil, :__yield_content__, block:) |
| 472 | end | |
| 473 | ||
| 474 | 1 | private def inlinable?(block) |
| 475 | 216 | 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. | |
| 482 | 1 | private def returns_nil?(node) |
| 483 | 198 | relied = [] |
| 484 | 198 | known = nil_valued?(node, relied) |
| 485 | 198 | @environment.inlined.merge(relied) if known |
| 486 | 198 | known |
| 487 | end | |
| 488 | ||
| 489 | 1 | private def nil_valued?(node, relied) |
| 490 | 200 | case node |
| 491 | in nil | Refract::NilNode | |
| 492 | 1 | true |
| 493 | 199 | in Refract::CallNode if node.receiver.nil? |
| 494 | # A `break` in its block returns from the call with its value. | |
| 495 | 38 | known = !((Refract::BlockNode === node.block) && breaks?(node.block)) && ( |
| 496 | 37 | @environment.element(node.name) || |
| 497 | 24 | (@environment.helper?(node.name) && node.name in :plain | :whitespace | :doctype | :comment | :fragment | :raw) || |
| 498 | render_returns_nil?(node) | |
| 499 | ) | |
| 500 | 38 | relied << node.name if known |
| 501 | 38 | known |
| 502 | in Refract::IfNode | |
| 503 | 2 | nil_valued?(node.statements&.body&.last, relied) && nil_valued?(node.subsequent, relied)receiver never nilreceiver never nil |
| 504 | in Refract::UnlessNode | |
| 505 | 0 | nil_valued?(node.statements&.body&.last, relied) && nil_valued?(node.else_clause, relied)in never taken |
| 506 | in Refract::ElseNode | |
| 507 | 0 | nil_valued?(node.statements&.body&.last, relied)in never taken |
| 508 | in Refract::CaseNode | Refract::CaseMatchNode | |
| 509 | 0 | node.conditions.all? { |condition| nil_valued?(condition.statements&.body&.last, relied) } && nil_valued?(node.else_clause, relied)in never taken |
| 510 | else | |
| 511 | 159 | 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. | |
| 517 | 1 | private def render_returns_nil?(node) |
| 518 | 23 | node.name == :render && @environment.helper?(:render) && case node.block |
| 519 | 0 | in nil then true |
| 520 | 0 | in Refract::BlockNode => block then !breaks?(block) |
| 521 | 0 | 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. | |
| 527 | 1 | private def breaks?(block) |
| 528 | 466 | [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. | |
| 536 | 1 | private def compile_literal_content(node) |
| 537 | 172 | case node |
| 538 | 98 | in Refract::StringNode | Refract::SymbolNode then plain(node.unescaped) |
| 539 | 0 | in Refract::InterpolatedStringNode if pure?(node) then append(expression(escaped(node)))in never taken |
| 540 | 0 | in Refract::NilNode then statements([])in never taken |
| 541 | in Refract::IfNode | Refract::UnlessNode | |
| 542 | 6 | folded = fold_conditional(node) { |leaf| literal_content(leaf) } |
| 543 | 2 | append(Output::Conditional.new(folded)) if folded && pure?(folded.predicate) |
| 544 | 72 | else nil |
| 545 | end | |
| 546 | end | |
| 547 | ||
| 548 | 1 | private def literal_content(node) |
| 549 | 4 | case node |
| 550 | 3 | in Refract::StringNode | Refract::SymbolNode then string(Phlex::Escape.html_escape(node.unescaped)) |
| 551 | 0 | in Refract::NilNode then string("")in never taken |
| 552 | 1 | else nil |
| 553 | end | |
| 554 | end | |
| 555 | ||
| 556 | 1 | private def compile_attributes(node, closing) |
| 557 | 266 | arguments = node.arguments&.arguments |
| 558 | 266 | return NO_ATTRIBUTES if arguments.nil? || arguments.empty? |
| 559 | 62 | return nil unless arguments in [Refract::KeywordHashNode => keyword_hash] |
| 560 | ||
| 561 | 59 | if (static = static_attributes(keyword_hash)) |
| 562 | begin | |
| 563 | 15 | normalize_attributes(node.name, static) |
| 564 | 15 | 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. | |
| 567 | 1 | @diagnostics.report(node, "#{node.name}'s attributes are serialised at runtime because serialising them now raised #{e.class}: #{e.message}") |
| 568 | 1 | return compile_attribute_hash(node.name, keyword_hash, closing) |
| 569 | end | |
| 570 | end | |
| 571 | ||
| 572 | 44 | 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. | |
| 581 | 1 | private def compile_attribute_pieces(node, keyword_hash, closing) |
| 582 | 44 | normalized_keys = Phlex::SGML::Elements::NORMALIZED_ATTRIBUTES[node.name] |
| 583 | 44 | elements = keyword_hash.elements |
| 584 | 101 | last_impure = elements.rindex { |assoc| !(Refract::AssocNode === assoc) || !pure?(attribute_value(assoc)) } |
| 585 | 110 | several_dynamic = elements.count { |assoc| !(Refract::AssocNode === assoc) || !static_attribute_value(attribute_value(assoc)) } > 1 |
| 586 | 44 | keys = Set.new |
| 587 | 44 | hoisted = [] |
| 588 | ||
| 589 | 44 | pieces = catch(:together) do |
| 590 | 44 | elements.each_with_index.map do |assoc, index| |
| 591 | 65 | throw :together, "a key is splatted or isn't a literal" unless assoc in Refract::AssocNode[key: Refract::StringNode | Refract::SymbolNode => key] |
| 592 | ||
| 593 | 59 | key_value = static_value(key) |
| 594 | 59 | throw :together, "#{key_value} is rewritten by the element's attribute normaliser" if normalized_keys&.include?(key_value) |
| 595 | 58 | throw :together, "#{key_value} is repeated" unless keys.add?(key_value)then never taken |
| 596 | ||
| 597 | 58 | attribute_piece(key, key_value, attribute_value(assoc), hoisted, hoist: several_dynamic || (last_impure && index <= last_impure)) |
| 598 | rescue Phlex::ArgumentError => e | |
| 599 | 0 | throw :together, "#{key_value} raised #{e.class}: #{e.message}" |
| 600 | end | |
| 601 | end | |
| 602 | ||
| 603 | 44 | case pieceselse never taken |
| 604 | in String => reason | |
| 605 | 7 | @diagnostics.report(node, "#{node.name}'s attributes are serialised together because #{reason}") |
| 606 | 7 | nil |
| 607 | in Array | |
| 608 | 37 | 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. | |
| 614 | 1 | private def attribute_value(assoc) |
| 615 | 174 | (Refract::ImplicitNode === assoc.value) ? assoc.value.value : assoc.valuethen never taken |
| 616 | end | |
| 617 | ||
| 618 | # One attribute's parts of the opening tag. | |
| 619 | 1 | private def attribute_piece(key, key_value, value, hoisted, hoist:) |
| 620 | 58 | if (static = static_attribute_value(value)) |
| 621 | 9 | return [literal(serialized_attribute(key_value, static[0]))] |
| 622 | end | |
| 623 | ||
| 624 | 49 | name = Phlex::SGML::Attributes.attribute_name(key_value) |
| 625 | 49 | Phlex::SGML::Attributes.validate_attribute_name(key_value, name) |
| 626 | ||
| 627 | 57 | if (folded = fold_conditional(value) { |leaf| (static = static_attribute_value(leaf)) && string(serialized_attribute(key_value, static[0])) }) |
| 628 | 4 | return [hoist ? expression(hoisted_local(folded, hoisted)) : Output::Conditional.new(folded)]else never taken |
| 629 | end | |
| 630 | ||
| 631 | 45 | if (tokens = token_list(key_value, value, hoisted)) |
| 632 | 1 | return [Output::Conditional.new(tokens)] |
| 633 | end | |
| 634 | ||
| 635 | 44 | reference = Phlex::SGML::Attributes.reference_attribute?(name) |
| 636 | ||
| 637 | 44 | if !reference && (nested = nested_attributes(key_value, name, value, hoisted)) |
| 638 | 3 | 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. | |
| 644 | 41 | quotable = Refract::InterpolatedStringNode === value |
| 645 | 41 | safe_prefix = reference && quotable && safe_reference_prefix?(value) |
| 646 | 41 | value = hoisted_local(value, hoisted) if hoist || (quotable && !reference) || safe_prefix |
| 647 | ||
| 648 | 41 | if quotable && !reference |
| 649 | 4 | return [literal(" #{name}=\""), Serialized.new(quoted(value)), literal('"')] |
| 650 | end | |
| 651 | ||
| 652 | 37 | if safe_prefix |
| 653 | 2 | serialized = call(constant("Phlex::SGML::Attributes"), :reference_attribute, key, string(name), value) |
| 654 | 2 | return [Typed.new(name:, cases: Cases.new(cases: [[decodable(value), Value.new(quoted(value))]], otherwise: Text.new(serialized)))] |
| 655 | end | |
| 656 | ||
| 657 | 35 | if reference |
| 658 | 5 | return [Serialized.new(call(constant("Phlex::SGML::Attributes"), :reference_attribute, key, string(name), value))] |
| 659 | end | |
| 660 | ||
| 661 | 30 | value = hoisted_local(value, hoisted) unless hoist |
| 662 | 60 | [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. | |
| 670 | 1 | private def safe_reference_prefix?(node) |
| 671 | 3 | prefix = node.parts.first |
| 672 | 3 | return false unless Refract::StringNode === prefix |
| 673 | ||
| 674 | 2 | text = prefix.unescaped |
| 675 | 2 | return false unless text.ascii_only? && !text.include?("&") && !text.include?('"')then never taken |
| 676 | ||
| 677 | 2 | normalized = text.downcase.delete("^a-z:") |
| 678 | 2 | !normalized.empty? && !normalized.start_with?("javascript:") && !"javascript:".start_with?(normalized) |
| 679 | end | |
| 680 | ||
| 681 | # Whether decoding the string's character references can't raise. | |
| 682 | 1 | private def decodable(node) |
| 683 | 2 | 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. | |
| 696 | 1 | private def typed_attribute(value, name) |
| 697 | 34 | number = Refract::OrNode.new(left: call(constant("Integer"), :===, value), operator: "||", right: call(constant("Float"), :===, value)) |
| 698 | ||
| 699 | 34 | 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 | ||
| 707 | 34 | 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 | ||
| 716 | 34 | 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. | |
| 722 | 1 | private def choice(typed) |
| 723 | 29 | escaped = @locals.fresh(:escaped) |
| 724 | 29 | text = @locals.fresh(:text) |
| 725 | ||
| 726 | 29 | statement = lower_cases(typed.cases) do |outcome| |
| 727 | 170 | case outcomeelse never taken |
| 728 | 85 | in Value[node] then [write(escaped, node)] |
| 729 | 85 | in Text[node] then [write(escaped, Refract::NilNode.new), write(text, node)] |
| 730 | end | |
| 731 | end | |
| 732 | ||
| 733 | 29 | [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. | |
| 737 | 1 | private def built(typed) |
| 738 | 7 | lower_cases(typed.cases) do |outcome| |
| 739 | 38 | case outcomeelse never taken |
| 740 | 19 | in Value[node] then call(call(call(string(" #{typed.name}=\""), :+@), :<<, node), :<<, string('"')) |
| 741 | 19 | in Text[node] then node |
| 742 | end | |
| 743 | end | |
| 744 | end | |
| 745 | ||
| 746 | 1 | private def lower_cases(outcome, &) |
| 747 | 278 | case outcome |
| 748 | in Cases[cases:, otherwise:] | |
| 749 | 242 | elsif_chain(*cases.map { |condition, nested| [condition, lower_cases(nested, &)] }, otherwise: lower_cases(otherwise, &)) |
| 750 | else | |
| 751 | 208 | 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. | |
| 760 | 1 | private def nested_attributes(key_value, name, value, hoisted) |
| 761 | 37 | return unless Refract::HashNode === value && key_value != :style |
| 762 | ||
| 763 | 3 | base = "#{name}-" |
| 764 | 8 | return unless value.elements.all? { |assoc| assoc in Refract::AssocNode[key: Refract::StringNode | Refract::SymbolNode] }then never taken |
| 765 | ||
| 766 | 8 | entries = value.elements.map { |assoc| [static_value(assoc.key), assoc.key, attribute_value(assoc)] } |
| 767 | 3 | return unless entries.map(&:first).uniq.length == entries.lengththen never taken |
| 768 | ||
| 769 | begin | |
| 770 | 3 | entries = entries.map do |(nested_key_value, nested_key, nested_value)| |
| 771 | 5 | nested_name = Phlex::Compiler.nested_attributes(nested_key_value, true, base).delete_prefix(" ") |
| 772 | ||
| 773 | 5 | if (static = static_attribute_value(nested_value)) |
| 774 | 1 | [:static, Phlex::Compiler.nested_attributes(nested_key_value, static[0], base)] |
| 775 | else | |
| 776 | 4 | [: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. | |
| 781 | 0 | return |
| 782 | end | |
| 783 | ||
| 784 | 3 | entries.map do |entry| |
| 785 | 5 | case entryelse never taken |
| 786 | in [:static, text] | |
| 787 | 1 | literal(text) |
| 788 | in [:dynamic, nested_key, nested_name, nested_value] | |
| 789 | 4 | nested_value = hoisted_local(nested_value, hoisted) |
| 790 | 8 | 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. | |
| 796 | 1 | private def elsif_chain(*branches, otherwise:) |
| 797 | 168 | branches.reverse.reduce(Refract::ElseNode.new(statements: statements(Array(otherwise)))) do |subsequent, (predicate, body)| |
| 798 | 564 | 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. | |
| 807 | 1 | private def token_list(key_value, value, hoisted) |
| 808 | 45 | return unless Refract::ArrayNode === value |
| 809 | ||
| 810 | 12 | tokens = catch(:dynamic) { value.elements.map { |element| token_choice(element) } } |
| 811 | 3 | choices = tokens&.grep(TokenChoice) |
| 812 | 3 | return unless choices&.length&.between?(1, TOKEN_CONDITIONS_LIMIT) |
| 813 | ||
| 814 | 1 | texts = token_texts(key_value, tokens, choices.length) |
| 815 | 1 | return unless textsthen never taken |
| 816 | ||
| 817 | 1 | conditions = choices.map do |choice| |
| 818 | 2 | hoisted_local(if_node(choice.condition, [Refract::TrueNode.new], else_body: [Refract::FalseNode.new]), hoisted) |
| 819 | end | |
| 820 | ||
| 821 | 1 | token_tree(conditions, texts) |
| 822 | end | |
| 823 | ||
| 824 | # The serialised text for each combination of the conditions. | |
| 825 | 1 | private def token_texts(key_value, tokens, conditions) |
| 826 | 1 | texts = [true, false].repeated_permutation(conditions).to_h do |picks| |
| 827 | 4 | pick = picks.each |
| 828 | 16 | chosen = tokens.map { |token| (TokenChoice === token) ? (pick.next ? token.truthy : token.falsy) : token } |
| 829 | 4 | [picks, serialized_attribute(key_value, chosen)] |
| 830 | end | |
| 831 | ||
| 832 | 1 | texts if texts.each_value.all?(&:ascii_only?)else never taken |
| 833 | rescue | |
| 834 | 0 | nil |
| 835 | end | |
| 836 | ||
| 837 | 1 | private def token_tree(conditions, texts, picks = []) |
| 838 | 7 | return string(texts.fetch(picks)) if picks.length == conditions.length |
| 839 | ||
| 840 | 3 | 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. | |
| 844 | 1 | private def token_choice(node) |
| 845 | 8 | case node |
| 846 | 2 | in Refract::ParenthesesNode[body: Refract::StatementsNode[body: [inner]]] then token_choice(inner) |
| 847 | in Refract::IfNode[subsequent: nil | Refract::ElseNode] | |
| 848 | 2 | TokenChoice.new(condition: node.predicate, truthy: branch_token(node.statements), falsy: branch_token(node.subsequent&.statements)) |
| 849 | in Refract::UnlessNode | |
| 850 | 0 | TokenChoice.new(condition: node.predicate, truthy: branch_token(node.else_clause&.statements), falsy: branch_token(node.statements))in never taken |
| 851 | else | |
| 852 | 4 | token_literal(node) |
| 853 | end | |
| 854 | end | |
| 855 | ||
| 856 | 1 | private def branch_token(branch) |
| 857 | 4 | case branch |
| 858 | 1 | in nil then nil |
| 859 | 3 | in Refract::StatementsNode[body: [statement]] then token_literal(statement) |
| 860 | 0 | else throw :dynamicelse never taken |
| 861 | end | |
| 862 | end | |
| 863 | ||
| 864 | 1 | private def token_literal(node) |
| 865 | 7 | case node |
| 866 | 5 | in Refract::StringNode | Refract::SymbolNode | Refract::IntegerNode | Refract::FloatNode | Refract::NilNode | Refract::FalseNode then static_value(node) |
| 867 | 0 | in Refract::ArrayNode then node.elements.map { |element| token_literal(element) }in never taken |
| 868 | 2 | else throw :dynamic |
| 869 | end | |
| 870 | end | |
| 871 | ||
| 872 | # The runtime only copies the string if it has quotes to escape. | |
| 873 | 1 | private def quoted(node) |
| 874 | 40 | parenthesized([ |
| 875 | if_node(call(node, :include?, string('"')), [call(constant("Phlex::Compiler"), :escape_quotes, node)], else_body: [node]), | |
| 876 | ]) | |
| 877 | end | |
| 878 | ||
| 879 | 1 | private def hoisted_local(node, hoisted) |
| 880 | 57 | local = @locals.fresh(:value) |
| 881 | 57 | hoisted << write(local, visit(node)) |
| 882 | 57 | read(local) |
| 883 | end | |
| 884 | ||
| 885 | 1 | private def serialized_attribute(key, value) |
| 886 | 21 | 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. | |
| 892 | 1 | private def attribute_parts(parts, closing) |
| 893 | 37 | writes = [] |
| 894 | ||
| 895 | 83 | last = parts.rindex { |part| part in Serialized | Typed } |
| 896 | ||
| 897 | 37 | parts = parts.each_with_index.map do |part, index| |
| 898 | 66 | part = Serialized.new(built(part)) if Typed === part && index != last |
| 899 | ||
| 900 | 66 | case part |
| 901 | in Serialized[node] | |
| 902 | 16 | local = @locals.fresh(:attribute) |
| 903 | 16 | writes << write(local, node) |
| 904 | 16 | expression(read(local)) |
| 905 | in Typed | |
| 906 | 29 | statement, choice = choice(part) |
| 907 | 29 | writes << statement |
| 908 | 29 | choice |
| 909 | else | |
| 910 | 21 | part |
| 911 | end | |
| 912 | end | |
| 913 | ||
| 914 | 37 | return parts if writes.empty? |
| 915 | ||
| 916 | # A choice is appended as statements, so the guard can't return it. | |
| 917 | 36 | parts.unshift(literal("")) if Output::Choice === parts.first |
| 918 | 36 | parts[0] = Output::Guarded.new(statements: writes, result: parts[0], closing:) |
| 919 | 36 | parts |
| 920 | end | |
| 921 | ||
| 922 | 1 | private def compile_attribute_hash(element, keyword_hash, closing) |
| 923 | 8 | hash = case keyword_hash.elements |
| 924 | 6 | in [*, Refract::AssocSplatNode, *] then call(constant("Phlex::Compiler"), :keywords, keyword_hash) |
| 925 | 2 | else Refract::HashNode.new(elements: keyword_hash.elements) |
| 926 | end | |
| 927 | 8 | hoisted = [] |
| 928 | 8 | hash = hoisted_local(hash, hoisted) |
| 929 | 8 | attributes = @locals.fresh(:attributes) |
| 930 | ||
| 931 | # Element methods only serialise a hash that has something in it. | |
| 932 | 8 | 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 | ||
| 938 | 8 | 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. | |
| 951 | 1 | private def cached_attributes(hash) |
| 952 | 8 | 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. | |
| 961 | 1 | private def normalize_call(element, hash) |
| 962 | 8 | if (normalizer = attribute_normalizer(element)) |
| 963 | 1 | [call(constant("Phlex::SGML::Elements"), normalizer, hash)] |
| 964 | else | |
| 965 | 7 | [] |
| 966 | end | |
| 967 | end | |
| 968 | ||
| 969 | 1 | private def normalize_attributes(element, attributes) |
| 970 | 15 | if (normalizer = attribute_normalizer(element)) |
| 971 | 0 | Phlex::SGML::Elements.public_send(normalizer, attributes)then never taken |
| 972 | end | |
| 973 | end | |
| 974 | ||
| 975 | 1 | private def attribute_normalizer(element) |
| 976 | 23 | Phlex::SGML::Elements::ATTRIBUTE_NORMALIZERS[element] |
| 977 | end | |
| 978 | ||
| 979 | 1 | private def static_attributes(keyword_hash) |
| 980 | 144 | catch(:dynamic) { static_hash(keyword_hash.elements) } |
| 981 | end | |
| 982 | ||
| 983 | # The value wrapped in an array, since a static value can be nil. | |
| 984 | 1 | private def static_attribute_value(node) |
| 985 | 262 | catch(:dynamic) { [static_value(node)] } |
| 986 | end | |
| 987 | ||
| 988 | 1 | private def static_hash(elements) |
| 989 | 80 | elements.to_h do |element| |
| 990 | 102 | throw :dynamic unless Refract::AssocNode === element |
| 991 | 96 | throw :dynamic unless element.key in Refract::StringNode | Refract::SymbolNodethen never taken |
| 992 | 96 | [static_value(element.key), static_value(element.value)] |
| 993 | end | |
| 994 | end | |
| 995 | ||
| 996 | 1 | private def static_value(node) |
| 997 | 423 | case node |
| 998 | 68 | in Refract::StringNode then node.unescaped |
| 999 | 162 | in Refract::SymbolNode then node.unescaped.to_sym |
| 1000 | 21 | in Refract::IntegerNode | Refract::FloatNode then node.value |
| 1001 | 1 | in Refract::TrueNode then true |
| 1002 | 1 | in Refract::FalseNode then false |
| 1003 | 6 | in Refract::NilNode then nil |
| 1004 | 32 | in Refract::ArrayNode then node.elements.map { |element| static_value(element) } |
| 1005 | 8 | in Refract::HashNode then static_hash(node.elements) |
| 1006 | 13 | in Refract::CallNode if set_literal?(node) then Set.new(node.arguments.arguments.map { |element| static_value(element) }) |
| 1007 | 142 | else throw :dynamic |
| 1008 | end | |
| 1009 | end | |
| 1010 | ||
| 1011 | 1 | private def set_literal?(node) |
| 1012 | 40 | node.name == :[] && node.block.nil? && node.arguments && ( |
| 1013 | 9 | (Refract::ConstantReadNode === node.receiver && node.receiver.name == :Set && @environment.standard_set?) || |
| 1014 | 7 | (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. | |
| 1024 | 1 | private def fold_conditional(node, &leaf) |
| 1025 | 53 | case node |
| 1026 | 12 | in Refract::IfNode | Refract::UnlessNode then catch(:dynamic) { fold(node, &leaf) } |
| 1027 | 2 | in Refract::ParenthesesNode[body: Refract::StatementsNode[body: [inner]]] then fold_conditional(inner, &leaf) |
| 1028 | 45 | else nil |
| 1029 | end | |
| 1030 | end | |
| 1031 | ||
| 1032 | 1 | private def fold(node, &leaf) |
| 1033 | 24 | case node |
| 1034 | in Refract::IfNode | |
| 1035 | 6 | node.copy(inline: false, statements: fold_branch(node.statements, &leaf), subsequent: fold_else(node.subsequent, &leaf)) |
| 1036 | in Refract::UnlessNode | |
| 1037 | 0 | 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 | |
| 1039 | 6 | node.copy(statements: fold_branch(node.statements, &leaf)) |
| 1040 | in Refract::ParenthesesNode[body: Refract::StatementsNode[body: [inner]]] | |
| 1041 | 0 | node.copy(body: statements([fold_nested(inner, &leaf)]))in never taken |
| 1042 | else | |
| 1043 | 12 | leaf.call(node) || throw(:dynamic) |
| 1044 | end | |
| 1045 | end | |
| 1046 | ||
| 1047 | 1 | private def fold_nested(node, &leaf) |
| 1048 | 18 | throw :dynamic if node in Refract::IfNode | Refract::UnlessNode and !pure?(node.predicate)then never taken |
| 1049 | ||
| 1050 | 18 | fold(node, &leaf) |
| 1051 | end | |
| 1052 | ||
| 1053 | 1 | private def fold_branch(branch, &leaf) |
| 1054 | 12 | case branch |
| 1055 | 0 | in nil then statements([fold(Refract::NilNode.new, &leaf)])in never taken |
| 1056 | 12 | in Refract::StatementsNode[body: [statement]] then statements([fold_nested(statement, &leaf)]) |
| 1057 | 0 | else throw :dynamicelse never taken |
| 1058 | end | |
| 1059 | end | |
| 1060 | ||
| 1061 | 1 | private def fold_else(node, &leaf) |
| 1062 | 6 | 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. | |
| 1071 | 1 | private def pure?(node) |
| 1072 | 223 | 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 | |
| 1077 | 62 | true |
| 1078 | 20 | in Refract::ArrayNode | Refract::HashNode | Refract::KeywordHashNode then node.elements.all? { |element| pure?(element) } |
| 1079 | 5 | in Refract::AssocNode[key: Refract::StringNode | Refract::SymbolNode | Refract::IntegerNode | Refract::FloatNode | Refract::NilNode | Refract::TrueNode | Refract::FalseNode] then pure?(node.value) |
| 1080 | 25 | in Refract::InterpolatedStringNode then node.parts.all? { |part| Refract::StringNode === part } |
| 1081 | 5 | in Refract::ParenthesesNode then pure?(node.body) |
| 1082 | 36 | in Refract::StatementsNode then node.body.all? { |statement| pure?(statement) } |
| 1083 | 8 | in Refract::IfNode then pure?(node.predicate) && pure?(node.statements) && pure?(node.subsequent) |
| 1084 | 0 | in Refract::UnlessNode then pure?(node.predicate) && pure?(node.statements) && pure?(node.else_clause)in never taken |
| 1085 | 6 | in Refract::ElseNode then pure?(node.statements) |
| 1086 | 1 | in Refract::AndNode | Refract::OrNode then pure?(node.left) && pure?(node.right) |
| 1087 | 101 | 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. | |
| 1093 | 1 | private def compile_plain(node) |
| 1094 | # Keep runtime block rejection and evaluation of forwarded block expressions. | |
| 1095 | 33 | return keep_call(node, "it has a block") if node.blockthen never taken |
| 1096 | 33 | return keep_call(node, "__text__ is overridden") unless @environment.helper?(:__text__)then never taken |
| 1097 | ||
| 1098 | 33 | compiled = case node.arguments&.argumentsreceiver never nil |
| 1099 | 17 | in [Refract::StringNode | Refract::SymbolNode => text] then plain(text.unescaped) |
| 1100 | in [Refract::InterpolatedStringNode => interpolated] | |
| 1101 | 4 | text = @locals.fresh(:text) |
| 1102 | 4 | statements([write(text, visit(interpolated)), append(expression(escaped(read(text))))]) |
| 1103 | 0 | in [Refract::NilNode] then Refract::NilNode.newin never taken |
| 1104 | 12 | else return keep_call(node, "its argument isn't a literal or an interpolation") |
| 1105 | end | |
| 1106 | ||
| 1107 | 21 | @environment.inlined.merge(%i[__text__ block_given?]) |
| 1108 | 21 | compiled |
| 1109 | end | |
| 1110 | ||
| 1111 | # `raw safe("…")` is a literal that skips escaping. | |
| 1112 | 1 | private def compile_raw(node) |
| 1113 | # Keep evaluation of forwarded block expressions, which may raise. | |
| 1114 | 6 | return keep_call(node, "it has a block") if node.blockthen never taken |
| 1115 | ||
| 1116 | 6 | 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) | |
| 1118 | 1 | @environment.inlined << :safe |
| 1119 | 1 | raw(text.unescaped) |
| 1120 | else | |
| 1121 | 5 | keep_call(node, "its argument isn't safe with a string literal") |
| 1122 | end | |
| 1123 | end | |
| 1124 | ||
| 1125 | 1 | private def compile_whitespace(node) |
| 1126 | 4 | return keep_call(node, "it has arguments") if node.arguments |
| 1127 | ||
| 1128 | 3 | if node.block.nil? |
| 1129 | 1 | @environment.inlined << :block_given? |
| 1130 | 1 | return raw(" ") |
| 1131 | end | |
| 1132 | ||
| 1133 | 2 | compile_wrapped_content(node, " ", " ") |
| 1134 | end | |
| 1135 | ||
| 1136 | 1 | private def compile_comment(node) |
| 1137 | 3 | return keep_call(node, "it has arguments") if node.argumentsthen never taken |
| 1138 | ||
| 1139 | 3 | 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. | |
| 1147 | 1 | private def compile_wrapped_content(node, opening, closing) |
| 1148 | 5 | 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. | |
| 1150 | 2 | return keep_call(node, "__yield_content__ or __implicit_output__ is overridden") |
| 1151 | end | |
| 1152 | ||
| 1153 | 3 | return compile_call_with_content(node, because: "its block is forwarded or #{UNINLINABLE_BLOCK}") unless inlinable_content?(node.block) |
| 1154 | ||
| 1155 | 2 | @environment.inlined.merge(%i[__yield_content__ __implicit_output__ block_given?]) |
| 1156 | 2 | statements([raw(opening), *compile_content(node), raw(closing)]) |
| 1157 | end | |
| 1158 | ||
| 1159 | 1 | private def inlinable_content?(block) |
| 1160 | 3 | case block |
| 1161 | 0 | in nil | Refract::BlockNode[parameters: nil, body: nil] then truein never taken |
| 1162 | 3 | in Refract::BlockNode then inlinable?(block) |
| 1163 | 0 | else falseelse never taken |
| 1164 | end | |
| 1165 | end | |
| 1166 | ||
| 1167 | 1 | private def compile_doctype(node) |
| 1168 | 1 | return keep_call(node, "it has arguments or a block") if node.arguments || node.blockelse never taken |
| 1169 | ||
| 1170 | 0 | 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. | |
| 1175 | 1 | private def compile_fragment(node) |
| 1176 | 17 | return keep_call(node, "its block has parameters or is forwarded") unless node.block in Refract::BlockNode[parameters: nil] |
| 1177 | ||
| 1178 | 16 | compile_call_with_content(node) |
| 1179 | end | |
| 1180 | ||
| 1181 | 1 | private def keep_call(node, because) |
| 1182 | 35 | @diagnostics.report(node, "#{node.name} keeps its call because #{because}") |
| 1183 | 35 | nil |
| 1184 | end | |
| 1185 | ||
| 1186 | 1 | private def escaped(node) |
| 1187 | 298 | call(constant("Phlex::Escape"), :html_escape, node) |
| 1188 | end | |
| 1189 | ||
| 1190 | 1 | private def plain(text) |
| 1191 | 115 | raw(Phlex::Escape.html_escape(text)) |
| 1192 | end | |
| 1193 | ||
| 1194 | 1 | private def raw(text) |
| 1195 | 358 | append(literal(text)) |
| 1196 | end | |
| 1197 | ||
| 1198 | 1 | private def literal(text) |
| 1199 | 938 | text => String |
| 1200 | ||
| 1201 | 938 | Output::Literal.new(text) |
| 1202 | end | |
| 1203 | ||
| 1204 | 1 | private def expression(node) |
| 1205 | 32 | Output::Expression.new(node) |
| 1206 | end | |
| 1207 | ||
| 1208 | 1 | private def append(*parts) |
| 1209 | 625 | @appends += 1 |
| 1210 | 625 | state_local |
| 1211 | ||
| 1212 | 625 | Output::Append.new(parts:) |
| 1213 | end | |
| 1214 | ||
| 1215 | 1 | private def opening(buffer, *parts) |
| 1216 | 2 | @appends += 1 |
| 1217 | 2 | state_local |
| 1218 | ||
| 1219 | 2 | 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. | |
| 1224 | 1 | private def state_local |
| 1225 | 1073 | unless @state_local_set || @guarded_blocks > 0 |
| 1226 | 148 | @preamble << write(Locals::STATE, Refract::InstanceVariableReadNode.new(name: :@_state)) |
| 1227 | 148 | @state_local_set = true |
| 1228 | end | |
| 1229 | ||
| 1230 | 1073 | Locals::STATE |
| 1231 | end | |
| 1232 | ||
| 1233 | 1 | private def self_local |
| 1234 | 34 | unless @self_local_set |
| 1235 | 18 | @preamble << write(Locals::SELF, Refract::SelfNode.new) |
| 1236 | 18 | @self_local_set = true |
| 1237 | end | |
| 1238 | ||
| 1239 | 34 | Locals::SELF |
| 1240 | end | |
| 1241 | end | |
| 1242 | end |