lib/phlex/compiler.rb
Lines
95%210 of 219 covered
Branches
82%73 of 89 covered
Methods
97%39 of 40 covered
- Not run
- 96121-124232307495556
- Never called
| 1 | # frozen_string_literal: true | |
| 2 | ||
| 3 | 1 | require "prism" |
| 4 | 1 | require "refract" |
| 5 | ||
| 6 | # Rewrites component methods ahead of time so that element calls become direct | |
| 7 | # buffer appends. Compilation is opt-in and safe to skip: an uncompiled | |
| 8 | # component renders exactly the same, just slower. | |
| 9 | # | |
| 10 | # Use `Phlex::Compiler.compile(component)` to compile a class, or | |
| 11 | # `Phlex::Compiler.enable!` to compile each class on its first render. | |
| 12 | # `Phlex::Compiler.explain(component)` lists what's left to the runtime and why. | |
| 13 | # | |
| 14 | # A component's live methods say which files and lines define them. Each file | |
| 15 | # is parsed with Prism and converted to a Refract tree, and FileCompiler | |
| 16 | # compiles the definitions at those lines, after reopening the class and | |
| 17 | # module statements around them with a probe so Ruby confirms which class they | |
| 18 | # name. MethodCompiler decides what each call means, using an Environment built | |
| 19 | # once per class body, and leaves Output nodes in the tree where text is | |
| 20 | # appended. The Emitter then lowers those to guarded buffer appends. The | |
| 21 | # compiled definitions are evaluated inside the original nesting under a path | |
| 22 | # of their own, and exceptions are mapped back to the real file. | |
| 23 | # | |
| 24 | # The compiler is meant to be invisible: a compiled component renders exactly | |
| 25 | # what it would have uncompiled, and code that can't be compiled faithfully is | |
| 26 | # refused with a Phlex::Compiler::Error naming the file and line rather than | |
| 27 | # compiled approximately. Refused: a method marked `ruby2_keywords`, a `using` | |
| 28 | # that applies to only part of its file, two definitions of a method on one | |
| 29 | # line, a local or bare call named like a local the compiler generates | |
| 30 | # (`__phlex_…`), a file edited since it was loaded, a refinement in the file | |
| 31 | # of a method compiled code calls for the runtime, such as String#include?, | |
| 32 | # or such a core method redefined in Ruby, and redefining an inlined element | |
| 33 | # or helper on a single instance with `extend` or a singleton method. | |
| 34 | # Redefining one on a class or by including a module recompiles whatever | |
| 35 | # inlined it. | |
| 36 | # | |
| 37 | # Seven differences remain, all deliberate: | |
| 38 | # - Changing what an inlined element or helper resolves to through a module | |
| 39 | # already mixed into a compiled component, or into Phlex::SVG for an inlined | |
| 40 | # svg block, isn't seen: defining, removing or undefining it on that module, | |
| 41 | # changing its visibility there, or mixing another module into it. Nor is | |
| 42 | # changing the visibility of a method where it's defined, such as `new` on | |
| 43 | # Phlex::SGML. Call `Phlex::Compiler.recompile` on each class whose methods | |
| 44 | # inlined it. A method already running when one is redefined finishes as | |
| 45 | # compiled. | |
| 46 | # - Attributes with literal keys are serialised without the attribute cache, so | |
| 47 | # a value's `to_s`, `to_h` or `iso8601` runs on every render rather than once | |
| 48 | # per distinct set of attributes, and its `hash` isn't called. | |
| 49 | # - Compiled code appends the text of neighbouring elements together and reads | |
| 50 | # the state once per method. When an append itself fails, because the buffer | |
| 51 | # is frozen or holds text in an encoding the new text can't join, the partial | |
| 52 | # output, the exception raised and its `cause` can differ from element | |
| 53 | # methods appending one by one. A buffer switched mid-element, by a Fiber | |
| 54 | # suspended inside `capture`, and a method that started before rendering, | |
| 55 | # can see a different buffer, and the buffer itself passed as an attribute | |
| 56 | # value is read after the attribute's name is appended to it. Whether to | |
| 57 | # render is checked at each append, where an element method checks once, | |
| 58 | # which only matters to code starting a fragment mid-element. A State | |
| 59 | # subclass overriding its methods sees them called a different number of | |
| 60 | # times, and an inlined svg block skips the State and core methods the | |
| 61 | # runtime calls to render its Phlex::SVG, such as `around_render` and | |
| 62 | # `Thread#[]=`. | |
| 63 | # - Static text and attributes are escaped and serialised once, when | |
| 64 | # compiling, outside `Regexp.timeout`, and so are references whose prefix | |
| 65 | # is known. A core method compiled code calls that's redefined after | |
| 66 | # compiling isn't noticed. A String subclass whose `gsub` returns something | |
| 67 | # other than a String, which the serialiser's own paths treat differently, | |
| 68 | # renders as its path for names it's seen before does. | |
| 69 | # - Method#source_location of a compiled method names the generated source; | |
| 70 | # exceptions are mapped back to the real file. `local_variables` and | |
| 71 | # `binding` in a compiled method also see the compiler's `__phlex_` locals. | |
| 72 | # - A block passed to a method the compiler doesn't know is compiled alongside | |
| 73 | # a copy of the original, used when the block runs with another `self`. A | |
| 74 | # literal Ruby reuses on each evaluation, such as a regular expression or a | |
| 75 | # range, is a different object in each copy. | |
| 76 | # | |
| 77 | # Methods a component gains from mixins aren't compiled, which only costs speed. | |
| 78 | 1 | module Phlex::Compiler |
| 79 | # Compiled code is evaluated under a path of its own so its line numbers | |
| 80 | # never collide with the file's, and each compilation of a file gets a new | |
| 81 | # one so exceptions from an old generation still map correctly. | |
| 82 | 1 | Generation = Data.define(:path, :lines) |
| 83 | ||
| 84 | # A live method and the line in the file being compiled that defines it. | |
| 85 | 1 | Target = Data.define(:component, :name, :line, :compiled, :replaced) |
| 86 | ||
| 87 | # What reopening a definition's class and module statements reached. | |
| 88 | 1 | Probe = Data.define(:component, :set, :method_resolver, :refinements) |
| 89 | ||
| 90 | 1 | MUTEX = Mutex.new |
| 91 | ||
| 92 | # component => the exception that stopped it compiling on first render | |
| 93 | 1 | FAILURES = {}.compare_by_identity |
| 94 | ||
| 95 | 1 | DEFAULT_FAILURE_HANDLER = lambda do |component, error| |
| 96 | 0 | warn "Phlex::Compiler couldn't compile #{component}, so it renders uncompiled: #{error.class}: #{error.message}\n\t#{error.backtrace&.first(5)&.join("\n\t")}" |
| 97 | end | |
| 98 | ||
| 99 | 1 | PROBE_PATH = "(phlex compiler probe)" |
| 100 | 1 | SCOPE_PATH = File.expand_path("compiler/scope.rb", __dir__) |
| 101 | ||
| 102 | # Bindings handed over by compiler/scope.rb as it's loaded. | |
| 103 | 1 | SCOPES = [] |
| 104 | ||
| 105 | 1 | @enabled = false |
| 106 | 1 | @recompiling = false |
| 107 | 1 | @generations = 0 |
| 108 | 1 | @on_failure = DEFAULT_FAILURE_HANDLER |
| 109 | ||
| 110 | 1 | def self.enabled? = @enabled |
| 111 | ||
| 112 | # Compiled code builds splatted attributes with this rather than a Hash | |
| 113 | # literal, since before Ruby 3.4 `**nil` is only allowed in a call. | |
| 114 | 1 | def self.keywords(**keywords) = keywords |
| 115 | ||
| 116 | # Compiled code escapes quotes with this, so the match data gsub sets stays | |
| 117 | # out of the component's method, as at runtime. | |
| 118 | 1 | def self.escape_quotes(value) = value.gsub('"', """) |
| 119 | ||
| 120 | # Compiled code writes a Symbol attribute value with this, as the serialiser does. | |
| 121 | 0 | def self.symbol_value(symbol) |
| 122 | 0 | name = symbol.name |
| 123 | 0 | name = name.tr("_", "-") if name.include?("_") |
| 124 | 0 | name.include?('"') ? name.gsub('"', """) : name |
| 125 | end | |
| 126 | ||
| 127 | # Compiled code yields to an element's block with this when the block can't | |
| 128 | # be inlined, as the element method yields to it. | |
| 129 | 1 | def self.yield_component(component) = yield(component) |
| 130 | ||
| 131 | # Compiled code serialises one entry of a nested attribute hash with this, | |
| 132 | # as the runtime does within the whole hash. | |
| 133 | 1 | def self.nested_attributes(key, value, base) |
| 134 | 17 | buffer = +"" |
| 135 | 17 | Phlex::SGML::Attributes.generate_nested_attributes({ key => value }, base, buffer) |
| 136 | 16 | buffer |
| 137 | end | |
| 138 | ||
| 139 | # Compile each component on its first render. A component that fails to | |
| 140 | # compile is reported to `on_failure` once and keeps rendering uncompiled, | |
| 141 | # so a compiler bug costs speed, never a page. | |
| 142 | # | |
| 143 | # Only the main Ractor compiles. Other Ractors render a component as they | |
| 144 | # find it, without waiting for a compilation in progress, so compile with | |
| 145 | # `Phlex::Compiler.compile` before starting them. | |
| 146 | 1 | def self.enable!(on_failure: DEFAULT_FAILURE_HANDLER) |
| 147 | # Prepended under the lock, so it isn't taken for a change to what's been | |
| 148 | # inlined: it only compiles a component before rendering it as before. | |
| 149 | 6 | MUTEX.synchronize { Phlex::SGML.prepend(LazyCompilation) } unless Phlex::SGML < LazyCompilation |
| 150 | 5 | @on_failure = on_failure |
| 151 | 5 | @enabled = true |
| 152 | end | |
| 153 | ||
| 154 | 1 | def self.disable! |
| 155 | 5 | @enabled = false |
| 156 | end | |
| 157 | ||
| 158 | 1 | def self.compiled?(component) |
| 159 | 213 | component.instance_variable_get(:@__phlex_compiled__) == true |
| 160 | end | |
| 161 | ||
| 162 | # Runs on every render, so a component that's compiled, or failed to, | |
| 163 | # returns without the lock, and doesn't wait for another to compile. The | |
| 164 | # check is repeated under the lock, so two first renders racing each other | |
| 165 | # still compile and report once. A render that starts during a | |
| 166 | # recompilation takes the lock, and so waits for the new methods. The | |
| 167 | # handler runs outside it, since it may well render something. | |
| 168 | 1 | def self.compile_on_first_render(component) |
| 169 | 10 | return unless Phlex.__main_ractor__?then never taken |
| 170 | 10 | return if !@recompiling && (compiled?(component) || FAILURES.key?(component)) |
| 171 | ||
| 172 | 6 | error = MUTEX.synchronize do |
| 173 | 6 | return if compiled?(component) || FAILURES.key?(component) |
| 174 | ||
| 175 | begin | |
| 176 | 5 | compile_ancestry(component) |
| 177 | 4 | nil |
| 178 | rescue StandardError, ScriptError => e | |
| 179 | 1 | FAILURES[component] = e |
| 180 | end | |
| 181 | end | |
| 182 | ||
| 183 | 5 | @on_failure.call(component, error) if error |
| 184 | end | |
| 185 | ||
| 186 | # Compiles the methods of the component and its Phlex ancestors wherever | |
| 187 | # they're defined. The files must already be loaded. | |
| 188 | 1 | def self.compile(component) |
| 189 | 59 | component!(component) |
| 190 | ||
| 191 | 118 | MUTEX.synchronize { compile_ancestry(component) } |
| 192 | end | |
| 193 | ||
| 194 | 1 | def self.compile_ancestry(component) |
| 195 | 64 | return if component.frozen? || compiled?(component) |
| 196 | ||
| 197 | 187 | ancestors = phlex_ancestors(component).reject { |ancestor| ancestor.frozen? || compiled?(ancestor) } |
| 198 | 129 | components = ancestors.select { |ancestor| live?(ancestor) } |
| 199 | ||
| 200 | 126 | components.flat_map { |ancestor| defining_files(ancestor) }.uniq.each do |path| |
| 201 | 66 | compile_file(path, components:) |
| 202 | end | |
| 203 | ||
| 204 | 115 | ancestors.each { |ancestor| ancestor.instance_variable_set(:@__phlex_compiled__, true) } |
| 205 | end | |
| 206 | ||
| 207 | # Why parts of the files defining the component and its Phlex ancestors are | |
| 208 | # left to the runtime, as Diagnostics::Diagnostic records in file order. | |
| 209 | # Nothing is compiled; an already compiled method is reported as such. | |
| 210 | 1 | def self.explain(component) |
| 211 | 6 | component!(component) |
| 212 | ||
| 213 | 6 | ancestors = phlex_ancestors(component) |
| 214 | ||
| 215 | 6 | failures = ancestors.filter_map do |ancestor| |
| 216 | 12 | next unless (error = FAILURES[ancestor]) |
| 217 | ||
| 218 | 1 | Diagnostics::Diagnostic.new(path: constant_source_path(ancestor), line: nil, message: "compiling #{ancestor} raised #{error.class}: #{error.message}") |
| 219 | end | |
| 220 | ||
| 221 | 18 | failures + ancestors.flat_map { |ancestor| defining_files(ancestor) }.uniq.flat_map do |path| |
| 222 | 12 | diagnostics = Diagnostics.new(path, strict: false) |
| 223 | 12 | FileCompiler.new(path, targets: targets(path, ancestors), diagnostics:).compile(parse(File.read(path), path)) |
| 224 | 12 | diagnostics.to_a |
| 225 | end | |
| 226 | end | |
| 227 | ||
| 228 | # Compiles the methods that the given components, by default every loaded | |
| 229 | # one, define in an already-loaded file. | |
| 230 | 1 | def self.compile_file(path, components: loaded_components, recompile: false, inline: true) |
| 231 | 121 | unless File.exist?(path) |
| 232 | 0 | raise ArgumentError, "Can’t compile #{path} because it doesn’t exist."then never taken |
| 233 | end | |
| 234 | ||
| 235 | 121 | parse_result = Prism.parse(without_byte_order_mark(File.read(path)), filepath: path) |
| 236 | 121 | file_compiler = FileCompiler.new(path, targets: targets(path, components, recompile:), recompile:, inline:) |
| 237 | 233 | results = file_compiler.compile(Refract::Converter.new.visit(parse_result.value)).reject { |result| result.compiled_snippets.empty? } |
| 238 | 109 | return if results.empty? |
| 239 | ||
| 240 | 94 | program = Refract::StatementsNode.new( |
| 241 | 103 | body: [*file_compiler.usings, *results.map { |result| wrap_in_namespace(result.namespace, result.compiled_snippets) }] |
| 242 | ) | |
| 243 | 94 | formatting_result = Refract::Formatter.new(starting_line: 2).format_node(program) |
| 244 | ||
| 245 | 94 | compiled_path = -"#{path} (compiled #{@generations += 1})" |
| 246 | ||
| 247 | 94 | lines = {} |
| 248 | 94 | formatting_result.source_map.each_with_index do |original_line, generated_line| |
| 249 | 5170 | lines[generated_line] = original_line if original_line |
| 250 | end | |
| 251 | ||
| 252 | # Added before the methods exist, so nothing running them finds a line unmapped. | |
| 253 | 94 | Phlex.__add_compiled_source_map__(compiled_path, Generation.new(path: -path, lines: lines.freeze)) |
| 254 | ||
| 255 | 94 | without_redefinition_warnings do |
| 256 | 94 | eval( |
| 257 | "#{magic_comments(parse_result)}#{formatting_result.source}", | |
| 258 | scope, | |
| 259 | compiled_path, | |
| 260 | 1 | |
| 261 | ) | |
| 262 | end | |
| 263 | ||
| 264 | 94 | results.each do |result| |
| 265 | 103 | result.visibilities.each do |name, visibility| |
| 266 | 108 | result.component.__send__(visibility, name) unless visibility == :public |
| 267 | end | |
| 268 | ||
| 269 | 103 | inlined = result.component.instance_variable_get(:@__phlex_inlined__) || Set.new |
| 270 | 103 | result.component.instance_variable_set(:@__phlex_inlined__, (inlined | result.inlined).freeze) |
| 271 | ||
| 272 | 103 | inlined_svg = result.component.instance_variable_get(:@__phlex_inlined_svg__) || Set.new |
| 273 | 103 | result.component.instance_variable_set(:@__phlex_inlined_svg__, (inlined_svg | result.inlined_svg).freeze) |
| 274 | end | |
| 275 | ||
| 276 | 94 | nil |
| 277 | end | |
| 278 | ||
| 279 | # Called by Phlex::SGML when methods are defined on, removed from or mixed | |
| 280 | # into a class or singleton class. A compiled class above or below it that | |
| 281 | # inlined one of them is recompiled, and with the change now loaded it | |
| 282 | # stops inlining that name, so the change takes effect just as it would | |
| 283 | # have uncompiled. A class that inlined an svg block relying on one of them | |
| 284 | # on Phlex::SVG is recompiled too. An override on a single instance can't | |
| 285 | # be compiled for, so it's refused. | |
| 286 | 1 | def self.inlining_changed(target, names) |
| 287 | 374 | return if Phlex.__main_ractor__? && MUTEX.owned? |
| 288 | ||
| 289 | 303 | related = target.singleton_class? ? target.ancestors : target.ancestors + descendants_of(target) |
| 290 | 303 | affected = related.select do |klass| |
| 291 | 3417 | (inlined = klass.instance_variable_get(:@__phlex_inlined__)) && names.any? { |name| inlined.include?(name) } |
| 292 | end | |
| 293 | ||
| 294 | 303 | if !target.singleton_class? && Phlex::SVG <= target |
| 295 | 15 | affected |= loaded_components.select do |klass| |
| 296 | 627 | (inlined = klass.instance_variable_get(:@__phlex_inlined_svg__)) && names.any? { |name| inlined.include?(name) } |
| 297 | end | |
| 298 | end | |
| 299 | ||
| 300 | 303 | return if affected.empty? |
| 301 | ||
| 302 | 18 | if target.singleton_class? |
| 303 | 3 | raise Error, "#{names.join(', ')} can't be redefined on a single instance: #{affected.join(', ')} compiled it inline. Redefine it on the class, before compiling." |
| 304 | end | |
| 305 | ||
| 306 | 15 | if (frozen = affected.select(&:frozen?)).any? |
| 307 | 0 | raise Error, "#{names.join(', ')} can't be redefined: #{frozen.join(', ')} compiled it inline and was frozen without Phlex::SGML.freeze restoring it."then never taken |
| 308 | end | |
| 309 | ||
| 310 | 30 | affected.each { |component| recompile(component) } |
| 311 | end | |
| 312 | ||
| 313 | # Compiles the component's methods again, replacing the compiled ones. | |
| 314 | 1 | def self.recompile(component, inline: true) |
| 315 | 22 | MUTEX.synchronize do |
| 316 | # Its subclasses render the methods being replaced too. | |
| 317 | 22 | @recompiling = true |
| 318 | 22 | component.remove_instance_variable(:@__phlex_inlined__) if component.instance_variable_defined?(:@__phlex_inlined__) |
| 319 | 22 | component.remove_instance_variable(:@__phlex_inlined_svg__) if component.instance_variable_defined?(:@__phlex_inlined_svg__) |
| 320 | ||
| 321 | 22 | defining_files(component).each do |path| |
| 322 | 26 | compile_file(path, components: [component], recompile: true, inline:) |
| 323 | end | |
| 324 | ensure | |
| 325 | 22 | @recompiling = false |
| 326 | end | |
| 327 | end | |
| 328 | ||
| 329 | # Reinstalls the component's original definitions. A frozen class can't be | |
| 330 | # recompiled when something it inlined changes, so Phlex::SGML.freeze | |
| 331 | # restores a compiled class first. | |
| 332 | 1 | def self.decompile(component) |
| 333 | 2 | recompile(component, inline: false) |
| 334 | end | |
| 335 | ||
| 336 | # Reopens the class and module statements around a definition with nothing | |
| 337 | # inside but a call reporting the class reached, what `Set` names there and | |
| 338 | # the refinements active there. The method resolver captures the file's | |
| 339 | # refinements, so element and helper lookup uses the same lexical scope as | |
| 340 | # the compiled definitions. The statements are copied without their | |
| 341 | # superclasses, so they only reopen. | |
| 342 | # Bind and call separately: TruffleRuby's bind_call loses the caller's refinements. | |
| 343 | 1 | def self.probe(namespace, usings: []) |
| 344 | 127 | report = parse(<<~RUBY, PROBE_PATH).statements.body.first |
| 345 | ::Phlex::Compiler.__probe__(self, defined?(Set) && Set, ->(component, name) { | |
| 346 | ::Phlex::UNBOUND_INSTANCE_METHOD_METHOD.bind(component).call(name) | |
| 347 | }, ::Module.used_modules) | |
| 348 | RUBY | |
| 349 | 127 | program = Refract::StatementsNode.new(body: [*usings, wrap_in_namespace(namespace, [report])]) |
| 350 | 127 | source = Refract::Formatter.new.format_node(program).source |
| 351 | ||
| 352 | 127 | Thread.current[:__phlex_compiler_probe__] = nil |
| 353 | 127 | eval(source, scope, PROBE_PATH, 1) |
| 354 | 127 | Thread.current[:__phlex_compiler_probe__] or raise Error, "Reopening the class and module statements didn't reach a class body:\n#{source}" |
| 355 | end | |
| 356 | ||
| 357 | # A fresh top-level binding, so refinements a compiled file activates stay | |
| 358 | # in it, as they would in a real file. TOPLEVEL_BINDING is shared, and a | |
| 359 | # `using` evaluated there applies to everything evaluated there after. | |
| 360 | 1 | def self.scope |
| 361 | 221 | load SCOPE_PATH |
| 362 | 221 | SCOPES.pop |
| 363 | end | |
| 364 | ||
| 365 | 1 | def self.__probe__(component, set, method_resolver, refinements) |
| 366 | 127 | Thread.current[:__phlex_compiler_probe__] = Probe.new(component:, set:, method_resolver:, refinements:) |
| 367 | end | |
| 368 | ||
| 369 | # Whether the class is still the one its name refers to. After a reload the | |
| 370 | # old class object lingers, and reopening its name would reach the new one. | |
| 371 | 1 | def self.live?(component) |
| 372 | 12144 | (name = component.name) && Object.const_get(name).equal?(component) |
| 373 | rescue NameError | |
| 374 | 385 | false |
| 375 | end | |
| 376 | ||
| 377 | 1 | def self.phlex_ancestors(component) |
| 378 | 756 | component.ancestors.take_while { |ancestor| ancestor != Phlex::SGML }.select { |ancestor| Class === ancestor } |
| 379 | end | |
| 380 | ||
| 381 | 1 | def self.loaded_components |
| 382 | 10852 | descendants_of(Phlex::SGML).select { |component| live?(component) } |
| 383 | end | |
| 384 | ||
| 385 | # Class#subclasses is called directly, so a class overriding it can't hide | |
| 386 | # or invent descendants. | |
| 387 | 1 | SUBCLASSES = Class.instance_method(:subclasses) |
| 388 | ||
| 389 | 1 | def self.descendants_of(component) |
| 390 | 27894 | SUBCLASSES.bind_call(component).flat_map { |subclass| [subclass, *descendants_of(subclass)] } |
| 391 | end | |
| 392 | ||
| 393 | # The lines in the file that define the components' live methods. A method | |
| 394 | # that's already compiled is traced back through its generation's map, and | |
| 395 | # is a target again only when recompiling. An alias has the source location | |
| 396 | # of the method it copied, and a method made by `attr_reader` or | |
| 397 | # `define_method` has none of a `def`'s source to compile, so neither is a | |
| 398 | # target. | |
| 399 | 1 | def self.targets(path, components, recompile: false) |
| 400 | 133 | components.each_with_object({}) do |component, targets| |
| 401 | 1169 | next if component.frozen? || !live?(component) |
| 402 | ||
| 403 | 1167 | own_methods(component).each do |name| |
| 404 | 1745 | method = component.instance_method(name) |
| 405 | 1745 | next unless method.original_name == name && (location = method.source_location) |
| 406 | ||
| 407 | 1740 | source_path, line = location |
| 408 | ||
| 409 | 1740 | if (generation = Phlex.__compiled_source_maps__[source_path]) |
| 410 | 891 | next unless generation.path == path && (line = generation.lines[line]) |
| 411 | ||
| 412 | 23 | targets[line] = Target.new(component:, name:, line:, compiled: !recompile, replaced: true) |
| 413 | 849 | elsif source_path == path && defined_by_def?(method) |
| 414 | 195 | targets[line] = Target.new(component:, name:, line:, compiled: false, replaced: false) |
| 415 | end | |
| 416 | end | |
| 417 | end | |
| 418 | end | |
| 419 | ||
| 420 | # Whether the method was made by `def`. Only CRuby can tell: a method from | |
| 421 | # `attr_reader` has no instruction sequence, and one from `define_method` | |
| 422 | # has a block's. Anything else, or any method elsewhere, is assumed to be, | |
| 423 | # so a change in how Ruby labels them makes a `def` that an `attr_reader` | |
| 424 | # or `define_method` replaced refused, rather than stopping compilation. | |
| 425 | 1 | def self.defined_by_def?(method) |
| 426 | 200 | return true unless defined?(RubyVM::InstructionSequence)then never taken |
| 427 | ||
| 428 | 200 | iseq = RubyVM::InstructionSequence.of(method) |
| 429 | 200 | !iseq.nil? && !iseq.label.start_with?("block ") |
| 430 | end | |
| 431 | ||
| 432 | # Module's own method listings, called directly so a class overriding them | |
| 433 | # can't change what the compiler sees. | |
| 434 | 4 | METHOD_LISTS = [:instance_methods, :private_instance_methods, :protected_instance_methods].map { |list| Module.instance_method(list) }.freeze |
| 435 | ||
| 436 | # The aliases, in the component or a descendant, that share a body with | |
| 437 | # the component's method, as [owner, name] pairs. A descendant isn't being | |
| 438 | # compiled, so it's reflected on without calling its own methods, which it | |
| 439 | # may have overridden. A copy made by `define_method` shares the body too | |
| 440 | # but isn't equal to the method, so they're matched by source location. | |
| 441 | 1 | def self.aliases_sharing(component, name) |
| 442 | 3 | method = Phlex::UNBOUND_INSTANCE_METHOD_METHOD.bind_call(component, name) |
| 443 | ||
| 444 | 3 | [component, *descendants_of(component)].flat_map do |owner| |
| 445 | 16 | names = METHOD_LISTS.flat_map { |list| list.bind_call(owner, false) } |
| 446 | ||
| 447 | 4 | names.filter_map do |alias_name| |
| 448 | 11 | next if alias_name == name |
| 449 | ||
| 450 | 8 | candidate = Phlex::UNBOUND_INSTANCE_METHOD_METHOD.bind_call(owner, alias_name) |
| 451 | 8 | [owner, alias_name] if candidate.original_name == name && candidate.source_location == method.source_location |
| 452 | end | |
| 453 | end | |
| 454 | end | |
| 455 | ||
| 456 | # The methods the component defines itself. `initialize` runs before the | |
| 457 | # component has any state to render into. | |
| 458 | 1 | def self.own_methods(component) |
| 459 | 1266 | names = component.instance_methods(false) + component.private_instance_methods(false) + component.protected_instance_methods(false) - [:initialize] |
| 460 | 3215 | names.reject { |name| revisibilised?(component, name) } |
| 461 | end | |
| 462 | ||
| 463 | # Changing the visibility of an inherited method lists it on the component, | |
| 464 | # with the component as its owner, but its source is still the ancestor's. | |
| 465 | 1 | def self.revisibilised?(component, name) |
| 466 | 1949 | location = component.instance_method(name).source_location |
| 467 | ||
| 468 | 1949 | component.ancestors.any? do |ancestor| |
| 469 | 20963 | next false if ancestor.equal?(component) |
| 470 | ||
| 471 | 19014 | defined = ancestor.method_defined?(name, false) || ancestor.private_method_defined?(name, false) || ancestor.protected_method_defined?(name, false) |
| 472 | 19014 | defined && ancestor.instance_method(name).source_location == location |
| 473 | end | |
| 474 | end | |
| 475 | ||
| 476 | 1 | def self.defining_files(component) |
| 477 | 99 | paths = own_methods(component).filter_map do |name| |
| 478 | 173 | source_path = component.instance_method(name).source_location&.firstreceiver never nil |
| 479 | 173 | Phlex.__compiled_source_maps__[source_path]&.path || source_path |
| 480 | end | |
| 481 | 99 | paths << constant_source_path(component) |
| 482 | 204 | paths.compact.uniq.select { |path| File.exist?(path) } |
| 483 | end | |
| 484 | ||
| 485 | # The file the class was first defined in, unless its name no longer | |
| 486 | # resolves to it, as after a code reload. | |
| 487 | 1 | def self.constant_source_path(component) |
| 488 | 100 | return unless live?(component) |
| 489 | ||
| 490 | 99 | Object.const_source_location(component.name)&.firstreceiver never nil |
| 491 | end | |
| 492 | ||
| 493 | 1 | def self.component!(component) |
| 494 | 65 | unless Class === component && Phlex::SGML > component |
| 495 | 0 | raise ArgumentError, "Expected a Phlex::SGML subclass, got #{component.inspect}."then never taken |
| 496 | end | |
| 497 | end | |
| 498 | ||
| 499 | 1 | def self.parse(source, path) |
| 500 | 139 | Refract::Converter.new.visit(Prism.parse(source, filepath: path).value) |
| 501 | end | |
| 502 | ||
| 503 | # Replacing a method is the whole point, so the warning for it is noise. | |
| 504 | 1 | def self.without_redefinition_warnings |
| 505 | 94 | verbose = $VERBOSE |
| 506 | 94 | $VERBOSE = nil |
| 507 | 94 | yield |
| 508 | ensure | |
| 509 | 94 | $VERBOSE = verbose |
| 510 | end | |
| 511 | ||
| 512 | 1 | BYTE_ORDER_MARK = "\xEF\xBB\xBF".b.freeze |
| 513 | ||
| 514 | # Ruby drops a byte order mark before reading the encoding comment, but | |
| 515 | # Prism reads the mark as the encoding and ignores the comment. | |
| 516 | 1 | def self.without_byte_order_mark(source) |
| 517 | 121 | source.b.start_with?(BYTE_ORDER_MARK) ? source.byteslice((BYTE_ORDER_MARK.bytesize)..) : source |
| 518 | end | |
| 519 | ||
| 520 | # The generated source is always prefixed with exactly one line so the | |
| 521 | # line arithmetic stays the same whatever the file's magic comments are. | |
| 522 | # Emacs-style syntax lets the encoding and frozen string literal comments | |
| 523 | # share that line, which is the only place Ruby reads an encoding from. | |
| 524 | 1 | def self.magic_comments(parse_result) |
| 525 | 94 | comments = ["coding: #{parse_result.encoding.name}"] |
| 526 | 94 | frozen_string_literal = frozen_string_literal(parse_result) |
| 527 | 94 | comments << "frozen_string_literal: #{frozen_string_literal}" unless frozen_string_literal.nil? |
| 528 | 94 | "# -*- #{comments.join('; ')} -*-\n" |
| 529 | end | |
| 530 | ||
| 531 | # Ruby only reads a frozen string literal comment from the comment block | |
| 532 | # before the first token, with the last valid one there winning. An | |
| 533 | # explicit false is forwarded too, since it isn't the same as no comment: | |
| 534 | # it overrides `--enable-frozen-string-literal` and unchills the strings. | |
| 535 | 1 | def self.frozen_string_literal(parse_result) |
| 536 | 94 | first_token = first_token_offset(parse_result) |
| 537 | ||
| 538 | 94 | comment = parse_result.magic_comments.reverse_each.find do |magic_comment| |
| 539 | 88 | magic_comment.key_loc.start_offset < first_token && |
| 540 | magic_comment.key.tr("-", "_").casecmp?("frozen_string_literal") && | |
| 541 | 83 | (magic_comment.value.casecmp?("true") || magic_comment.value.casecmp?("false")) |
| 542 | end | |
| 543 | ||
| 544 | 94 | comment&.value&.casecmp?("true") |
| 545 | end | |
| 546 | ||
| 547 | # The AST can't tell us where the first token is because it leaves out | |
| 548 | # tokens such as a lone semicolon, so the lexer's tokens are read instead. | |
| 549 | 1 | def self.first_token_offset(parse_result) |
| 550 | 94 | Prism.lex(parse_result.source.source).value.each do |token, _state| |
| 551 | 213 | next if token.type in :COMMENT | :NEWLINE | :IGNORED_NEWLINE | :EMBDOC_BEGIN | :EMBDOC_LINE | :EMBDOC_END |
| 552 | ||
| 553 | 94 | return token.location.start_offset |
| 554 | end | |
| 555 | ||
| 556 | 0 | raise Phlex::Compiler::Error, "Prism lexed #{parse_result.source.source.bytesize} bytes without an end of file token" |
| 557 | end | |
| 558 | ||
| 559 | 1 | def self.wrap_in_namespace(namespace, body) |
| 560 | 230 | namespace.reverse_each.reduce(Refract::StatementsNode.new(body:)) do |inner, scope| |
| 561 | 374 | wrapped = Refract::StatementsNode.new(body: [inner]) |
| 562 | ||
| 563 | 374 | case scopeelse never taken |
| 564 | 230 | in Refract::ClassNode then scope.copy(body: wrapped, superclass: nil) |
| 565 | 144 | in Refract::ModuleNode then scope.copy(body: wrapped) |
| 566 | end | |
| 567 | end | |
| 568 | end | |
| 569 | ||
| 570 | 1 | module LazyCompilation |
| 571 | 1 | def internal_call(...) |
| 572 | 295 | Phlex::Compiler.compile_on_first_render(self.class) if Phlex::Compiler.enabled? |
| 573 | ||
| 574 | 295 | super |
| 575 | end | |
| 576 | end | |
| 577 | end |