repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/server.rb
lib/opal/cli_runners/server.rb
# frozen_string_literal: true require 'opal/simple_server' module Opal module CliRunners class Server def self.call(data) runner = new(data) runner.run runner.exit_status end def initialize(data) options = data[:options] || {} @builder = data[:builder] @argv = data[:argv] || [] @output = data[:output] || $stdout @port = options.fetch(:port, ENV['OPAL_CLI_RUNNERS_SERVER_PORT'] || 3000).to_i @static_folder = options[:static_folder] || ENV['OPAL_CLI_RUNNERS_SERVER_STATIC_FOLDER'] @static_folder = @static_folder == true ? 'public' : @static_folder @static_folder = File.expand_path(@static_folder) if @static_folder end attr_reader :output, :port, :server, :static_folder, :builder, :argv def run unless argv.empty? raise ArgumentError, 'Program arguments are not supported on the Server runner' end require 'rack' require 'logger' app = build_app(builder) @server = Rack::Server.start( app: app, Port: port, AccessLog: [], Logger: Logger.new(output), ) end def exit_status nil end def build_app(builder) app = Opal::SimpleServer.new(builder: builder, main: 'cli-runner') if static_folder not_found = [404, {}, []] app = Rack::Cascade.new( [ Rack::Static.new(->(_) { not_found }, urls: [''], root: static_folder), app ], ) end app end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/deno.rb
lib/opal/cli_runners/deno.rb
# frozen_string_literal: true require 'shellwords' require 'opal/paths' require 'opal/cli_runners/system_runner' require 'opal/os' module Opal module CliRunners class Deno def self.call(data) argv = data[:argv].dup.to_a SystemRunner.call(data) do |tempfile| opts = Shellwords.shellwords(ENV['DENO_OPTS'] || '') [ 'deno', 'run', '--allow-read', '--allow-write', *opts, tempfile.path, *argv ] end rescue Errno::ENOENT raise MissingDeno, 'Please install Deno to be able to run Opal scripts.' end class MissingDeno < RunnerError end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cli_runners/gjs.rb
lib/opal/cli_runners/gjs.rb
# frozen_string_literal: true require 'opal/paths' require 'opal/cli_runners/system_runner' require 'shellwords' module Opal module CliRunners # Gjs is GNOME's JavaScript runtime based on Mozilla SpiderMonkey class Gjs def self.call(data) exe = ENV['GJS_PATH'] || 'gjs' builder = data[:builder].call opts = Shellwords.shellwords(ENV['GJS_OPTS'] || '') opts.unshift('-m') if builder.esm? SystemRunner.call(data.merge(builder: -> { builder })) do |tempfile| [exe, *opts, tempfile.path, *data[:argv]] end rescue Errno::ENOENT raise MissingGjs, 'Please install Gjs to be able to run Opal scripts.' end class MissingGjs < RunnerError end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/builder/directory.rb
lib/opal/builder/directory.rb
# frozen_string_literal: true module Opal class Builder # This module is included into Builder, provides abstracted data about a new # paradigm of compiling Opal applications into a directory. module Directory def version_prefix "opal/#{Opal::VERSION_MAJOR_MINOR}" end def source_prefix 'opal/src' end # Output method #compile_to_directory depends on a directory compiler # option being set, so that imports are generated correctly. def compile_to_directory(dir = nil, single_file: nil, with_source_map: true) raise ArgumentError, 'no directory provided' if dir.nil? && single_file.nil? catch(:file) do index = [] postprocessed.each do |file| module_name = Compiler.module_name(file.filename) last_segment_name = File.basename(module_name) depth = module_name.split('/').length - 1 file_name = Pathname(file.filename).cleanpath.to_s index << module_name if file.options[:load] || !file.options[:requirable] compiled_filename = "#{version_prefix}/#{module_name}.#{output_extension}" try_building_single_file(dir, compiled_filename, single_file) do compiled_source = file.to_s compiled_source += "\n//# sourceMappingURL=./#{last_segment_name}.map" if with_source_map compiled_source end if with_source_map source_map_filename = "#{version_prefix}/#{module_name}.map" try_building_single_file(dir, source_map_filename, single_file) do # Correct the map to point to source files and remove embedded source source_map = file.source_map.to_h.dup source_map[:sourceRoot] = "./#{'../' * depth}../../#{source_prefix}" source_map[:sources] = [file_name] source_map.delete(:sourcesContent) source_map.to_json end source_filename = "#{source_prefix}/#{file_name}" try_building_single_file(dir, source_filename, single_file) do file.original_source end end end compile_index(dir, index: index, single_file: single_file) end end private # Generates executable index files def compile_index(dir = nil, index:, single_file: nil) index = index.map { |i| "./#{version_prefix}/#{i}.#{output_extension}" } if !esm? try_building_single_file(dir, 'index.js', single_file) do index.map { |i| "require(#{i.to_json});" }.join("\n") + "\n" end else try_building_single_file(dir, 'index.mjs', single_file) do index.map { |i| "import #{i.to_json};" }.join("\n") + "\n" end try_building_single_file(dir, 'index.html', single_file) do <<~HTML <!doctype html> <html> <head> <meta charset='utf-8'> <title>Opal application</title> </head> <body> #{index.map { |i| "<script type='module' src='#{i}'></script>" }.join("\n ")} </body> </html> HTML end end end # A helper method to either generate a single file or write a file to # a specified location. def try_building_single_file(dir, file, single_file, &_block) if !single_file FileUtils.mkdir_p(File.dirname("#{dir}/#{file}")) File.binwrite("#{dir}/#{file}", yield) elsif single_file == file throw :file, yield end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/builder/processor.rb
lib/opal/builder/processor.rb
# frozen_string_literal: true require 'opal/compiler' require 'opal/erb' require 'erb' module Opal class Builder class Processor def initialize(source, filename, abs_path = nil, options = {}) options = abs_path if abs_path.is_a? Hash source += "\n" unless source.end_with?("\n") @source, @filename, @abs_path, @options = source, filename, abs_path, options.dup @cache = @options.delete(:cache) { Opal.cache } @requires = [] @required_trees = [] @autoloads = [] end attr_reader :source, :filename, :options, :requires, :required_trees, :autoloads, :abs_path alias original_source source def to_s source.to_s end class << self attr_reader :extensions def handles(*extensions) @extensions = extensions matches = extensions.join('|') matches = "(#{matches})" unless extensions.size == 1 @match_regexp = Regexp.new "\\.#{matches}#{REGEXP_END}" ::Opal::Builder.register_processor(self, extensions) nil end def match?(other) other.is_a?(String) && other.match(match_regexp) end def match_regexp @match_regexp || raise(NotImplementedError) end end def mark_as_required(filename) "Opal.loaded([#{filename.to_s.inspect}]);" end class JsProcessor < Processor handles :js, :mjs ManualFragment = Struct.new(:line, :column, :code, :source_map_name) def source_map @source_map ||= begin manual_fragments = source.each_line.with_index.map do |line_source, index| column = line_source.index(/\S/) line = index + 1 ManualFragment.new(line, column, line_source, nil) end ::Opal::SourceMap::File.new(manual_fragments, filename, source) end end def source @source.to_s + mark_as_required(@filename) end end class RubyProcessor < Processor handles :rb, :opal def source compiled.result end def source_map compiled.source_map end def compiled @compiled ||= Opal::Cache.fetch(@cache, cache_key) do compiler = compiler_for(@source, file: @filename) compiler.compile compiler end end def cache_key [self.class, @filename, @source, @options] end def compiler_for(source, options = {}) ::Opal::Compiler.new(source, @options.merge(options)) end def requires compiled.requires end def required_trees compiled.required_trees end def autoloads compiled.autoloads end # Also catch a files with missing extensions and nil. def self.match?(other) super || File.extname(other.to_s) == '' end end # This handler is for files named ".opalerb", which ought to # first get compiled to Ruby code using ERB, then with Opal. # Unlike below processors, OpalERBProcessor can be used to # compile templates, which will in turn output HTML. Take # a look at docs/templates.md to understand this subsystem # better. class OpalERBProcessor < RubyProcessor handles :opalerb def initialize(*args) super @source = prepare(@source, @filename) end def requires ['erb'] + super end private def prepare(source, path) ::Opal::ERB::Compiler.new(source, path).prepared_source end end # This handler is for files named ".rb.erb", which ought to # first get preprocessed via ERB, then via Opal. class RubyERBProcessor < RubyProcessor handles :"rb.erb" def compiled @compiled ||= begin erb = ::ERB.new(@source.to_s) erb.filename = @abs_path @source = erb.result compiler = compiler_for(@source, file: @filename) compiler.compile compiler end end end # This handler is for files named ".js.erb", which ought to # first get preprocessed via ERB, then served verbatim as JS. class ERBProcessor < Processor handles :erb def source erb = ::ERB.new(@source.to_s) erb.filename = @abs_path result = erb.result module_name = ::Opal::Compiler.module_name(@filename) "Opal.modules[#{module_name.inspect}] = function() {#{result}};" end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/builder/scheduler.rb
lib/opal/builder/scheduler.rb
# frozen_string_literal: true require 'opal/os' unless RUBY_ENGINE == 'opal' module Opal class Builder class Scheduler def initialize(builder) @builder = builder end attr_accessor :builder # Prefork is not deterministic. This module corrects an order of processed # files so that it would be exactly the same as if building sequentially. # While for Ruby files it usually isn't a problem, because the real order # stems from how `Opal.modules` array is accessed, the JavaScript files # are executed verbatim and their order may be important. Also, having # deterministic output is always a good thing. module OrderCorrector module_function def correct_order(processed, requires, builder) # Let's build a hash that maps a filename to an array of files it requires requires_hash = processed.to_h do |i| [i.filename, expand_requires(i.requires, builder)] end # Let's build an array with a correct order of requires order_array = build_require_order_array(expand_requires(requires, builder), requires_hash) # If a key is duplicated, remove the last duplicate order_array = order_array.uniq # Create a hash from this array: [a,b,c] => [a => 0, b => 1, c => 2] order_hash = order_array.each_with_index.to_h # Let's return a processed array that has elements in the order provided processed.sort_by do |asset| # If a filename isn't present somehow in our hash, let's put it at the end order_hash[asset.filename] || order_array.length end end # Expand a requires array, so that the requires filenames will be # matching Builder::Processor#. Builder needs to be passed so that # we can access an `expand_ext` function from its context. def expand_requires(requires, builder) requires.map { |i| builder.expand_ext(i) } end def build_require_order_array(requires, requires_hash, built_for = Set.new) array = [] requires.each do |name| next if built_for.include?(name) built_for << name asset_requires = requires_hash[name] array += build_require_order_array(asset_requires, requires_hash, built_for) if asset_requires array << name end array end end end end singleton_class.attr_accessor :builder_scheduler if RUBY_ENGINE == 'opal' require 'opal/builder/scheduler/sequential' Opal.builder_scheduler = Builder::Scheduler::Sequential elsif RUBY_ENGINE == 'ruby' # Windows has a faulty `fork`. if OS.windows? || ENV['OPAL_PREFORK_DISABLE'] require 'opal/builder/scheduler/sequential' Opal.builder_scheduler = Builder::Scheduler::Sequential else require 'opal/builder/scheduler/prefork' Opal.builder_scheduler = Builder::Scheduler::Prefork end elsif RUBY_ENGINE == 'truffleruby' require 'opal/builder/scheduler/threaded' Opal.builder_scheduler = Builder::Scheduler::Threaded elsif RUBY_ENGINE == 'jruby' require 'opal/builder/scheduler/threaded' Opal.builder_scheduler = Builder::Scheduler::Threaded else require 'opal/builder/scheduler/sequential' Opal.builder_scheduler = Builder::Scheduler::Sequential end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/builder/post_processor.rb
lib/opal/builder/post_processor.rb
# frozen_string_literal: true module Opal class Builder class PostProcessor @postprocessors = [] def self.register(klass) @postprocessors << klass end def self.call(processed, builder) @postprocessors.each do |postprocessor| processed = postprocessor.new(processed, builder).call end processed end def self.postprocessing_enabled?(builder) @postprocessors.any? do |postprocessor| postprocessor.enabled?(builder) end end # For spec use def self.with_postprocessors(postprocessors) prev_postprocessors = @postprocessors @postprocessors = Array(postprocessors) result = yield @postprocessors = prev_postprocessors result end # If any postprocessor is enabled, we need to cache fragments # and source. def self.enabled?(_builder) true end def initialize(processed, builder) @processed = processed @builder = builder end attr_reader :processed, :builder # descendants override def call processed end class Directive attr_accessor :name, :params def initialize(name, **params) @name = name @params = params end # Unhandled post-processor directive def code '' end end module NodeSupport def post_processor_directive(name, **kwargs) Directive.new(name, **kwargs) end end end end end require 'opal/builder/post_processor/dce'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/builder/scheduler/threaded.rb
lib/opal/builder/scheduler/threaded.rb
# frozen_string_literal: true module Opal class Builder class Scheduler class Threaded < Scheduler def initialize(builder) super(builder) @threads = [] @threads_mutex = Thread::Mutex.new init_thread_args end # We hook into the process_requires method def process_requires(rel_path, requires, autoloads, options) return if requires.empty? first_run = threaded_reactor(rel_path, requires, autoloads, options) if first_run processed = OrderCorrector.correct_order(@thread_args[:processed], requires, builder) builder.processed.append(*processed) init_thread_args end end private def init_thread_args @thread_args = { queue: [], queue_mutex: Thread::Mutex.new, processed: [], processed_req: {}, processed_mutex: Thread::Mutex.new, } end # By default we use 3/4 of CPU threads detected. def thread_count ENV['OPAL_PREFORK_THREADS']&.to_i || ((n = Etc.nprocessors) > 8 ? (n * 3 / 4.0).ceil : n) end def create_thread(execution) Thread.new(@thread_args, execution, builder) do |args, exe, builder| shall_skip = false while exe[:continue] todo = nil args[:queue_mutex].synchronize do todo = args[:queue].shift exe[:busy] += 1 if todo end unless todo sleep 0.01 # to keep things simple and prevent busy looping next end rel_path, req, autoloads, options = *todo begin args[:processed_mutex].synchronize do shall_skip = builder.already_processed.include?(req) builder.already_processed << req unless shall_skip end next if shall_skip asset = builder.process_require_threadsafely(req, autoloads, options) if asset args[:processed_mutex].synchronize { args[:processed] << asset } end rescue Builder::MissingRequire => error args[:queue_mutex].synchronize do exe[:continue] = false exe[:busy] = 0 args[:exception] = Builder::MissingRequire.new "A file required by #{rel_path.inspect} wasn't found.\n#{error.message}", error.backtrace end rescue => error args[:queue_mutex].synchronize do exe[:continue] = false exe[:busy] = 0 args[:exception] = error end ensure args[:queue_mutex].synchronize do exe[:busy] -= 1 exe[:continue] = false if args[:queue].empty? && exe[:busy] <= 0 end end end end end def run_threads execution = { continue: true, busy: 0 } @threads_mutex.synchronize do thread_count.times do @threads << create_thread(execution) end end @threads.each(&:join) @threads_mutex.synchronize { @threads.clear } exception = @thread_args[:exception] raise exception if exception end def threaded_reactor(rel_path, requires, autoloads, options) first_run = @threads_mutex.synchronize { @threads.empty? } @thread_args[:queue_mutex].synchronize do requires.each do |req| @thread_args[:queue] << [rel_path, req, autoloads, options] end end run_threads if first_run first_run end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/builder/scheduler/sequential.rb
lib/opal/builder/scheduler/sequential.rb
# frozen_string_literal: true module Opal class Builder class Scheduler class Sequential < Scheduler def process_requires(rel_path, requires, autoloads, options) requires.map { |r| builder.process_require(r, autoloads, options) } rescue Builder::MissingRequire => error raise error, "A file required by #{rel_path.inspect} wasn't found.\n#{error.message}", error.backtrace end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/builder/scheduler/prefork.rb
lib/opal/builder/scheduler/prefork.rb
# frozen_string_literal: true require 'etc' require 'set' module Opal class Builder class Scheduler class Prefork < Scheduler # We hook into the process_requires method def process_requires(rel_path, requires, autoloads, options) return if requires.empty? if @in_fork io = @in_fork io.send(:new_requires, rel_path, requires, autoloads, options) else processed = prefork_reactor(rel_path, requires, autoloads, options) processed = OrderCorrector.correct_order(processed, requires, builder) builder.processed.append(*processed) end end private class ForkSet < Array def initialize(count, &block) super([]) @count, @block = count, block create_fork end def get_events(queue_length) # Wait for anything to happen: # - Either any of our workers return some data # - Or any workers become ready to receive data # - But only if we have enough work for them ios = IO.select( map(&:read_io), sample(queue_length).map(&:write_io), [] ) return [[], []] unless ios events = ios[0].map do |io| io = from_io(io, :read_io) [io, *io.recv] end idles = ios[1].map do |io| from_io(io, :write_io) end # Progressively create forks, because we may not need all # the workers at the time. The number 6 was picked due to # some trial and error on a Ryzen machine. # # Do note that prefork may happen more than once. create_fork if length < @count && rand(6) == 1 [events, idles] end def create_fork self << Fork.new(self, &@block) end def from_io(io, type) find { |i| i.__send__(type) == io } end def close each(&:close) end def wait each(&:wait) end end class Fork def initialize(forkset) @parent_read, @child_write = IO.pipe(binmode: true) @child_read, @parent_write = IO.pipe(binmode: true) @forkset = forkset @in_fork = false @pid = fork do @in_fork = true begin @parent_read.close @parent_write.close yield(self) rescue => error send(:exception, error) ensure send(:close) unless write_io.closed? @child_write.close end end @child_read.close @child_write.close end def close send(:close) @parent_write.close end def goodbye read_io.close unless read_io.closed? end def send_message(io, msg) msg = Marshal.dump(msg) io.write([msg.length].pack('Q') + msg) end def recv_message(io) length, = *io.read(8).unpack('Q') Marshal.load(io.read(length)) # rubocop:disable Security/MarshalLoad end def fork? @in_fork end def read_io fork? ? @child_read : @parent_read end def write_io fork? ? @child_write : @parent_write end def eof? write_io.closed? end def send(*msg) send_message(write_io, msg) end def recv recv_message(read_io) end def wait Process.waitpid(@pid, Process::WNOHANG) end end # By default we use 3/4 of CPU threads detected. def fork_count ENV['OPAL_PREFORK_THREADS']&.to_i || (Etc.nprocessors * 3 / 4.0).ceil end def prefork @forks = ForkSet.new(fork_count, &method(:fork_entrypoint)) end def fork_entrypoint(io) # Ensure we can work with our forks async... Fiber.set_scheduler(nil) if Fiber.respond_to? :set_scheduler @in_fork = io until io.eof? $0 = 'opal/builder: idle' type, *args = *io.recv case type when :compile rel_path, req, autoloads, options = *args $0 = "opal/builder: #{req}" begin asset = builder.process_require_threadsafely(req, autoloads, options) io.send(:new_asset, asset) rescue Builder::MissingRequire => error io.send(:missing_require_exception, rel_path, error) end when :close io.goodbye break end end rescue Errno::EPIPE exit! end def prefork_reactor(rel_path, requires, autoloads, options) prefork processed = [] first = rel_path queue = requires.map { |i| [rel_path, i, autoloads, options] } awaiting = 0 built = 0 should_log = $stderr.tty? && !ENV['OPAL_DISABLE_PREFORK_LOGS'] $stderr.print "\r\e[K" if should_log loop do events, idles = @forks.get_events(queue.length) idles.each do |io| break if queue.empty? rel_path, req, autoloads, options = *queue.shift next if builder.already_processed.include?(req) awaiting += 1 builder.already_processed << req io.send(:compile, rel_path, req, autoloads, options) end events.each do |io, type, *args| case type when :new_requires rel_path, requires, autoloads, options = *args requires.each do |i| queue << [rel_path, i, autoloads, options] end when :new_asset asset, = *args if !asset # Do nothing, we received a nil which is expected. else processed << asset end built += 1 awaiting -= 1 when :missing_require_exception rel_path, error = *args raise error, "A file required by #{rel_path.inspect} wasn't found.\n#{error.message}", error.backtrace when :exception error, = *args raise error when :close io.goodbye end end if should_log percent = (100.0 * built / (awaiting + built)).round(1) str = format("[opal/builder] Building %<first>s... (%<percent>4.3g%%)\r", first: first, percent: percent) $stderr.print str end break if awaiting == 0 && queue.empty? end processed ensure $stderr.print "\r\e[K\r" if should_log @forks.close @forks.wait end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/builder/post_processor/dce.rb
lib/opal/builder/post_processor/dce.rb
# frozen_string_literal: true require 'opal/builder/post_processor/dce/call_tree' module Opal class Builder class PostProcessor class DCE < PostProcessor def self.enabled?(builder) builder.dce? end def initialize(_, _) super reset end def reset @call_tree = CallTree.new @sct = nil end def dce_status(message, idx = nil, len = nil) if $stderr.tty? if message == :finished $stderr.print "\r\e[K\r" else if idx && len message = "(#{(100.0 * idx / len).round(1)}%) " + message end $stderr.print "\r\e[K[opal/dce] #{message}\r" end end end def call # Return if DCE is not enabled. return processed unless DCE.enabled? builder process end def process len = processed.length # First, process what we have generated processed.each_with_index do |file, idx| dce_status "Processing #{file.filename}...", idx, len if file.respond_to? :compiled read_ruby(file.compiled) else read_js(file.source) end end # Then, do processing of the data we got dce_status 'Computing...' process_data # Finally, rebuild Ruby files processed.each_with_index do |file, idx| dce_status "Rebuilding #{file.filename}...", idx, len if file.respond_to? :compiled rebuild_ruby(file.compiled) end end dce_status :finished processed end OPERATOR_RE = Regexp.union( %i[ ** << >> <= >= <=> === == != =~ !~ +@ -@ []= [] ! + - * / % & | ^ ~ < > ].map(&:to_s) ) # FIXME: Regexp issues with Opal METHOD_NAME_RE = if RUBY_ENGINE == 'opal' / (?: [[A-Za-z]_][[A-Za-z0-9]_]* (?:[!?=])? | #{OPERATOR_RE} ) /x else / (?: [[:alpha:]_][[:alnum:]_]* (?:[!?=])? | #{OPERATOR_RE} ) /x end # Identifiers defined on Opal, eg. Opal.def OPAL_IDENT_RE = /[a-zA-Z_][a-zA-Z0-9_]*/ # This is needed for runtime. But we could strip some of those # and move more into `dce_use` and friends helper calls. METHOD_CALL_RE = / \.\$(#{METHOD_NAME_RE}) | \['\$(#{METHOD_NAME_RE})'\] | \["\$(#{METHOD_NAME_RE})"\] | (?<!typeof\s)Opal\.(#{OPAL_IDENT_RE}) | (?<![\w$.]|function\s)\$(#{OPAL_IDENT_RE}) /x def dce_directive?(frag) frag.is_a?(Directive) && %i[dce_def_begin dce_def_end dce_use].include?(frag.name) && (builder.dce + [:*]).include?(frag.params[:type]) end def extract_names_from(str) str.scan(METHOD_CALL_RE).map(&:compact).map(&:first).map(&:to_sym) end def read_js(str) @call_tree.add_calls(extract_names_from(str)) end def read_ruby(compiler) stack = [] compiler.fragments.each do |frag| if dce_directive?(frag) case frag.name when :dce_def_begin stack << frag.params[:name] @call_tree.add_definitions(stack) when :dce_use @call_tree.add_calls(frag.params[:name], frag.params[:force] ? [] : stack) when :dce_def_end stack.pop end elsif !ignore_incoming?(frag) @call_tree.add_calls(extract_names_from(frag.code), stack) end end end # Apply some heuristics to skip regexp matching for certain # parts of the code. def ignore_incoming?(frag) if frag.respond_to?(:sexp) && frag.sexp case frag.sexp.type when :xstr, :str, :jscall # :top, :def, :defs false else true end else true end end # Dynamic calls for opal-parser. Those functions shouldn't # happen in typical code you want to DCE, but if your code # needs parser, this is required. def add_dynamic_calls begin [:_reduce_none, :_racc_do_parse_rb, /\A_reduce_\d+\z/, :Symbol, :Number] end.then { |i| @call_tree.add_calls(i) } end def process_data add_dynamic_calls @sct = ShadowedCallTree.new(@call_tree) @sct.process end ScopeIdent = Struct.new(:name, :handled, :placeholder) def readd_directive(new_fragments, frag, stack) new_fragments << frag if keep_definition?(stack) end def rebuild_ruby(compiler) new_fragments = [] stack = [] compiler.fragments.each do |frag| if dce_directive?(frag) case frag.name when :dce_def_begin stack << ScopeIdent.new( frag.params[:name], false, frag.params[:placeholder] ) readd_directive(new_fragments, frag, stack) when :dce_def_end readd_directive(new_fragments, frag, stack) stack.pop else readd_directive(new_fragments, frag, stack) end elsif keep_definition?(stack) new_fragments << frag elsif stack.none?(&:handled) func = stack.last new_fragments << Opal::Fragment.new( "#{func.placeholder}/* Removed by DCE: #{func.name} */", frag.scope, frag.sexp ) func.handled = true end end compiler.fragments = new_fragments end def keep_definition?(stack) stack.empty? || stack.all? do |idents| Array(idents.name).any? do |ident| @sct.keep_definition?(ident) end end end module NodeSupport def dce_def_begin(name, placeholder: nil, type: :method) placeholder ||= 'nil' placeholder += ' ' unless placeholder == '' post_processor_directive( :dce_def_begin, name: name, placeholder: placeholder, type: type ) end def dce_def_end(name, type: :method) post_processor_directive(:dce_def_end, name: name, type: type) end def dce_use(name, type: :method, force: false) post_processor_directive(:dce_use, name: name, type: type, force: force) end end end register DCE end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/builder/post_processor/dce/call_tree.rb
lib/opal/builder/post_processor/dce/call_tree.rb
# frozen_string_literal: true # rubocop:disable Style/CaseEquality module Opal class Builder class PostProcessor class DCE < PostProcessor # CallTree records a tree of definitions and calls, like # so: # # (root): # - definitions: # - CallTree: # calls: attr_accessor # definitions: # - initialize # calls: Set, new # # After collecting, this structure is later used by # ShadowingCallTree to calculate which parts of the # code can be safely stripped. class CallTree attr_accessor :definitions, :calls def initialize(loc = :"") @loc = loc @definitions = {} @calls = Set.new end def dig(*path) if path.empty? [self] else first, *rest = *path Array(first).flat_map do |leaf| self[leaf].dig(*rest) end end end def add_calls(calls, path = []) if path.empty? @calls += Array(calls) else dig(*path).each do |leaf| leaf.add_calls(calls) end end end def add_definitions(path = []) *rest, last = *path if rest.empty? Array(last).each do |leaf| @definitions[leaf] ||= CallTree.new(:"#{@loc}/#{leaf}") end else dig(*rest).each do |leaf| leaf.add_definitions([last]) end end end def [](child) @definitions[child] end end # Hides access to parts of the structure that is meant # to be stripped, so that multiple passes of DCE can be # performed, but only on the unstripped parts. # # This class also contains the logic class ShadowedCallTree def initialize(call_tree) @shadowed = Set.new @call_tree = call_tree end def shadow(items) @shadowed += Array(items) end def shadowed?(key) @shadowed.include?(key) end def in_temporary_shadowing_context old_shadowed = @shadowed ret = yield @shadowed = old_shadowed ret end def inspect(call_tree = @call_tree, indent = 1, shadowed = false) indent_str = ' ' * indent newline = "\n" calls_str = call_tree.calls.map(&:inspect).join(', ') calls_str + newline + call_tree.definitions.map do |k, v| is_shadowed = shadowed || shadowed?(k) inspect_str = inspect(v, indent + 1, is_shadowed) shadowed_str = is_shadowed ? '[S] ' : '[ ] ' indent_str + shadowed_str + k.to_s + ': ' + inspect_str end.join end def dfs(call_tree = @call_tree, key = nil, &block) yield(call_tree, key) call_tree.definitions.each do |subkey, value| next if shadowed? subkey dfs(value, subkey, &block) end end def all_definitions defs = Set.new dfs { |_, key| defs << key } defs end def all_calls calls = Set.new dfs { |node, _| calls += node.calls } calls end def calls_by_key by_key = Hash.new { |a, b| a[b] = [] } dfs { |node, key| by_key[key] << node } by_key.transform_values do |value| value.map(&:calls).sum(Set.new) end end def all_calls_from_root by_key = calls_by_key final_calls = Set.new calls = by_key[nil].to_a while (call = calls.pop) next if final_calls.include?(call) final_calls << call calls += by_key[call].to_a end final_calls end def unused_definitions definitions = all_definitions used_calls = all_calls_from_root matcher_calls = used_calls.reject { |i| i.is_a?(Symbol) } definitions -= used_calls definitions.reject do |definition| matcher_calls.any? { |matcher| matcher === definition } end.to_set end def all_constant_definitions all_definitions.select { |key| key.to_s.match?(/\A[A-Z]/) } end # While undoubtedly very useful, Complex and Rational # can be stripped safely together. def enhanced_all_constant_definitions all_constant_definitions + [%i[Complex Rational]] end # An approach that allows us to strip a module if there's # no external usage of its constants by temporarily # shadowing each one, checking for any calls referencing it, # and then permanently shadowing (removing) it when it is # confirmed to be unused. def try_shadowing_constants enhanced_all_constant_definitions.each do |key| in_temporary_shadowing_context do shadow key shadow unused_definitions (all_calls & Array(key)).empty? end and shadow key end end def definition_count all_definitions.length end def process def_count = definition_count # Run steps repeatedly until there's nothing left to # remove. loop do shadow unused_definitions try_shadowing_constants old_def_count, def_count = def_count, definition_count break if def_count == old_def_count end @kept_definitions = all_definitions end def keep_definition?(name) @kept_definitions.include?(name) end end end end end end # rubocop:enable Style/CaseEquality
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/cache/file_cache.rb
lib/opal/cache/file_cache.rb
# frozen_string_literal: true require 'fileutils' require 'zlib' module Opal module Cache class FileCache def initialize(dir: nil, max_size: nil) @dir = dir || self.class.find_dir # Store at most 32MB of cache - de facto this 32MB is larger, # as we don't account for inode size for instance. In fact, it's # about 50M. Also we run this check before anything runs, so things # may go up to 64M or even larger. @max_size = max_size || 32 * 1024 * 1024 tidy_up_cache end def set(key, data) file = cache_filename_for(key) out = Marshal.dump(data) # Sometimes `Zlib::BufError` gets raised, unsure why, makes no sense, possibly # some race condition (see https://github.com/ruby/zlib/issues/49). # Limit the number of retries to avoid infinite loops. retries = 5 begin out = Zlib.gzip(out, level: 9) rescue Zlib::BufError warn "\n[Opal]: Zlib::BufError; retrying (#{retries} retries left)" retries -= 1 retry if retries > 0 end File.binwrite(file, out) end def get(key) file = cache_filename_for(key) if File.exist?(file) FileUtils.touch(file) out = File.binread(file) out = Zlib.gunzip(out) Marshal.load(out) # rubocop:disable Security/MarshalLoad end rescue Zlib::GzipFile::Error nil end # Remove cache entries that overflow our cache limit... and which # were used least recently. private def tidy_up_cache entries = Dir[@dir + '/*.rbm.gz'] entries_stats = entries.map { |entry| [entry, File.stat(entry)] } size_sum = entries_stats.map { |_entry, stat| stat.size }.sum return unless size_sum > @max_size # First, we try to get the oldest files first. # Then, what's more important, is that we try to get the least # recently used files first. Filesystems with relatime or noatime # will get this wrong, but it doesn't matter that much, because # the previous sort got things "maybe right". entries_stats = entries_stats.sort_by { |_entry, stat| [stat.mtime, stat.atime] } entries_stats.each do |entry, stat| size_sum -= stat.size File.unlink(entry) # We don't need to work this out anymore - we reached our goal. break unless size_sum > @max_size end rescue Errno::ENOENT # Do nothing, this comes from multithreading. We will tidy up at # the next chance. nil end # Check if we can robustly mkdir_p a directory. def self.dir_writable?(*paths) return false unless File.exist?(paths.first) until paths.empty? dir = File.expand_path(paths.shift, dir) ok = File.directory?(dir) && File.writable?(dir) if File.exist?(dir) end dir if ok end def self.find_dir @find_dir ||= case # Try to write cache into a directory pointed by an environment variable if present when dir = ENV['OPAL_CACHE_DIR'] FileUtils.mkdir_p(dir) dir # Otherwise, we write to the place where Opal is installed... # I don't think it's a good location to store cache, so many things can go wrong. # when dir = dir_writable?(Opal.gem_dir, '..', 'tmp', 'cache') # FileUtils.mkdir_p(dir) # FileUtils.chmod(0o700, dir) # dir # Otherwise, ~/.cache/opal... when dir = dir_writable?(Dir.home, '.cache', 'opal') FileUtils.mkdir_p(dir) FileUtils.chmod(0o700, dir) dir # Only /tmp is writable... or isn't it? when (dir = dir_writable?('/tmp', "opal-cache-#{ENV['USER']}")) && File.sticky?('/tmp') FileUtils.mkdir_p(dir) FileUtils.chmod(0o700, dir) dir # No way... we can't write anywhere... else warn "Couldn't find a writable path to store Opal cache. " \ 'Try setting OPAL_CACHE_DIR environment variable' nil end end private def cache_filename_for(key) "#{@dir}/#{key}.rbm.gz" end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/masgn.rb
lib/opal/nodes/masgn.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes class MassAssignNode < Base SIMPLE_ASSIGNMENT = %i[lvasgn ivasgn lvar gvasgn cdecl casgn].freeze handle :masgn children :lhs, :rhs def compile with_temp do |array| if rhs.type == :array push "#{array} = ", expr(rhs) rhs_len = rhs.children.any? { |c| c.type == :splat } ? nil : rhs.children.size compile_masgn(lhs.children, array, rhs_len) push ", #{array}" # a mass assignment evaluates to the RHS else helper :to_ary with_temp do |retval| push "#{retval} = ", expr(rhs) push ", #{array} = $to_ary(#{retval})" compile_masgn(lhs.children, array) push ", #{retval}" end end end end # 'len' is how many rhs items are we sure we have def compile_masgn(lhs_items, array, len = nil) pre_splat = lhs_items.take_while { |child| child.type != :splat } post_splat = lhs_items.drop(pre_splat.size) pre_splat.each_with_index do |child, idx| compile_assignment(child, array, idx, len) end unless post_splat.empty? splat = post_splat.shift if post_splat.empty? # trailing splat if part = splat.children[0] helper :slice part = part.dup << s(:js_tmp, "$slice(#{array}, #{pre_splat.size})") push ', ' push expr(part) end else tmp = scope.new_temp # end index for items consumed by splat push ", #{tmp} = #{array}.length - #{post_splat.size}" push ", #{tmp} = (#{tmp} < #{pre_splat.size}) ? #{pre_splat.size} : #{tmp}" if part = splat.children[0] helper :slice part = part.dup << s(:js_tmp, "$slice(#{array}, #{pre_splat.size}, #{tmp})") push ', ' push expr(part) end post_splat.each_with_index do |child, idx| if idx == 0 compile_assignment(child, array, tmp) else compile_assignment(child, array, "#{tmp} + #{idx}") end end scope.queue_temp(tmp) end end end def compile_assignment(child, array, idx, len = nil) assign = if !len || idx >= len s(:js_tmp, "(#{array}[#{idx}] == null ? nil : #{array}[#{idx}])") else s(:js_tmp, "#{array}[#{idx}]") end part = child.updated if SIMPLE_ASSIGNMENT.include?(child.type) part = part.updated(nil, part.children + [assign]) elsif child.type == :send part = part.updated(nil, part.children + [assign]) elsif child.type == :attrasgn part.last << assign elsif child.type == :mlhs helper :to_ary # nested destructuring tmp = scope.new_temp push ", (#{tmp} = $to_ary(#{assign.children[0]})" compile_masgn(child.children, tmp) push ')' scope.queue_temp(tmp) return else raise "Bad child node in masgn LHS: #{child}. LHS: #{lhs}" end push ', ' push expr(part) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/singleton_class.rb
lib/opal/nodes/singleton_class.rb
# frozen_string_literal: true require 'opal/nodes/scope' module Opal module Nodes class SingletonClassNode < ScopeNode handle :sclass children :object, :body def compile push '(function(self, $parent_nesting) {' in_scope do body_stmt = stmt(compiler.returns(body)) add_temp '$nesting = [self].concat($parent_nesting)' if @define_nesting add_temp '$$ = Opal.$r($nesting)' if @define_relative_access line scope.to_vars line body_stmt end helper :get_singleton_class line '})($get_singleton_class(', recv(object), "), #{scope.nesting})" end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/node_with_args.rb
lib/opal/nodes/node_with_args.rb
# frozen_string_literal: true require 'opal/nodes/scope' require 'opal/nodes/args/parameters' require 'opal/nodes/node_with_args/shortcuts' module Opal module Nodes class NodeWithArgs < ScopeNode attr_reader :used_kwargs attr_accessor :arity attr_reader :original_args def initialize(*) super @original_args = @sexp.meta[:original_args] @used_kwargs = [] @arity = 0 end def arity_check_node s(:arity_check, original_args) end # Returns code used in debug mode to check arity of method call def compile_arity_check push process(arity_check_node) end def compile_block_arg if scope.uses_block? scope.prepare_block end end def parameters_code Args::Parameters.new(original_args).to_code end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/while.rb
lib/opal/nodes/while.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes class WhileNode < Base handle :while children :test, :body def compile test_code = js_truthy(test) @redo_var = scope.new_temp if uses_redo? compiler.in_while do while_loop[:closure] = true if wrap_in_closure? while_loop[:redo_var] = @redo_var has_retry = node_has?(body, :retry) in_closure( Closure::LOOP | Closure::JS_LOOP | (wrap_in_closure? ? Closure::JS_FUNCTION : 0) | (has_retry ? Closure::RETRY_CONTAINER : 0) ) do in_closure(Closure::LOOP_INSIDE | Closure::JS_LOOP_INSIDE | (has_retry ? Closure::RETRY_CONTAINER : 0)) do line(indent { stmt(body) }) end if uses_redo? compile_with_redo(test_code) else compile_without_redo(test_code) end end end scope.queue_temp(@redo_var) if uses_redo? if wrap_in_closure? if scope.await_encountered wrap '(await (async function() {', '; return nil; })())' else wrap '(function() {', '; return nil; })()' end end end private def compile_with_redo(test_code) compile_while(test_code, "#{@redo_var} = false;") end def compile_without_redo(test_code) compile_while(test_code) end def compile_while(test_code, redo_code = nil) unshift redo_code if redo_code unshift while_open, test_code, while_close unshift redo_code if redo_code line '}' end def while_open if uses_redo? redo_part = "#{@redo_var} || " end "while (#{redo_part}" end def while_close ') {' end def uses_redo? @sexp.meta[:has_redo] end def wrap_in_closure? expr? || recv? end end class UntilNode < WhileNode handle :until private def while_open if uses_redo? redo_part = "#{@redo_var} || " end "while (#{redo_part}!(" end def while_close ')) {' end end class WhilePostNode < WhileNode handle :while_post private def compile_while(test_code, redo_code = nil) unshift redo_code if redo_code unshift "do {" line "} ", while_open, test_code, while_close end def while_close ');' end end class UntilPostNode < WhilePostNode handle :until_post private def while_open if uses_redo? redo_part = "#{@redo_var} || " end "while (#{redo_part}!(" end def while_close '));' end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/top.rb
lib/opal/nodes/top.rb
# frozen_string_literal: true require 'pathname' require 'json' require 'opal/version' require 'opal/nodes/scope' module Opal module Nodes # Generates code for an entire file, i.e. the base sexp class TopNode < ScopeNode handle :top children :body def compile compiler.top_scope = self compiler.dynamic_cache_result = true if sexp.meta[:dynamic_cache_result] push version_comment helper :return_val if compiler.eof_content if body == s(:nil) # A shortpath for empty (stub?) modules. if compiler.requirable? || compiler.esm? || compiler.eval? unshift 'Opal.return_val(Opal.nil); ' definition else unshift 'Opal.nil; ' end else in_scope do line '"use strict";' if compiler.use_strict? body_code = in_closure(Closure::JS_FUNCTION | Closure::TOP) do stmt(stmts) end body_code = [body_code] unless body_code.is_a?(Array) if compiler.eval? add_temp '$nesting = self.$$is_a_module ? [self] : [self.$$class]' if @define_nesting else add_temp 'self = Opal.top' if @define_self add_temp '$nesting = []' if @define_nesting end add_temp '$$ = Opal.$r($nesting)' if @define_relative_access add_temp 'nil = Opal.nil' add_temp '$$$ = Opal.$$$' if @define_absolute_const add_used_helpers line scope.to_vars compile_method_stubs compile_irb_vars compile_end_construct line body_code end opening definition closing end add_file_source_embed if compiler.enable_file_source_embed? end def module_name Opal::Compiler.module_name(compiler.file) end def definition if compiler.requirable? unshift "Opal.modules[#{module_name.inspect}] = " elsif compiler.esm? && !compiler.no_export? && !compiler.directory? unshift 'export default ' end if compiler.directory? imports end end def opening async_prefix = "async " if await_encountered if compiler.requirable? unshift "#{async_prefix}function(Opal) {" elsif compiler.eval? || compiler.irb? unshift "(#{async_prefix}function(Opal, self) {" else unshift "Opal.queue(#{async_prefix}function(Opal) {" end end def closing if compiler.requirable? line "};\n" if compiler.load? # Opal.load normalizes the path, so that we can't # require absolute paths from CLI. For other cases # we can expect the module names to be normalized # already. line "Opal.queue(()=>{ Opal.load_normalized(#{module_name.inspect}) });" elsif compiler.runtime_mode? line "Opal.load_normalized(#{module_name.inspect});" end elsif compiler.eval? || compiler.irb? line "})(Opal, self);" else line "});\n" end end # Generate import/require statements def imports imports = compiler.requires unshift "\n" unless imports.empty? # Check how many directories we have to go up depth = module_name.delete_prefix('./').count("/") imports.reverse_each do |req| ref = depth == 0 ? "./" : ("../" * depth) mod = "#{ref}#{Compiler.module_name(req)}.#{compiler.esm? ? 'mjs' : 'js'}" if compiler.esm? unshift "import #{mod.inspect};\n" else unshift "require(#{mod.inspect});\n" end end end def stmts compiler.returns(body) end # Returns '$$$', but also ensures that the '$$$' variable is set def absolute_const @define_absolute_const = true '$$$' end def compile_irb_vars if compiler.irb? line 'if (!Opal.irb_vars) { Opal.irb_vars = {}; }' end end def add_used_helpers compiler.helpers.to_a.reverse_each do |h| prepend_scope_temp "$#{h} = Opal.#{h}" end end def compile_method_stubs if compiler.method_missing? calls = compiler.method_calls stubs = calls.to_a.map(&:to_s).join(',') line "Opal.add_stubs('#{stubs}');" unless stubs.empty? end end # Any special __END__ content in code def compile_end_construct if content = compiler.eof_content line 'var $__END__ = Opal.Object.$new();' line "$__END__.$read = $return_val(#{content.inspect});" end end def version_comment "/* Generated by Opal #{Opal::VERSION} */" end def add_file_source_embed filename = compiler.file source = compiler.source unshift "Opal.file_sources[#{filename.to_json}] = #{source.to_json};\n" end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/literal.rb
lib/opal/nodes/literal.rb
# frozen_string_literal: true require 'opal/nodes/base' require 'opal/regexp_transpiler' module Opal module Nodes class ValueNode < Base handle :true, :false, :nil def compile push type.to_s end def self.truthy_optimize? true end end class SelfNode < Base handle :self def compile push scope.self end end class NumericNode < Base handle :int, :float children :value def compile push value.to_s wrap '(', ')' if recv? end def self.truthy_optimize? true end end class StringNode < Base handle :str children :value ESCAPE_CHARS = { 'a' => '\\u0007', 'e' => '\\u001b' }.freeze ESCAPE_REGEX = /(\\+)([#{ ESCAPE_CHARS.keys.join('') }])/.freeze def translate_escape_chars(inspect_string) inspect_string.gsub(ESCAPE_REGEX) do |original| if Regexp.last_match(1).length.even? original else Regexp.last_match(1).chop + ESCAPE_CHARS[Regexp.last_match(2)] end end end def compile string_value = value sanitized_value = sanitize_utf16(string_value) push translate_escape_chars(sanitized_value) if RUBY_ENGINE != 'opal' encoding = string_value.encoding unless encoding == Encoding::UTF_8 helper :str wrap "$str(", ",\"#{encoding.name}\")" end end unless value.valid_encoding? helper :str wrap "$str(", ",\"BINARY\")" end end def sanitize_utf16(string_value) string_value.inspect.gsub(/\\u\{([0-9a-f]+)\}/) do code_point = Regexp.last_match(1).to_i(16) if code_point <= 0xFFFF '\\u' + code_point.to_s(16).upcase else Regexp.last_match(0) end end end end class SymbolNode < Base handle :sym children :value def compile push value.to_s.inspect end end class RegexpNode < Base handle :regexp attr_accessor :value, :flags # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp SUPPORTED_FLAGS = /[gimuy]/.freeze def initialize(*) super extract_flags_and_value end def compile flags.select! do |flag| if SUPPORTED_FLAGS =~ flag true else compiler.warning "Skipping the '#{flag}' Regexp flag as it's not widely supported by JavaScript vendors.", @sexp.line false end end if value.type == :str compile_static_regexp else compile_dynamic_regexp end end def compile_dynamic_regexp helper :regexp push '$regexp([' value.children.each_with_index do |v, index| push ', ' unless index.zero? push expr(v) end push ']' push ", '#{flags.join}'" if flags.any? push ")" end include Opal::RegexpTranspiler def compile_static_regexp value = self.value.children[0] case value when '' helper :empty_regexp push("$empty_regexp(#{flags.join.inspect})") when /\(\?[(<>#]|[*+?]\+|\\G/ # Safari/WebKit will not execute javascript code if it contains a lookbehind literal RegExp # and they fail with "Syntax Error". This tricks their parser by disguising the literal RegExp # as string for the dynamic $regexp helper. Safari/Webkit will still fail to execute the RegExp, # but at least they will parse and run everything else. # # Also, let's compile a couple of more patterns into $regexp calls, as there are many syntax # errors in RubySpec when ran in reverse, while there shouldn't be (they should be catchable # errors) - at least since Node 17. static_as_dynamic(value) else regexp_content = Regexp.new(value).inspect regexp_content = regexp_content[1...regexp_content.rindex('/')] old_flags = flags.join new_regexp, new_flags = transform_regexp(regexp_content, old_flags) push "/#{new_regexp}/#{new_flags}" # Annotate the source regexp and flags, so it can be used to redo transforming while doing # unions etc. if regexp_content != new_regexp || old_flags != new_flags helper :annotate_regexp wrap '$annotate_regexp(', ", #{regexp_content != new_regexp ? regexp_content.inspect : 'null'}" \ "#{old_flags != new_flags ? ", #{old_flags.inspect}" : ''})" end end end def static_as_dynamic(value) helper :regexp push '$regexp(["' push value.gsub('\\', '\\\\\\\\').gsub('"', '\"') push '"]' push ", '#{flags.join}'" if flags.any? push ")" end def extract_flags_and_value *values, flags_sexp = *children self.flags = flags_sexp.children.map(&:to_s) self.value = if values.empty? # empty regexp, we can process it inline s(:str, '') elsif single_line?(values) # simple plain regexp, we can put it inline values[0] else s(:dstr, *values) end # trimming when //x provided # required by parser gem, but JS doesn't support 'x' flag if flags.include?('x') parts = value.children.map do |part| if part.is_a?(::Opal::AST::Node) && part.type == :str trimmed_value = part.children[0] .gsub(/\A\s*\#.*/, '') .gsub(/\s/, '') s(:str, trimmed_value) else part end end self.value = value.updated(nil, parts) flags.delete('x') end end def raw_value self.value = @sexp.loc.expression.source end private def single_line?(values) return false if values.length > 1 value = values[0] # JavaScript doesn't support multiline regexp value.type != :str || !value.children[0].include?("\n") end end # $_ = 'foo'; call if /foo/ # s(:if, s(:match_current_line, /foo/, true)) class MatchCurrentLineNode < Base handle :match_current_line children :regexp # Here we just convert it to # ($_ =~ regexp) # and let :send node to handle it def compile gvar_sexp = s(:gvar, :$_) send_node = s(:send, gvar_sexp, :=~, regexp) push expr(send_node) end end class DynamicStringNode < Base handle :dstr def compile if children.empty? push '""' else helper :dstr helper :to_s last_index = children.size - 1 push '$dstr(' children.each_with_index do |part, index| push '$to_s(' unless part.type == :str push expr(part) push ')' unless part.type == :str push ',' unless index == last_index end push ')' wrap '(', ')' if recv? end end end class DynamicSymbolNode < DynamicStringNode handle :dsym end class RangeNode < Base children :start, :finish SIMPLE_CHILDREN_TYPES = %i[int float str sym].freeze def compile if compile_inline? helper :range compile_inline else compile_range_initialize end end def compile_inline? ( !start || (start.type && SIMPLE_CHILDREN_TYPES.include?(start.type)) ) && ( !finish || (finish.type && SIMPLE_CHILDREN_TYPES.include?(finish.type)) ) end def compile_inline raise NotImplementedError end def compile_range_initialize raise NotImplementedError end end class InclusiveRangeNode < RangeNode handle :irange def compile_inline push '$range(', expr_or_nil(start), ', ', expr_or_nil(finish), ', false)' end def compile_range_initialize push 'Opal.Range.$new(', expr_or_nil(start), ', ', expr_or_nil(finish), ', false)' end end class ExclusiveRangeNode < RangeNode handle :erange def compile_inline push '$range(', expr_or_nil(start), ', ', expr_or_nil(finish), ', true)' end def compile_range_initialize push 'Opal.Range.$new(', expr_or_nil(start), ',', expr_or_nil(finish), ', true)' end end # 0b1111r -> s(:rational, (15/1)) # -0b1111r -> s(:rational, (-15/1)) class RationalNode < Base handle :rational children :value def compile push "#{top_scope.absolute_const}('Rational').$new(#{value.numerator}, #{value.denominator})" end end # 0b1110i -> s(:complex, (0+14i)) # -0b1110i -> s(:complex, (0-14i)) class ComplexNode < Base handle :complex children :value def compile push "#{top_scope.absolute_const}('Complex').$new(#{value.real}, #{value.imag})" end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/variables.rb
lib/opal/nodes/variables.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes class LocalVariableNode < Base handle :lvar children :var_name def using_irb? compiler.irb? && scope.top? end def compile return push(var_name.to_s) unless using_irb? with_temp do |tmp| push property(var_name.to_s) wrap "((#{tmp} = Opal.irb_vars", ") == null ? nil : #{tmp})" end end end class LocalAssignNode < Base handle :lvasgn children :var_name, :value def using_irb? compiler.irb? && scope.top? end def compile if using_irb? push "Opal.irb_vars#{property var_name.to_s} = " else add_local var_name.to_s push "#{var_name} = " end push expr(value) wrap '(', ')' if (recv? || expr?) && value end end class LocalDeclareNode < Base handle :lvdeclare children :var_name def compile add_local(var_name.to_s) nil end end class InstanceVariableNode < Base handle :ivar children :name def var_name name.to_s[1..-1] end def compile name = property(var_name) add_ivar name push "#{scope.self}#{name}" end end class InstanceAssignNode < Base handle :ivasgn children :name, :value def var_name name.to_s[1..-1] end def compile name = property(var_name) push "#{scope.self}#{name} = " push expr(value) wrap '(', ')' if (recv? || expr?) && value end end class GlobalVariableNode < Base handle :gvar children :name def var_name name.to_s[1..-1] end def compile helper :gvars name = property var_name add_gvar name push "$gvars#{name}" end end # back_ref can be: # $` # $' # $& # $+ (currently unsupported) class BackRefNode < GlobalVariableNode handle :back_ref def compile helper :gvars case var_name when '&' handle_global_match when "'" handle_post_match when '`' handle_pre_match when '+' super else raise NotImplementedError end end def handle_global_match with_temp do |tmp| push "((#{tmp} = $gvars['~']) === nil ? nil : #{tmp}['$[]'](0))" end end def handle_pre_match with_temp do |tmp| push "((#{tmp} = $gvars['~']) === nil ? nil : #{tmp}.$pre_match())" end end def handle_post_match with_temp do |tmp| push "((#{tmp} = $gvars['~']) === nil ? nil : #{tmp}.$post_match())" end end end class GlobalAssignNode < Base handle :gvasgn children :name, :value def var_name name.to_s[1..-1] end def compile helper :gvars name = property var_name push "$gvars#{name} = " push expr(value) wrap '(', ')' if (recv? || expr?) && value end end # $1 => s(:nth_ref, 1) class NthrefNode < Base handle :nth_ref children :index def compile helper :gvars with_temp do |tmp| push "((#{tmp} = $gvars['~']) === nil ? nil : #{tmp}['$[]'](#{index}))" end end end class ClassVariableNode < Base handle :cvar children :name def compile helper :class_variable_get tolerant = false # We should be tolerant of expressions like: def x; @@notexist; 0; end # (NB: Shouldn't we actually optimize them out?) tolerant = true if stmt? # We should be tolerant of expressions like: @@notexist ||= 6 # (those are handled with logical_operator_assignment) push "$class_variable_get(#{class_variable_owner}, '#{name}', #{tolerant.inspect})" end end class ClassVarAssignNode < Base handle :cvasgn children :name, :value def compile helper :class_variable_set push "$class_variable_set(#{class_variable_owner}, '#{name}', ", expr(value), ')' end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/array.rb
lib/opal/nodes/array.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes class ArrayNode < Base handle :array def compile return push('[]') if children.empty? code, work = [], [] children.each do |child| splat = child.type == :splat part = expr(child) if splat if work.empty? if code.empty? code << fragment('[].concat(') << part << fragment(')') else code << fragment('.concat(') << part << fragment(')') end else if code.empty? code << fragment('[') << work << fragment(']') else code << fragment('.concat([') << work << fragment('])') end code << fragment('.concat(') << part << fragment(')') end work = [] else work << fragment(', ') unless work.empty? work << part end end unless work.empty? join = [fragment('['), work, fragment(']')] if code.empty? code = join else code.push([fragment('.concat('), join, fragment(')')]) end end push code end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/def.rb
lib/opal/nodes/def.rb
# frozen_string_literal: true require 'opal/nodes/node_with_args' module Opal module Nodes class DefNode < NodeWithArgs handle :def children :mid, :inline_args, :stmts def compile compile_body_or_shortcut blockopts = {} blockopts["$$arity"] = arity if arity < 0 if compiler.arity_check? blockopts["$$parameters"] = parameters_code end if compiler.parse_comments? blockopts["$$comments"] = comments_code end if compiler.enable_source_location? blockopts["$$source_location"] = source_location end if blockopts.keys == ["$$arity"] push ", #{arity}" elsif !blockopts.empty? push ', {', blockopts.map { |k, v| "#{k}: #{v}" }.join(', '), '}' end wrap_with_definition wrap_with_postprocessor_directives scope.nesting if @define_nesting scope.relative_access if @define_relative_access end def compile_body inline_params = nil scope_name = nil in_scope do scope.mid = mid scope.defs = true if @sexp.type == :defs scope.identify! scope_name = scope.identity # Setting a default block name (later can be overwritten by a blockarg) scope.block_name = '$yield' inline_params = process(inline_args) in_closure(Closure::DEF | Closure::JS_FUNCTION) do stmt_code = stmt(compiler.returns(stmts)) compile_block_arg add_temp 'self = this' if @define_self compile_arity_check unshift "\n#{current_indent}", scope.to_vars line stmt_code end end unshift ') {' unshift(inline_params) unshift "function #{scope_name}(" if await_encountered unshift "async " end line '}' end def wrap_with_definition helper :def wrap "$def(#{scope.self}, '$#{mid}', ", ')' unshift "\n#{current_indent}" unless expr? end def wrap_with_postprocessor_directives unshift dce_def_begin(mid) push dce_def_end(mid) end def comments_code '[' + comments.map { |comment| comment.text.inspect }.join(', ') + ']' end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/constants.rb
lib/opal/nodes/constants.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes class ConstNode < Base handle :const children :const_scope, :name def compile push dce_use(name, type: :const) if magical_data_const? push('$__END__') elsif optimized_access? helper :"#{name}" push "$#{name}" elsif const_scope == s(:cbase) && name == :Opal push "Opal" elsif const_scope == s(:cbase) push "#{top_scope.absolute_const}('#{name}')" elsif const_scope push "#{top_scope.absolute_const}(", recv(const_scope), ", '#{name}')" elsif compiler.eval? push "#{scope.relative_access}('#{name}')" else push "#{scope.relative_access}('#{name}')" end end # Ruby has a magical const DATA # that should be processed in a different way: # 1. When current file contains __END__ in the end of the file # DATA const should be resolved to the string located after __END__ # 2. When current file doesn't have __END__ section # DATA const should be resolved to a regular ::DATA constant def magical_data_const? const_scope.nil? && name == :DATA && compiler.eof_content end OPTIMIZED_ACCESS_CONSTS = %i[ BasicObject Object Module Class Kernel NilClass ].freeze # For a certain case of calls like `::Opal.coerce_to?` we can # optimize the calls. We can be sure they are defined from the # beginning. def optimized_access? const_scope == s(:cbase) && OPTIMIZED_ACCESS_CONSTS.include?(name) end end # ::CONST # s(:const, s(:cbase), :CONST) class CbaseNode < Base handle :cbase def compile push "'::'" end end class ConstAssignNode < Base handle :casgn children :base, :name, :value def compile helper :const_set # Constant definitions like: Separator = SEPARATOR = "/" # can be unwittingly removed. push dce_def_begin(name, type: :const) unless value.type == :casgn if base push '$const_set(', expr(base), ", '#{name}', ", expr(value), ')' else push "$const_set(#{scope.nesting}[0], '#{name}', ", expr(value), ')' end push dce_def_end(name, type: :const) unless value.type == :casgn end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/x_string.rb
lib/opal/nodes/x_string.rb
# frozen_string_literal: true module Opal module Nodes class XStringNode < Base handle :xstr def compile if compiler.backtick_javascript_or_warn? compile_javascript else compile_send end end def compile_send sexp = s(:send, nil, :`, s(:dstr, *children)) push process(sexp, @level) end def compile_javascript @should_add_semicolon = false unpacked_children = unpack_return(children) stripped_children = XStringNode.strip_empty_children(unpacked_children) if XStringNode.single_line?(stripped_children) # If it's a single line we'll try to: # # - strip empty lines # - remove a trailing `;` # - detect an embedded `return` # - prepend a `return` when needed # - append a `;` when needed # - warn the user not to use the semicolon in single-line x-strings compile_single_line(stripped_children) else # Here we leave to the user the responsibility to add # a return where it's due. unpacked_children.each { |c| compile_child(c) } end wrap '(', ')' if recv? push ';' if @should_add_semicolon end # Check if there's only one child or if they're all part of # the same line (e.g. because of interpolations) def self.single_line?(children) (children.size == 1) || children.none? do |c| c.type == :str && c.loc.expression.source.end_with?("\n") end end # Will remove empty :str lines coming from cosmetic newlines in x-strings # # @example # # this will generate two additional empty # # children before and after `foo()` # %x{ # foo() # } def self.strip_empty_children(children) children = children.dup empty_line = ->(child) { child.nil? || (child.type == :str && child.loc.expression.source.rstrip.empty?) } children.shift while children.any? && empty_line[children.first] children.pop while children.any? && empty_line[children.last] children end private def compile_child(child) case child.type when :str value = child.loc.expression.source scope.self if value.include? 'self' push Fragment.new(value, scope, child) when :begin, :gvar, :ivar, :nil push expr(child) else raise "Unsupported xstr part: #{child.type}" end end def compile_single_line(children) has_embeded_return = false first_child = children.shift single_child = children.empty? first_child ||= s(:nil) if first_child.type == :str first_value = first_child.loc.expression.source.strip has_embeded_return = first_value =~ /^return\b/ end push('return ') if @returning && !has_embeded_return last_child = children.pop || first_child last_value = extract_last_value(last_child) if last_child.type == :str unless single_child # assuming there's an interpolation somewhere (type != :str) @should_add_semicolon = false compile_child(first_child) children.each { |c| compile_child(c) } end if last_child.type == :str push Fragment.new(last_value, scope, last_child) else compile_child(last_child) end end # Will drop the trailing semicolon if all conditions are met def extract_last_value(last_child) last_value = last_child.loc.expression.source.rstrip scope.self if last_value.include? 'self' if (@returning || expr?) && last_value.end_with?(';') compiler.warning( 'Removed semicolon ending x-string expression, interpreted as unintentional', last_child.line, ) last_value = last_value[0..-2] end @should_add_semicolon = true if @returning last_value end # A case for manually created :js_return statement in Compiler#returns # Since we need to take original source of :str we have to use raw source # so we need to combine "return" with "raw_source" def unpack_return(children) first_child = children.first @returning = false if first_child.type == :js_return @returning = true children = first_child.children end children end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/arglist.rb
lib/opal/nodes/arglist.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes # FIXME: needs rewrite class ArglistNode < Base handle :arglist def compile code, work = [], [] children.each do |current| splat = current.type == :splat arg = expr(current) if splat if work.empty? if code.empty? code << arg else code << fragment('.concat(') << arg << fragment(')') end else if code.empty? code << fragment('[') << work << fragment(']') else code << fragment('.concat([') << work << fragment('])') end code << fragment('.concat(') << arg << fragment(')') end work = [] else work << fragment(', ') unless work.empty? work << arg end end unless work.empty? join = work if code.empty? code = join else code << fragment('.concat([') << join << fragment('])') end end push(*code) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/helpers.rb
lib/opal/nodes/helpers.rb
# frozen_string_literal: true require 'opal/regexp_anchors' module Opal module Nodes module Helpers def property(name) valid_name?(name) ? ".#{name}" : "[#{name.inspect}]" end def valid_name?(name) Opal::Rewriters::JsReservedWords.valid_name?(name) end # Converts a ruby method name into its javascript equivalent for # a method/function call. All ruby method names get prefixed with # a '$', and if the name is a valid javascript identifier, it will # have a '.' prefix (for dot-calling), otherwise it will be # wrapped in brackets to use reference notation calling. def mid_to_jsid(mid) if %r{\=|\+|\-|\*|\/|\!|\?|<|\>|\&|\||\^|\%|\~|\[|`} =~ mid.to_s "['$#{mid}']" else '.$' + mid end end def indent(&block) compiler.indent(&block) end def current_indent compiler.parser_indent end def line(*strs) push fragment("\n#{current_indent}", loc: false) push(*strs) end def empty_line push fragment("\n", loc: false) end def js_truthy(sexp) if optimize = js_truthy_optimize(sexp) return optimize end helper :truthy [fragment('$truthy('), expr(sexp), fragment(')')] end def js_truthy_optimize(sexp) case sexp.type when :send receiver, mid, *args = *sexp receiver_handler_class = receiver && compiler.handlers[receiver.type] # Only operator calls on the truthy_optimize? node classes should be optimized. # Monkey patch method calls might return 'self'/aka a bridged instance and need # the nil check - see discussion at https://github.com/opal/opal/pull/1097 allow_optimization_on_type = Compiler::COMPARE.include?(mid.to_s) && receiver_handler_class && receiver_handler_class.truthy_optimize? if allow_optimization_on_type || mid == :block_given? expr(sexp) elsif args.count == 1 case mid when :== helper :eqeq compiler.record_method_call mid [fragment('$eqeq('), expr(receiver), fragment(', '), expr(args.first), fragment(')')] when :=== helper :eqeqeq compiler.record_method_call mid [fragment('$eqeqeq('), expr(receiver), fragment(', '), expr(args.first), fragment(')')] when :!= helper :neqeq compiler.record_method_call mid [fragment('$neqeq('), expr(receiver), fragment(', '), expr(args.first), fragment(')')] end elsif args.count == 0 case mid when :! helper :not compiler.record_method_call mid [fragment('$not('), expr(receiver), fragment(')')] end end when :begin if sexp.children.count == 1 js_truthy_optimize(sexp.children.first) end when :if _test, true_body, false_body = *sexp if true_body == s(:true) # Ensure we recurse the js_truthy call on the `false_body` of the if `expr`. # This transforms an expression like: # # $truthy($truthy(a) || b) # # Into: # # $truthy(a) || $truthy(b) sexp.meta[:do_js_truthy_on_false_body] = true expr(sexp) elsif false_body == s(:false) sexp.meta[:do_js_truthy_on_true_body] = true expr(sexp) end end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/defs.rb
lib/opal/nodes/defs.rb
# frozen_string_literal: true require 'opal/nodes/def' module Opal module Nodes class DefsNode < DefNode handle :defs children :recvr, :mid, :inline_args, :stmts def wrap_with_definition if compiler.runtime_mode? unshift "Opal.$#{mid} = Opal.#{mid} = " else helper :defs unshift '$defs(', expr(recvr), ", '$#{mid}', " push ')' end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/defined.rb
lib/opal/nodes/defined.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes class DefinedNode < Base handle :defined? children :value def compile case value.type when :self, :nil, :false, :true push value.type.to_s.inspect when :lvasgn, :ivasgn, :gvasgn, :cvasgn, :casgn, :op_asgn, :or_asgn, :and_asgn push "'assignment'" when :lvar push "'local-variable'" when :begin if value.children.size == 1 && value.children[0].type == :masgn push "'assignment'" else push "'expression'" end when :send compile_defined_send(value) wrap '(', " ? 'method' : nil)" when :ivar compile_defined_ivar(value) wrap '(', " ? 'instance-variable' : nil)" when :zsuper, :super compile_defined_super when :yield compile_defined_yield wrap '(', " ? 'yield' : nil)" when :xstr compile_defined_xstr(value) when :const compile_defined_const(value) wrap '((', ") != null ? 'constant' : nil)" when :cvar compile_defined_cvar(value) wrap '(', " ? 'class variable' : nil)" when :gvar compile_defined_gvar(value) wrap '(', " ? 'global-variable' : nil)" when :back_ref compile_defined_back_ref wrap '(', " ? 'global-variable' : nil)" when :nth_ref compile_defined_nth_ref wrap '(', " ? 'global-variable' : nil)" when :array compile_defined_array(value) wrap '(', " ? 'expression' : nil)" else push "'expression'" end end def compile_defined(node) type = node.type if respond_to? "compile_defined_#{type}" __send__("compile_defined_#{type}", node) else node_tmp = scope.new_temp push "(#{node_tmp} = ", expr(node), ')' node_tmp end end def wrap_with_try_catch(code) returning_tmp = scope.new_temp helper :pop_exception helper :rescue push "(#{returning_tmp} = (function() { try {" push " return #{code};" push '} catch ($err) {' push ' if ($rescue($err, [Opal.Exception])) {' push ' try {' push ' return false;' push ' } finally { $pop_exception($err); }' push ' } else { throw $err; }' push '}})())' returning_tmp end def compile_send_recv_doesnt_raise(recv_code) wrap_with_try_catch(recv_code) end def compile_defined_send(node) recv, method_name, *args = *node mid = mid_to_jsid(method_name.to_s) if recv recv_code = compile_defined(recv) push ' && ' if recv.type == :send recv_code = compile_send_recv_doesnt_raise(recv_code) push ' && ' end recv_tmp = scope.new_temp push "(#{recv_tmp} = ", recv_code, ", #{recv_tmp}) && " else recv_tmp = scope.self end recv_value_tmp = scope.new_temp push "(#{recv_value_tmp} = #{recv_tmp}) && " meth_tmp = scope.new_temp push "(((#{meth_tmp} = #{recv_value_tmp}#{mid}) && !#{meth_tmp}.$$stub)" push " || #{recv_value_tmp}['$respond_to_missing?']('#{method_name}'))" args.each do |arg| case arg.type when :block_pass # ignoring else push ' && ' compile_defined(arg) end end wrap '(', ')' "#{meth_tmp}()" end def compile_defined_ivar(node) name = node.children[0].to_s[1..-1] # FIXME: this check should be positive for ivars initialized as nil too. # Since currently all known ivars are inialized to nil in the constructor # we can't tell if it was the user that put nil and made the ivar #defined? # or not. tmp = scope.new_temp push "(#{tmp} = #{scope.self}['#{name}'], #{tmp} != null && #{tmp} !== nil)" tmp end def compile_defined_super push expr s(:defined_super) end def compile_defined_yield scope.uses_block! block_name = scope.block_name || scope.find_parent_def.block_name push "(#{block_name} != null && #{block_name} !== nil)" block_name end def compile_defined_xstr(node) push '(typeof(', expr(node), ') !== "undefined")' end def compile_defined_const(node) const_scope, const_name = *node const_tmp = scope.new_temp if const_scope.nil? push "(#{const_tmp} = #{scope.relative_access}('#{const_name}', 'skip_raise'))" elsif const_scope == s(:cbase) push "(#{const_tmp} = #{top_scope.absolute_const}('::', '#{const_name}', 'skip_raise'))" else const_scope_tmp = compile_defined(const_scope) push " && (#{const_tmp} = #{top_scope.absolute_const}(#{const_scope_tmp}, '#{const_name}', 'skip_raise'))" end const_tmp end def compile_defined_cvar(node) cvar_name, _ = *node cvar_tmp = scope.new_temp push "(#{cvar_tmp} = #{class_variable_owner}.$$cvars['#{cvar_name}'], #{cvar_tmp} != null)" cvar_tmp end def compile_defined_gvar(node) helper :gvars name = node.children[0].to_s[1..-1] gvar_temp = scope.new_temp if %w[~ !].include? name push "(#{gvar_temp} = ", expr(node), ' || true)' else push "(#{gvar_temp} = $gvars[#{name.inspect}], #{gvar_temp} != null)" end gvar_temp end def compile_defined_back_ref helper :gvars back_ref_temp = scope.new_temp push "(#{back_ref_temp} = $gvars['~'], #{back_ref_temp} != null && #{back_ref_temp} !== nil)" back_ref_temp end def compile_defined_nth_ref helper :gvars nth_ref_tmp = scope.new_temp push "(#{nth_ref_tmp} = $gvars['~'], #{nth_ref_tmp} != null && #{nth_ref_tmp} != nil)" nth_ref_tmp end def compile_defined_array(node) node.children.each_with_index do |child, idx| push ' && ' unless idx == 0 compile_defined(child) end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/definitions.rb
lib/opal/nodes/definitions.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes class UndefNode < Base handle :undef children :value def compile helper :udef children.each do |child| push dce_def_begin(child.children.first) if child.type == :sym line "$udef(#{scope.self}, '$' + ", expr(child), ');' push dce_def_end(child.children.first) if child.type == :sym end end end class AliasNode < Base handle :alias children :new_name, :old_name def compile # We only need to check one type, because parser otherwise denies invalid expressions case new_name.type when :gvar # This is a gvar alias: alias $a $b helper :alias_gvar new_name_str = new_name.children.first.to_s[1..-1].inspect old_name_str = old_name.children.first.to_s[1..-1].inspect push '$alias_gvar(', new_name_str, ', ', old_name_str, ')' when :dsym, :sym # This is a method alias: alias a b helper :alias if old_name.type == :sym compiler.record_method_call old_name.children.last if new_name.type == :sym push dce_def_begin(new_name.children.first) end push dce_use(old_name.children.first) end push "$alias(#{scope.self}, ", expr(new_name), ', ', expr(old_name), ')' if old_name.type == :sym && new_name.type == :sym push dce_def_end(new_name.children.first) end else # Nothing else is available, but just in case, drop an error error "Opal doesn't know yet how to alias with #{new_name.type}" end end end class BeginNode < ScopeNode handle :begin def compile return push 'nil' if children.empty? if stmt? compile_children(children, @level) elsif simple_children? compile_inline_children(children, @level) wrap '(', ')' if children.size > 1 elsif children.size == 1 compile_inline_children(returned_children, @level) else in_closure do compile_children(returned_children, @level) end if scope.parent&.await_encountered wrap '(await (async function() {', '})())' else wrap '(function() {', '})()' end end end def returned_children @returned_children ||= begin *rest, last_child = *children if last_child rest + [compiler.returns(last_child)] else [s(:nil)] end end end def compile_children(children, level) children.each do |child| line process(child, level), fragment(';', loc: false) end end COMPLEX_CHILDREN = %i[while while_post until until_post js_return].freeze def simple_children? children.none? do |child| COMPLEX_CHILDREN.include?(child.type) end end def compile_inline_children(children, level) processed_children = children.map do |child| process(child, level) end processed_children.reject(&:empty?).each_with_index do |child, idx| push fragment(', ', loc: false) unless idx == 0 push child end end end class KwBeginNode < BeginNode handle :kwbegin end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/base.rb
lib/opal/nodes/base.rb
# frozen_string_literal: true require 'opal/nodes/helpers' require 'opal/nodes/closure' require 'opal/builder/post_processor' module Opal module Nodes class Base include Helpers include Closure::NodeSupport include Builder::PostProcessor::NodeSupport include Builder::PostProcessor::DCE::NodeSupport def self.handlers @handlers ||= {} end def self.handle(*types) types.each do |type| Base.handlers[type] = self end end def self.children(*names) names.each_with_index do |name, idx| define_method(name) do @sexp.children[idx] end end end def self.truthy_optimize? false end attr_reader :compiler, :type, :sexp def initialize(sexp, level, compiler) @sexp = sexp @type = sexp.type @level = level @compiler = compiler @compiler.top_scope ||= self end def children @sexp.children end def compile_to_fragments return @fragments if defined?(@fragments) @fragments = [] compile @fragments end def compile raise 'Not Implemented' end def push(*strs) strs.each do |str| str = fragment(str) if str.is_a?(String) @fragments << str end end def unshift(*strs) strs.reverse_each do |str| str = fragment(str) if str.is_a?(String) @fragments.unshift str end end def wrap(pre, post) unshift pre push post end def fragment(str, loc: true) Opal::Fragment.new str, scope, loc && @sexp end def error(msg) @compiler.error msg end def scope @compiler.scope end def top_scope @compiler.top_scope end def s(type, *children) ::Opal::AST::Node.new(type, children, location: @sexp.loc) end def expr? @level == :expr end def recv? @level == :recv end def stmt? @level == :stmt end def process(sexp, level = :expr) @compiler.process sexp, level end def expr(sexp) @compiler.process sexp, :expr end def recv(sexp) @compiler.process sexp, :recv end def stmt(sexp) @compiler.process sexp, :stmt end def expr_or_nil(sexp) sexp ? expr(sexp) : 'nil' end def expr_or_empty(sexp) sexp && sexp.type != :nil ? expr(sexp) : '' end def add_local(name) scope.add_scope_local name.to_sym end def add_ivar(name) scope.add_scope_ivar name end def add_gvar(name) scope.add_scope_gvar name end def add_temp(temp) scope.add_scope_temp temp end def helper(name) push dce_use(name, type: :*) @compiler.helper name end def with_temp(&block) @compiler.with_temp(&block) end def in_while? @compiler.in_while? end def while_loop @compiler.instance_variable_get(:@while_loop) end def has_rescue_else? scope.has_rescue_else? end def in_ensure(&block) scope.in_ensure(&block) end def in_ensure? scope.in_ensure? end def in_resbody(&block) scope.in_resbody(&block) end def in_resbody? scope.in_resbody? end def in_rescue(node, &block) scope.in_rescue(node, &block) end def class_variable_owner_nesting_level cvar_scope = scope nesting_level = 0 while cvar_scope && !cvar_scope.class_scope? # Needs only `class << self`, `module`, and `class` # can increase nesting, but `class` & `module` are # covered by `class_scope?`. nesting_level += 1 if cvar_scope.sclass? cvar_scope = cvar_scope.parent end nesting_level end def class_variable_owner if scope "#{scope.nesting}[#{class_variable_owner_nesting_level}]" else 'Opal.Object' end end def comments compiler.comments[@sexp.loc] end def source_location expr = @sexp.loc.expression if expr.respond_to? :source_buffer file = expr.source_buffer.name file = "<internal:#{file}>" if file.start_with?("corelib/") file = "<js:#{file}>" if file.end_with?(".js") else file = "(eval)" end line = @sexp.loc.line "['#{file}', #{line}]" end def node_has?(node, type) # look ahead if a child with specified type is in the tree if node node.children.each do |child| if child.is_a?(::AST::Node) || child.is_a?(::Opal::Nodes::Base) return true if child.type == type return true if node_has?(child, type) end end end false end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/yield.rb
lib/opal/nodes/yield.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes class BaseYieldNode < Base def compile_call yielding_scope = find_yielding_scope yielding_scope.uses_block! yielding_scope.block_name ||= '$yield' block_name = yielding_scope.block_name if yields_single_arg?(children) push expr(children.first) helper :yield1 wrap "$yield1(#{block_name}, ", ')' else push expr(s(:arglist, *children)) helper :yieldX if uses_splat?(children) wrap "$yieldX(#{block_name}, ", ')' else wrap "$yieldX(#{block_name}, [", '])' end end end def find_yielding_scope working = scope while working if working.block_name || working.def? break end working = working.parent end working end def yields_single_arg?(children) !uses_splat?(children) && children.size == 1 end def uses_splat?(children) children.any? { |child| child.type == :splat } end end class YieldNode < BaseYieldNode handle :yield def compile compile_call end end # Created by `#returns()` for when a yield statement should return # it's value (its last in a block etc). class ReturnableYieldNode < BaseYieldNode handle :returnable_yield def compile compile_call wrap 'return ', ';' end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/scope.rb
lib/opal/nodes/scope.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes class ScopeNode < Base # Every scope can have a parent scope attr_accessor :parent # The class or module name if this scope is a class scope attr_accessor :name # The given block name for a def scope attr_accessor :block_name attr_reader :scope_name attr_reader :locals attr_reader :ivars attr_reader :gvars attr_accessor :mid # true if singleton def, false otherwise attr_accessor :defs # used by modules to know what methods to donate to includees attr_reader :methods attr_accessor :catch_return, :has_break, :has_retry attr_accessor :rescue_else_sexp def initialize(*) super @locals = [] @temps = [] @args = [] @ivars = [] @gvars = [] @parent = nil @queue = [] @unique = 'a' @while_stack = [] @identity = nil @defs = nil @methods = [] @uses_block = false @in_ensure = false # used by classes to store all ivars used in direct def methods @proto_ivars = [] end def in_scope indent do @parent = compiler.scope compiler.scope = self yield self compiler.scope = @parent end end # Returns true if this scope is a class/module body scope def class_scope? @type == :class || @type == :module end # Returns true if this is strictly a class scope def class? @type == :class end # True if this is a module scope def module? @type == :module end def sclass? @type == :sclass end # Returns true if this is a top scope (main file body) def top? @type == :top end # True if a block/iter scope def iter? @type == :iter end def def? @type == :def || @type == :defs end def lambda? iter? && @is_lambda end # rubocop:disable Naming/PredicatePrefix def is_lambda! @is_lambda = true end # rubocop:enable Naming/PredicatePrefix def defines_lambda @lambda_definition = true yield @lambda_definition = false end def lambda_definition? @lambda_definition end # Is this a normal def method directly inside a class? This is # used for optimizing ivars as we can set them to nil in the # class body def def_in_class? !@defs && @type == :def && @parent && @parent.class? end # rubocop:disable Style/LambdaCall ## # Vars to use inside each scope def to_vars f = ->(x) { fragment(x) } vars = @temps.map do |t| if t =~ /\A\$([a-z][a-zA-Z0-9_]*) = Opal.\1\z/ helper = ::Regexp.last_match(1).to_sym end a = [] a << dce_def_begin(helper, placeholder: '') if helper a << f.(t) a << f.(', ') a << dce_def_end(helper) if helper a end vars.push(*@locals.map { |l| [f.("#{l} = nil"), f.(', ')] }) iv = ivars.map do |ivar| "if (self#{ivar} == null) self#{ivar} = nil;\n" end gv = gvars.map do |gvar| "if ($gvars#{gvar} == null) $gvars#{gvar} = nil;\n" end if class? && !@proto_ivars.empty? vars << f.('$proto = self.$$prototype') << f.(', ') end vars = vars.flatten vars.pop if vars.last && vars.last.code == ', ' indent = @compiler.parser_indent fragments = vars.empty? ? [] : [f.("var ")] + vars + [f.(";\n")] fragments << f.("#{indent}#{iv.join indent}") unless ivars.empty? fragments << f.("#{indent}#{gv.join indent}") unless gvars.empty? if class? && !@proto_ivars.empty? pvars = @proto_ivars.map { |i| "$proto#{i}" }.join(' = ') fragments << f.("\n#{indent}#{pvars} = nil;") end fragments end # rubocop:enable Style/LambdaCall def add_scope_ivar(ivar) if def_in_class? @parent.add_proto_ivar ivar else @ivars << ivar unless @ivars.include? ivar end end def add_scope_gvar(gvar) @gvars << gvar unless @gvars.include? gvar end def add_proto_ivar(ivar) @proto_ivars << ivar unless @proto_ivars.include? ivar end def add_arg(arg) @args << arg unless @args.include? arg arg end def add_scope_local(local) return if has_local? local @locals << local end def has_local?(local) return true if @locals.include?(local) || @args.include?(local) || @temps.include?(local) return @parent.has_local?(local) if @parent && @type == :iter false end def scope_locals locals = @locals | @args | (@parent && @type == :iter ? @parent.scope_locals : []) locals.reject { |i| i.to_s.start_with?('$') } end def add_scope_temp(tmp) return if has_temp?(tmp) @temps.push(tmp) end def prepend_scope_temp(tmp) return if has_temp?(tmp) @temps.unshift(tmp) end def has_temp?(tmp) @temps.include? tmp end def new_temp return @queue.pop unless @queue.empty? tmp = next_temp @temps << tmp tmp end def next_temp tmp = nil loop do tmp = "$#{@unique}" @unique = @unique.succ break unless has_local?(tmp) end tmp end def queue_temp(name) @queue << name end def push_while info = {} @while_stack.push info info end def pop_while @while_stack.pop end def in_while? !@while_stack.empty? end def uses_block! if @type == :iter && @parent @parent.uses_block! else @uses_block = true identify! end end def identify!(name = nil) return @identity if @identity if valid_name? mid # There are some special utf8 chars that can be used as valid JS # identifiers, some examples: # # utf8_pond = 'ⵌ' # utf8_question = 'ʔ̣' # utf8_exclamation 'ǃ' # # For now we're just using $$, to maintain compatibility with older IEs. @identity = "$$#{mid}" else # Parent scope is the defining module/class name ||= [parent && (parent.name || parent.scope_name), mid].compact.join('_') @identity = @compiler.unique_temp(name) end @identity end attr_reader :identity def find_parent_def scope = self while scope = scope.parent if scope.def? || scope.lambda? return scope end end nil end def super_chain chain, scope, defn, mid = [], self, 'null', 'null' while scope if scope.type == :iter chain << scope.identify! scope = scope.parent if scope.parent elsif %i[def defs].include?(scope.type) defn = scope.identify! mid = "'#{scope.mid}'" break else break end end [chain, defn, mid] end def uses_block? @uses_block end def has_rescue_else? !rescue_else_sexp.nil? end def in_rescue(node) @rescues ||= [] @rescues.push(node) result = yield @rescues.pop result end def current_rescue @rescues.last end def in_resbody return unless block_given? @in_resbody = true result = yield @in_resbody = false result end def in_resbody? @in_resbody end def in_ensure return unless block_given? @in_ensure = true result = yield @in_ensure = false result end def in_ensure? @in_ensure end def gen_retry_id @next_retry_id ||= 'retry_0' @next_retry_id = @next_retry_id.succ end def accepts_using? # IterNode of a special kind of Module.new {} is accepted... # though we don't check for it that thoroughly. [TopNode, ModuleNode, ClassNode, IterNode].include? self.class end def collect_refinements_temps(temps = []) temps << @refinements_temp if @refinements_temp return parent.collect_refinements_temps(temps) if parent temps end def new_refinements_temp var = compiler.unique_temp("$refn") add_scope_local(var) var end def refinements_temp prev, curr = @refinements_temp, new_refinements_temp @refinements_temp = curr [prev, curr] end # Returns 'self', but also ensures that the self variable is set def self @define_self = true 'self' end # Returns '$nesting', but also ensures we compile the nesting chain def nesting @define_nesting = true '$nesting' end # Returns '$$', but also ensures we compile it def relative_access @define_relative_access = @define_nesting = true '$$' end def prepare_block(block_name = nil) scope_name = scope.identity self.block_name = block_name if block_name add_temp "#{self.block_name} = #{scope_name}.$$p || nil" unless @block_prepared line "#{scope_name}.$$p = null;" @block_prepared = true end end attr_accessor :await_encountered end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/class.rb
lib/opal/nodes/class.rb
# frozen_string_literal: true require 'opal/nodes/module' module Opal module Nodes class ClassNode < ModuleNode handle :class children :cid, :sup, :body def compile name, base = name_and_base helper :klass_def if body.nil? # Empty body: rely on runtime $klass_def (no callback) to return nil unshift '$klass_def(', base, ', ', super_code, ", '#{name}')" else in_scope do scope.name = name in_closure(Closure::MODULE | Closure::JS_FUNCTION) do compile_body end end if await_encountered await_begin = '(await ' await_end = ')' async = 'async ' parent.await_encountered = true end # Emit a direct runtime call with an inline body function. unshift "#{await_begin}$klass_def(", base, ', ', super_code, ", '#{name}', #{async}function(self#{', $nesting' if @define_nesting}) {" line "}#{", #{scope.nesting}" if @define_nesting})#{await_end}" end forbid_dce_if_bridged mark_dce(name) end def super_code sup ? expr(sup) : 'null' end def bridged? sup&.type == :xstr end def forbid_dce_if_bridged push dce_use(name, type: :*, force: true) if bridged? end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/closure.rb
lib/opal/nodes/closure.rb
# frozen_string_literal: true module Opal module Nodes # This module takes care of providing information about the # closure stack that we have for the nodes during compile time. # This is not a typical node. # # Also, while loops are not closures per se, this module also # takes a note about them. # # Then we can use this information for control flow like # generating breaks, nexts, returns. class Closure NONE = 0 @types = {} def self.add_type(name, value) const_set(name, value) @types[name] = value end def self.type_inspect(type) @types.reject do |_name, value| (type & value) == 0 end.map(&:first).join("|") end add_type(:JS_FUNCTION, 1 << 0) # everything that generates an IIFE add_type(:JS_LOOP, 1 << 1) # exerything that generates a JS loop add_type(:JS_LOOP_INSIDE, 1 << 2) # everything that generates an inside of a loop add_type(:DEF, 1 << 3) # def add_type(:LAMBDA, 1 << 4) # lambda add_type(:ITER, 1 << 5) # iter, lambda add_type(:MODULE, 1 << 6) add_type(:LOOP, 1 << 7) # for building a catcher outside a loop add_type(:LOOP_INSIDE, 1 << 8) # for building a catcher inside a loop add_type(:SEND, 1 << 9) # to generate a break catcher after send with a block add_type(:TOP, 1 << 10) add_type(:RESCUE_RETRIER, 1 << 11) # a virtual loop to catch a retrier add_type(:RETRY_CONTAINER, 1 << 12) # a loop or inside loop that contains a retry ANY = 0xffffffff def initialize(node, type, parent) @node, @type, @parent = node, type, parent @catchers = [] @throwers = {} end def register_catcher(type = :return) @catchers << type unless @catchers.include? type "$t_#{type}" end def register_thrower(type, id) @throwers[type] = id end def is?(type) (@type & type) != 0 end def inspect "#<Closure #{Closure.type_inspect(type)} #{@node.class}>" end attr_accessor :node, :type, :parent, :catchers, :throwers module NodeSupport def push_closure(type = JS_FUNCTION) closure = Closure.new(self, type, select_closure) @compiler.closure_stack << closure @closure = closure end attr_accessor :closure def pop_closure compile_catcher @compiler.closure_stack.pop last = @compiler.closure_stack.last @closure = last if last&.node == self end def in_closure(type = JS_FUNCTION) closure = push_closure(type) out = yield closure pop_closure out end def select_closure(type = ANY, break_after: NONE) @compiler.closure_stack.reverse.find do |i| break if (i.type & break_after) != 0 (i.type & type) != 0 end end def generate_thrower(type, closure, value) id = closure.register_catcher(type) closure.register_thrower(type, id) push id, '.$throw(', expr_or_nil(value), ', ', scope.identify!, '.$$is_lambda)' id end def generate_thrower_without_catcher(type, closure, value) helper :thrower if closure.throwers.key? type id = closure.throwers[type] else id = compiler.unique_temp('t_') parent_scope = closure.node.scope&.parent || top_scope parent_scope.add_scope_temp("#{id} = $thrower('#{type}')") closure.register_thrower(type, id) end push id, '.$throw(', expr_or_nil(value), ', ', scope.identify!, '.$$is_lambda)' id end def thrower(type, value = nil) case type when :return thrower_closure = select_closure(DEF, break_after: MODULE | TOP) last_closure = select_closure(JS_FUNCTION) if !thrower_closure iter_closure = select_closure(ITER, break_after: DEF | MODULE | TOP) if iter_closure generate_thrower_without_catcher(:return, iter_closure, value) elsif compiler.eval? push 'Opal.t_eval_return.$throw(', expr_or_nil(value), ', false)' else error 'Invalid return' end elsif thrower_closure == last_closure push 'return ', expr_or_nil(value) else id = generate_thrower(:return, thrower_closure, value) # Additionally, register our thrower on the surrounding iter, if present iter_closure = select_closure(ITER, break_after: DEF | MODULE | TOP) iter_closure.register_thrower(:return, id) if iter_closure end when :eval_return thrower_closure = select_closure(DEF | LAMBDA, break_after: MODULE | TOP) if thrower_closure thrower_closure.register_catcher(:eval_return) end when :next, :redo thrower_closure = select_closure(ITER | LOOP_INSIDE, break_after: DEF | MODULE | TOP) last_closure = select_closure(JS_FUNCTION | JS_LOOP_INSIDE) if !thrower_closure error 'Invalid next' elsif thrower_closure == last_closure if thrower_closure.is? RETRY_CONTAINER generate_thrower(:next, thrower_closure, value) elsif thrower_closure.is? LOOP_INSIDE push 'continue' elsif thrower_closure.is? ITER | LAMBDA push 'return ', expr_or_nil(value) end else generate_thrower(:next, thrower_closure, value) end when :break thrower_closure = select_closure(SEND | LAMBDA | LOOP, break_after: DEF | MODULE | TOP) last_closure = select_closure(JS_FUNCTION | JS_LOOP) if !thrower_closure iter_closure = select_closure(ITER, break_after: DEF | MODULE | TOP) if iter_closure generate_thrower_without_catcher(:break, iter_closure, value) else error 'Invalid break' end elsif thrower_closure == last_closure if thrower_closure.is? RETRY_CONTAINER generate_thrower(:break, thrower_closure, value) elsif thrower_closure.is? JS_FUNCTION | LAMBDA push 'return ', expr_or_nil(value) elsif thrower_closure.is? LOOP push 'break' end else generate_thrower(:break, thrower_closure, value) end when :retry thrower_closure = select_closure(RESCUE_RETRIER, break_after: DEF | MODULE | TOP) last_closure = select_closure(JS_LOOP_INSIDE) if !thrower_closure error 'Invalid retry' elsif thrower_closure == last_closure push 'continue' else generate_thrower(:retry, thrower_closure, value) end end end def closure_is?(type) @closure.is?(type) end # Generate a catcher if thrower has been used def compile_catcher catchers = @closure.catchers return if catchers.empty? helper :thrower catchers_without_eval_return = catchers.grep_v(:eval_return) push "} catch($e) {" indent do catchers.each do |type| case type when :eval_return line "if ($e === Opal.t_eval_return) return $e.$v;" else line "if ($e === $t_#{type}) return $e.$v;" end end line "throw $e;" end line "}" unless catchers_without_eval_return.empty? push " finally {", *catchers_without_eval_return.map { |type| "$t_#{type}.is_orphan = true;" }, "}" end unshift "return " if closure_is? SEND unless catchers_without_eval_return.empty? unshift "var ", catchers_without_eval_return.map { |type| "$t_#{type} = $thrower('#{type}')" }.join(", "), "; " end unshift "try { " unless closure_is? JS_FUNCTION if scope.await_encountered wrap "(await (async function(){", "})())" else wrap "(function(){", "})()" end end end end module CompilerSupport def closure_stack @closure_stack ||= [] end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/rescue.rb
lib/opal/nodes/rescue.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes class EnsureNode < Base handle :ensure children :begn, :ensr def compile push_closure if wrap_in_closure? push 'try {' in_ensure do line stmt(body_sexp) end line '} finally {' indent do if has_rescue_else? # $no_errors indicates thate there were no error raised unshift 'var $no_errors = true; ' # when there's a begin;rescue;else;ensure;end statement, # ruby returns a result of the 'else' branch # but invokes it before 'ensure'. # so, here we # 1. save the result of calling else to $rescue_else_result # 2. call ensure # 2. return $rescue_else_result line 'var $rescue_else_result;' line 'if ($no_errors) { ' indent do line '$rescue_else_result = (function() {' indent do line stmt(rescue_else_code) end line '})();' end line '}' line compiler.process(ensr_sexp, @level) line 'if ($no_errors) { return $rescue_else_result; }' else line compiler.process(ensr_sexp, @level) end end line '}' pop_closure if wrap_in_closure? if wrap_in_closure? if scope.await_encountered wrap '(await (async function() { ', '; })())' else wrap '(function() { ', '; })()' end end end def body_sexp if wrap_in_closure? compiler.returns(begn) else begn end end def ensr_sexp ensr || s(:nil) end def wrap_in_closure? recv? || expr? || has_rescue_else? end def rescue_else_code rescue_else_code = scope.rescue_else_sexp rescue_else_code = compiler.returns(rescue_else_code) unless stmt? rescue_else_code end def has_rescue_else? @sexp.meta[:has_rescue_else] end end class RescueNode < Base handle :rescue children :body def compile scope.rescue_else_sexp = children[1..-1].detect { |sexp| sexp && sexp.type != :resbody } _has_rescue_handlers = false if handle_rescue_else_manually? line 'var $no_errors = true;' end closure_type = Closure::NONE closure_type |= Closure::JS_FUNCTION if expr? || recv? if has_retry? closure_type |= Closure::JS_LOOP \ | Closure::JS_LOOP_INSIDE \ | Closure::RESCUE_RETRIER end push_closure(closure_type) if closure_type != Closure::NONE in_rescue(self) do push 'try {' indent do line stmt(body_code) end line '} catch ($err) {' indent do if has_rescue_else? line '$no_errors = false;' end children[1..-1].each_with_index do |child, idx| # counting only rescue, ignoring rescue-else statement next unless child && child.type == :resbody _has_rescue_handlers = true push ' else ' unless idx == 0 line process(child, @level) end # if no resbodys capture our error, then rethrow push ' else { throw $err; }' end line '}' if handle_rescue_else_manually? # here we must add 'finally' explicitly push 'finally {' indent do line 'if ($no_errors) { ' indent do line stmt(rescue_else_code) end line '}' end push '}' end end pop_closure if closure_type != Closure::NONE wrap 'do { ', ' break; } while(1)' if has_retry? # Wrap a try{} catch{} into a function # when it's an expression # or when there's a method call after begin;rescue;end if expr? || recv? if scope.await_encountered wrap '(await (async function() { ', '})())' else wrap '(function() { ', '})()' end end end def body_code body_code = (body.nil? || body.type == :resbody ? s(:nil) : body) body_code = compiler.returns(body_code) unless stmt? body_code end def rescue_else_code rescue_else_code = scope.rescue_else_sexp rescue_else_code = compiler.returns(rescue_else_code) unless stmt? rescue_else_code end # Returns true when there's no 'ensure' statement # wrapping current rescue. # def handle_rescue_else_manually? !in_ensure? && has_rescue_else? end def has_retry? @sexp.meta[:has_retry] end end class ResBodyNode < Base handle :resbody children :klasses_sexp, :lvar, :body def compile helper :rescue helper :pop_exception push 'if ($rescue($err, ', expr(klasses), ')) {' indent do if lvar push expr(lvar.updated(nil, [*lvar.children, s(:js_tmp, '$err')])) end # Need to ensure we clear the current exception out after the rescue block ends line 'try {' indent do in_resbody do line stmt(rescue_body) end end line '} finally { $pop_exception($err); }' end line '}' end def klasses klasses_sexp || s(:array, s(:const, nil, :StandardError)) end def rescue_body body_code = body || s(:nil) body_code = compiler.returns(body_code) unless stmt? body_code end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args.rb
lib/opal/nodes/args.rb
# frozen_string_literal: true require 'opal/nodes/base' require 'opal/nodes/args/arg' require 'opal/nodes/args/arity_check' require 'opal/nodes/args/ensure_kwargs_are_kwargs' require 'opal/nodes/args/extract_block_arg' require 'opal/nodes/args/extract_kwarg' require 'opal/nodes/args/extract_kwargs' require 'opal/nodes/args/extract_kwoptarg' require 'opal/nodes/args/extract_kwrestarg' require 'opal/nodes/args/extract_optarg' require 'opal/nodes/args/extract_post_arg' require 'opal/nodes/args/extract_post_optarg' require 'opal/nodes/args/extract_restarg' require 'opal/nodes/args/fake_arg' require 'opal/nodes/args/initialize_iterarg' require 'opal/nodes/args/initialize_shadowarg' require 'opal/nodes/args/parameters' require 'opal/nodes/args/prepare_post_args' module Opal module Nodes class ArgsNode < Base handle :args def compile children.each_with_index do |arg, idx| push ', ' if idx != 0 push process(arg) end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/super.rb
lib/opal/nodes/super.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes # This base class is used just to child the find_super_dispatcher method # body. This is then used by actual super calls, or a defined?(super) style # call. class BaseSuperNode < CallNode def initialize(*) super args = *@sexp *rest, last_child = *args if last_child && %i[iter block_pass].include?(last_child.type) @iter = last_child args = rest else @iter = s(:js_tmp, 'null') end @arglist = s(:arglist, *args) @recvr = s(:self) end def compile_using_send helper :send2 push '$send2(' compile_receiver compile_method_body compile_method_name compile_arguments compile_block_pass push ')' end private # Using super in a block inside a method is allowed, e.g. # def a # { super } # end # # This method finds returns a closest s(:def) (or s(:defs)) def def_scope @def_scope ||= scope.def? ? scope : scope.find_parent_def end def defined_check_param 'false' end def implicit_arguments_param 'false' end def method_id def_scope.mid.to_s end def def_scope_identity def_scope.identify!(def_scope.mid) end def allow_stubs 'true' end def super_method_invocation helper :find_super "$find_super(#{scope.self}, '#{method_id}', #{def_scope_identity}, #{defined_check_param}, #{allow_stubs})" end def super_block_invocation helper :find_block_super chain, cur_defn, mid = scope.super_chain trys = chain.map { |c| "#{c}.$$def" }.join(' || ') "$find_block_super(#{scope.self}, #{mid}, (#{trys} || #{cur_defn}), #{defined_check_param}, #{implicit_arguments_param})" end def compile_method_body push ', ' if scope.def? push super_method_invocation elsif scope.iter? push super_block_invocation else raise 'super must be called from method body or block' end end def compile_method_name if scope.def? push ", '#{method_id}'" elsif scope.iter? _chain, _cur_defn, mid = scope.super_chain push ", #{mid}" end end end class DefinedSuperNode < BaseSuperNode handle :defined_super def allow_stubs 'false' end def defined_check_param 'true' end def compile compile_receiver compile_method_body wrap '((', ') != null ? "super" : nil)' end end # super with explicit args class SuperNode < BaseSuperNode handle :super def initialize(*) super if scope.def? scope.uses_block! end end def compile compile_using_send end end # super with implicit args class ZsuperNode < SuperNode handle :zsuper def implicit_arguments_param 'true' end def initialize(*) super # preserve a block if we have one already but otherwise, assume a block is coming from higher # up the chain unless iter.type == :iter # Need to support passing block up even if it's not referenced in this method at all scope.uses_block! @iter = s(:js_tmp, scope.block_name || '$yield') end end def compile if def_scope implicit_args = implicit_arglist # If the method we're in has a block and we're using a default super call with no args, we need to grab the block # If an iter (block via braces) is provided, that takes precedence if block_name && !iter block_pass = s(:block_pass, s(:lvar, block_name)) implicit_args << block_pass end @arglist = s(:arglist, *implicit_args) end compile_using_send end def implicit_arglist args = [] kwargs = [] def_scope.original_args.children.each do |sexp| lvar_name = sexp.children[0] case sexp.type when :arg, :optarg arg_node = s(:lvar, lvar_name) args << arg_node when :restarg arg_node = lvar_name ? s(:lvar, lvar_name) : s(:js_tmp, '$rest_arg') args << s(:splat, arg_node) when :kwarg, :kwoptarg key_name = sexp.meta[:arg_name] kwargs << s(:pair, s(:sym, key_name), s(:lvar, lvar_name)) when :kwrestarg arg_node = lvar_name ? s(:lvar, lvar_name) : s(:js_tmp, '$kw_rest_arg') kwargs << s(:kwsplat, arg_node) end end args << s(:hash, *kwargs) unless kwargs.empty? args end def block_name case def_scope when Opal::Nodes::IterNode def_scope.block_name when Opal::Nodes::DefNode def_scope.block_name else raise "Don't know what to do with super in the scope #{def_scope}" end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/module.rb
lib/opal/nodes/module.rb
# frozen_string_literal: true require 'opal/nodes/scope' module Opal module Nodes class ModuleNode < ScopeNode handle :module children :cid, :body def compile if compiler.runtime_mode? # Skip class/module generation line stmt(body) return end name, base = name_and_base helper :module_def if body.nil? # Empty body: runtime $module_def without a callback returns nil unshift '$module_def(', base, ", '#{name}')" else in_scope do scope.name = name in_closure(Closure::MODULE | Closure::JS_FUNCTION) do compile_body end end if await_encountered await_begin = '(await ' await_end = ')' async = 'async ' parent.await_encountered = true end # Emit a direct runtime call with an inline body function. unshift "#{await_begin}$module_def(", base, ", '#{name}', #{async}function(self#{', $nesting' if @define_nesting}) {" line "}#{", #{scope.nesting}" if @define_nesting})#{await_end}" end mark_dce(name) end private # cid is always s(:const, scope_sexp_or_nil, :ConstName) def name_and_base base, name = cid.children base = if base.nil? case scope when ModuleNode, ClassNode scope.self else "#{scope.nesting}[0]" end else expr(base) end [name, base] end def compile_body body_code = stmt(compiler.returns(body)) empty_line # $nesting is now provided as a parameter to the body callback by # $klass_def/$module_def. Just setup relative access when needed. add_temp '$$ = Opal.$r($nesting)' if @define_relative_access line scope.to_vars line body_code end def mark_dce(name) unshift dce_def_begin(name, type: :const) push dce_def_end(name, type: :const) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/iter.rb
lib/opal/nodes/iter.rb
# frozen_string_literal: true require 'opal/nodes/node_with_args' module Opal module Nodes class IterNode < NodeWithArgs handle :iter children :inline_args, :stmts def compile is_lambda! if scope.lambda_definition? compile_body_or_shortcut blockopts = {} blockopts["$$arity"] = arity if arity < 0 blockopts["$$s"] = scope.self if @define_self blockopts["$$brk"] = @closure.throwers[:break] if @closure&.throwers&.key? :break blockopts["$$ret"] = @closure.throwers[:return] if @closure&.throwers&.key? :return if compiler.arity_check? blockopts["$$parameters"] = parameters_code end if compiler.enable_source_location? blockopts["$$source_location"] = source_location end # MRI expands a passed argument if the block: # 1. takes a single argument that is an array # 2. has more that one argument # With a few exceptions: # 1. mlhs arg: if a block takes |(a, b)| argument # 2. trailing ',' in the arg list (|a, |) # This flag on the method indicates that a block has a top level mlhs argument # which means that we have to expand passed array explicitly in runtime. if has_top_level_mlhs_arg? blockopts["$$has_top_level_mlhs_arg"] = "true" end if has_trailing_comma_in_args? blockopts["$$has_trailing_comma_in_args"] = "true" end unless plain_js_function? if blockopts.keys == ["$$arity"] push ", #{arity}" elsif !blockopts.empty? push ', {', blockopts.map { |k, v| "#{k}: #{v}" }.join(', '), '}' end end scope.nesting if @define_nesting scope.relative_access if @define_relative_access end def plain_js_function? sexp.meta[:plain_js_function] end def compile_body inline_params = nil to_vars = identity = body_code = nil in_scope do identity = scope.identify! inline_params = process(inline_args) compile_arity_check in_closure(Closure::JS_FUNCTION | Closure::ITER | (@is_lambda ? Closure::LAMBDA : 0)) do body_code = stmt(returned_body) if @define_self && !plain_js_function? add_temp "self = #{identity}.$$s == null ? this : #{identity}.$$s" end to_vars = scope.to_vars line body_code end end unshift to_vars if await_encountered unshift "async function #{identity}(", inline_params, '){' else unshift "function #{identity}(", inline_params, '){' end push '}' end def compile_block_arg if block_arg scope.prepare_block end end def extract_underscore_args valid_args = [] caught_blank_argument = false args.children.each do |arg| arg_name = arg.children.first if arg_name == :_ unless caught_blank_argument caught_blank_argument = true valid_args << arg end else valid_args << arg end end @sexp = @sexp.updated( nil, [ args.updated(nil, valid_args), stmts ] ) end def returned_body compiler.returns(stmts || s(:nil)) end def has_top_level_mlhs_arg? original_args.children.any? { |arg| arg.type == :mlhs } end def has_trailing_comma_in_args? if original_args.loc && original_args.loc.expression args_source = original_args.loc.expression.source args_source.match(/,\s*\|/) end end def arity_check_node s(:iter_arity_check, original_args) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/if.rb
lib/opal/nodes/if.rb
# frozen_string_literal: true require 'opal/nodes/base' require 'opal/ast/matcher' require 'thread' if RUBY_ENGINE == 'opal' module Opal module Nodes class IfNode < Base handle :if children :test, :true_body, :false_body def compile if should_compile_as_simple_expression? if true_body == s(:true) compile_with_binary_or elsif false_body == s(:false) compile_with_binary_and else compile_with_ternary end elsif could_become_switch? compile_with_switch else compile_with_if end end def compile_with_if push_closure if expects_expression? truthy = self.truthy falsy = self.falsy if falsy && !truthy # Let's optimize a little bit `unless` calls. push 'if (!', js_truthy(test), ') {' falsy, truthy = truthy, falsy else push 'if (', js_truthy(test), ') {' end # skip if-body if no truthy sexp indent { line stmt(truthy) } if truthy if falsy if falsy.type == :if line '} else ', stmt(falsy) else line '} else {' indent do line stmt(falsy) end line '}' end else line '}' # This resolution isn't finite. Let's ensure this block # always return something if we expect a return line 'return nil;' if expects_expression? end pop_closure if expects_expression? if expects_expression? return_kw = 'return ' if returning_if? if scope.await_encountered wrap "#{return_kw}(await (async function() {", '})())' else wrap "#{return_kw}(function() {", '})()' end end end def returning_if? @sexp.meta[:returning] end def truthy returnify(true_body) end def falsy returnify(false_body) end def returnify(body) if expects_expression? && body compiler.returns(body) else body end end def expects_expression? expr? || recv? end # There was a particular case in the past, that when we # expected an expression from if, we always had to closure # it. This produced an ugly code that was hard to minify. # This addition tries to make a few cases compiled with # a ternary operator instead and possibly a binary operator # even? def should_compile_as_simple_expression? expects_expression? && simple?(true_body) && simple?(false_body) end def compile_with_ternary truthy = true_body falsy = false_body push '(' push js_truthy(test), ' ? ' push '(', expr(truthy || s(:nil)), ') : ' if !falsy || falsy.type == :if push expr(falsy || s(:nil)) else push '(', expr(falsy || s(:nil)), ')' end push ')' end def compile_with_binary_and if sexp.meta[:do_js_truthy_on_true_body] truthy = js_truthy(true_body || s(:nil)) else truthy = expr(true_body || s(:nil)) end push '(' push js_truthy(test), ' && ' push '(', truthy, ')' push ')' end def compile_with_binary_or if sexp.meta[:do_js_truthy_on_false_body] falsy = js_truthy(false_body || s(:nil)) else falsy = expr(false_body || s(:nil)) end push '(' push js_truthy(test), ' || ' push '(', falsy, ')' push ')' end # Let's ensure there are no control flow statements inside. def simple?(body) case body when AST::Node case body.type when :return, :js_return, :break, :next, :redo, :retry false when :xstr XStringNode.single_line?( XStringNode.strip_empty_children(body.children) ) else body.children.all? { |i| simple?(i) } end else true end end # NOTE: all following matcher will act on case/when statements in their rewitten form: # # bin/opal --sexp -e'case some_value_or_expression; when 123; when 456, 789; end' # # s(:top, # s(:if, # s(:send, # s(:int, 123), :===, # s(:lvasgn, "$ret_or_1", # s(:send, nil, :some_value_or_expression))), nil, # s(:if, # s(:if, # s(:send, # s(:int, 456), :===, # s(:js_tmp, "$ret_or_1")), # s(:true), # s(:send, # s(:int, 789), :===, # s(:js_tmp, "$ret_or_1"))), nil, # s(:nil)))) # # Matches: `case some_value_or_expression; when 123` # Captures: [s(:int, 123), "$ret_or_1", s(:send, nil, :some_value_or_expression))] def switch_test Thread.current[:_opal_switch_test] ||= AST::Matcher.new do s(:send, cap(s(%i[float int sym str true false nil], :*)), :===, s(:lvasgn, cap(:*), cap(:*)) ) end end # Matches: case some_value_or_expression; when 123, 456; end # Captures: [ # s(:int, 123), # "$ret_or_1", # s(:send, nil, :some_value_or_expression)), # …here we delegate to either switch_branch_test or switch_branch_test_continued # ] def switch_test_continued Thread.current[:_opal_switch_test_continued] ||= AST::Matcher.new do s(:if, s(:send, cap(s(%i[float int sym str true false nil], :*)), :===, s(:lvasgn, cap(:*), cap(:*)) ), s(:true), cap(:*) ) end end # Matches: `when 456` (from `case foo; when 123; when 456; end`) # Captures: [s(:int, 456), "$ret_or_1"] def switch_branch_test Thread.current[:_opal_switch_branch_test] ||= AST::Matcher.new do s(:send, cap(s(%i[float int sym str true false nil], :*)), :===, s(:js_tmp, cap(:*)) ) end end # Matches: `when 456` # Captures: [ # s(:int, 789), # "$ret_or_1", # …here we delegate to either switch_branch_tes or switch_branch_test_continued # ] def switch_branch_test_continued Thread.current[:_opal_switch_branch_test_continued] ||= AST::Matcher.new do s(:if, s(:send, cap(s(%i[float int sym str true false nil], :*)), :===, s(:js_tmp, cap(:*)) ), s(:true), cap(:*) ) end end def could_become_switch? return false if expects_expression? return true if sexp.meta[:switch_child] test_match = switch_test.match(test) || switch_test_continued.match(test) return false unless test_match @switch_test, @switch_variable, @switch_first_test, additional_rules = *test_match additional_rules = handle_additional_switch_rules(additional_rules) return false unless additional_rules # It's ok for them to be empty, but false denotes a mismatch @switch_additional_rules = additional_rules return false unless valid_switch_body?(true_body) could_become_switch_branch?(false_body) end def handle_additional_switch_rules(additional_rules) switch_additional_rules = [] while additional_rules match = switch_branch_test.match(additional_rules) || switch_branch_test_continued.match(additional_rules) return false unless match switch_test, switch_variable, additional_rules = *match return false unless switch_variable == @switch_variable switch_additional_rules << switch_test end switch_additional_rules end def could_become_switch_branch?(body) if !body return true elsif body.type != :if if valid_switch_body?(body) body.meta[:switch_default] = true return true end return false end test, true_body, false_body = *body test_match = switch_branch_test.match(test) || switch_branch_test_continued.match(test) unless test_match if valid_switch_body?(body, true) body.meta[:switch_default] = true return true end end switch_test, switch_variable, additional_rules = *test_match switch_additional_rules = handle_additional_switch_rules(additional_rules) return false unless switch_additional_rules # It's ok for them to be empty, but false denotes a mismatch return false unless switch_variable == @switch_variable return false unless valid_switch_body?(true_body) return false unless could_become_switch_branch?(false_body) body.meta.merge!(switch_child: true, switch_test: switch_test, switch_variable: @switch_variable, switch_additional_rules: switch_additional_rules ) true end def valid_switch_body?(body, check_variable = false) case body when AST::Node case body.type when :break, :redo, :retry false when :iter, :while # Don't traverse the iters or whiles! true else body.children.all? { |i| valid_switch_body?(i, check_variable) } end when @switch_variable # Perhaps we ended abruptly and we lack a $ret_or variable... but sometimes # we can ignore this. !check_variable else true end end def compile_with_switch if sexp.meta[:switch_child] @switch_variable = sexp.meta[:switch_variable] @switch_additional_rules = sexp.meta[:switch_additional_rules] compile_switch_case(sexp.meta[:switch_test]) else line "switch (", expr(@switch_first_test), ".valueOf()) {" indent do compile_switch_case(@switch_test) end line "}" end end def returning?(body) %i[return js_return next].include?(body.type) || (body.type == :begin && %i[return js_return next].include?(body.children.last.type)) end def compile_switch_case(test) line "case ", expr(test), ":" if @switch_additional_rules @switch_additional_rules.each do |rule| line "case ", expr(rule), ":" end end indent do line stmt(true_body) line "break;" if !true_body || !returning?(true_body) end if false_body if false_body.meta[:switch_default] compile_switch_default elsif false_body.meta[:switch_child] push stmt(false_body) end else push stmt(s(:nil)) end end def compile_switch_default line "default:" indent do line stmt(false_body) end end end class BaseFlipFlop < Base children :start_condition, :end_condition def compile helper :truthy func_name = top_scope.new_temp flip_flop_state = "#{func_name}.$$ff" # Start function definition, checking and initializing it if necessary push "(#{func_name} = #{func_name} || function(_start_func, _end_func){" # If flip flop state is not defined, set it to false push " var flip_flop = #{flip_flop_state} || false;" # If flip flop state is false, call the 'start_condition' function and store its truthy result into flip flop state push " if (!flip_flop) #{flip_flop_state} = flip_flop = $truthy(_start_func());" # If flip flop state is true, call the 'end_condition' function and set flip flop state to false if 'end_condition' is truthy push " #{excl}if (flip_flop && $truthy(_end_func())) #{flip_flop_state} = false;" # Return current state of flip flop push " return flip_flop;" # End function definition push "})(" # Call the function with 'start_condition' and 'end_condition' arguments wrapped in functions to ensure correct binding and delay evaluation push " function() { ", stmt(compiler.returns(start_condition)), " }," push " function() { ", stmt(compiler.returns(end_condition)), " }" push ")" end end class IFlipFlop < BaseFlipFlop handle :iflipflop # Inclusive flip flop, check 'end_condition' in the same iteration when 'start_condition' is truthy def excl "" end end class EFlipFlop < BaseFlipFlop handle :eflipflop # Exclusive flip flop, check 'end_condition' in the next iteration after 'start_condition' is truthy def excl "else " end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/hash.rb
lib/opal/nodes/hash.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes class HashNode < Base handle :hash attr_accessor :has_kwsplat, :keys, :values def initialize(*) super @has_kwsplat = false @keys = [] @values = [] children.each do |child| case child.type when :kwsplat @has_kwsplat = true when :pair @keys << child.children[0] @values << child.children[1] end end end def simple_keys? keys.all? { |key| %i[sym str int].include?(key.type) } end def compile if has_kwsplat compile_merge else compile_hash end end # Compiles hashes containing kwsplats inside. # hash like { **{ nested: 1 }, a: 1, **{ nested: 2} } # should be compiled to # { nested: 1}.merge(a: 1).merge(nested: 2) # Each kwsplat overrides previosly defined keys # Hash k/v pairs override previously defined kwsplat values def compile_merge result, seq = [], [] children.each do |child| if child.type == :kwsplat unless seq.empty? result << expr(s(:hash, *seq)) end result << expr(child) seq = [] else seq << child end end unless seq.empty? result << expr(s(:hash, *seq)) end result.each_with_index do |fragment, idx| if idx == 0 push fragment else push '.$merge(', fragment, ')' end end end # Compiles a hash without kwsplats # with simple or complex keys. def compile_hash children.each_with_index do |pair, idx| key, value = pair.children push ', ' unless idx == 0 if %i[sym str].include?(key.type) push key.children[0].to_s.inspect, ', ', expr(value) else push expr(key), ', ', expr(value) end end if keys.empty? push '(new Map())' elsif simple_keys? helper :hash_new wrap '$hash_new(', ')' else helper :hash_new2 wrap '$hash_new2(', ')' end end end class KwSplatNode < Base handle :kwsplat children :value def compile helper :to_hash push '$to_hash(', expr(value), ')' end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/call.rb
lib/opal/nodes/call.rb
# frozen_string_literal: true require 'set' require 'pathname' require 'opal/nodes/base' module Opal module Nodes class CallNode < Base handle :send, :csend attr_reader :recvr, :meth, :arglist, :iter SPECIALS = {} # Operators that get optimized by compiler OPERATORS = { :+ => :plus, :- => :minus, :* => :times, :/ => :divide, :< => :lt, :<= => :le, :> => :gt, :>= => :ge }.freeze def self.add_special(name, options = {}, &handler) SPECIALS[name] ||= [] SPECIALS[name] << [options, handler] end def initialize(*) super @recvr, @meth, *args = *@sexp *rest, last_arg = *args if last_arg && %i[iter block_pass].include?(last_arg.type) @iter = last_arg args = rest else @iter = nil end @arglist = s(:arglist, *args) end def compile # handle some methods specially # some special methods need to skip compilation, so we pass the default as a block handle_special do compiler.record_method_call meth with_wrapper do if using_eval? # if trying to access an lvar in eval or irb mode compile_eval_var elsif using_irb? # if trying to access an lvar in irb mode compile_irb_var else default_compile end end end end private def iter_has_break? return false unless iter iter.meta[:has_break] end # Opal has a runtime helper 'Opal.send_method_name' that assigns # provided block to a '$$p' property of the method body # and invokes a method using 'apply'. # # We have to compile a method call using this 'Opal.send_method_name' when a method: # 1. takes a splat # 2. takes a block # # Arguments that contain splat must be handled in a different way. # @see #compile_arguments # # When a method takes a block we have to calculate all arguments # **before** assigning '$$p' property (that stores a passed block) # to a method body. This is some kind of protection from method calls # like 'a(a {}) { 1 }'. def invoke_using_send? iter || splat? || call_is_writer_that_needs_handling? end def invoke_using_refinement? !scope.scope.collect_refinements_temps.empty? end # Is it a conditional send, ie. `foo&.bar`? def csend? @sexp.type == :csend end def default_compile if auto_await? push '(await ' scope.await_encountered = true end push_closure(Closure::SEND) if iter_has_break? if invoke_using_refinement? compile_using_refined_send elsif invoke_using_send? compile_using_send else compile_simple_call_chain end pop_closure if iter_has_break? if auto_await? push ')' end end # Compiles method call using `Opal.send` # # @example # a.b(c, &block) # # Opal.send(a, 'b', [c], block) # def compile_using_send helper :send push dce_use(meth) push '$send(' compile_receiver compile_method_name compile_arguments compile_block_pass push ')' end # Compiles method call using `Opal.refined_send` # # @example # a.b(c, &block) # # Opal.refined_send(a, 'b', [c], block, [[Opal.MyRefinements]]) # def compile_using_refined_send helper :refined_send push dce_use(meth) push '$refined_send(' compile_refinements compile_receiver compile_method_name compile_arguments compile_block_pass push ')' end def compile_receiver push @conditional_recvr || recv(receiver_sexp) end def compile_method_name push ", '#{meth}'" end def compile_arguments(skip_comma = false) push ', ' unless skip_comma if @with_writer_temp push @with_writer_temp elsif splat? push expr(arglist) elsif arglist.children.empty? push '[]' else push '[', expr(arglist), ']' end end def compile_block_pass if iter push ', ', expr(iter) end end def compile_refinements refinements = scope.collect_refinements_temps.map { |i| s(:js_tmp, i) } push expr(s(:array, *refinements)), ', ' end def compile_simple_call_chain compile_receiver push dce_use(meth) push method_jsid, '(', expr(arglist), ')' end def splat? arglist.children.any? { |a| a.type == :splat } end def receiver_sexp recvr || s(:self) end def method_jsid mid_to_jsid meth.to_s end # Used to generate the code to use this sexp as an ivar var reference def compile_irb_var with_temp do |tmp| lvar = meth call = s(:send, s(:self), meth.intern, s(:arglist)) ref = "(typeof #{lvar} !== 'undefined') ? #{lvar} : " push "((#{tmp} = Opal.irb_vars.#{lvar}) == null ? ", ref, expr(call), " : #{tmp})" end end def compile_eval_var push meth.to_s end # a variable reference in irb mode in top scope might be a var ref, # or it might be a method call def using_irb? @compiler.irb? && scope.top? && variable_like? end def using_eval? @compiler.eval? && scope.top? && @compiler.scope_variables.include?(meth) end def variable_like? arglist == s(:arglist) && recvr.nil? && iter.nil? end def sexp_with_arglist @sexp.updated(nil, [recvr, meth, arglist]) end def auto_await? awaited_set = compiler.async_await awaited_set && awaited_set != true && awaited_set.match?(meth.to_s) end # Handle "special" method calls, e.g. require(). Subclasses can override # this method. If this method returns nil, then the method will continue # to be generated by CallNode. def handle_special(&compile_default) if SPECIALS.include? meth current_proc = compile_default SPECIALS[meth].reverse_each do |_options, handler| previous_proc = current_proc current_proc = proc do instance_exec(previous_proc, &handler) end end current_proc.call else yield # i.e. compile_default.call end end OPERATORS.each do |operator, name| add_special(operator.to_sym) do |compile_default| if invoke_using_refinement? compile_default.call elsif compiler.inline_operators? compiler.record_method_call operator helper :"rb_#{name}" lhs, rhs = expr(recvr), expr(arglist) push fragment("$rb_#{name}(") push lhs push fragment(', ') push rhs push fragment(')') else compile_default.call end end end add_special :block_given? do push compiler.handle_block_given_call @sexp end # Refinements support add_special :using do |compile_default| if scope.accepts_using? && arglist.children.count == 1 using_refinement(arglist.children.first) else compile_default.call end end def using_refinement(arg) prev, curr = *scope.refinements_temp if prev push "(#{curr} = #{prev}.slice(), #{curr}.push(", expr(arg), "), #{scope.self})" else push "(#{curr} = [", expr(arg), "], #{scope.self})" end end add_special :debugger do push fragment 'debugger' end add_special :lambda do |compile_default| scope.defines_lambda do compile_default.call end end add_special :__await__ do |compile_default| if compiler.async_await push fragment '(await (' push process(recvr) push fragment '))' scope.await_encountered = true else compile_default.call end end def push_nesting? recv = children.first children.size == 2 && ( # only receiver and method recv.nil? || ( # and no receiver recv.type == :const && # or receiver recv.children.last == :Module # is Module ) ) end def with_wrapper(&block) if csend? && !@conditional_recvr handle_conditional_send do with_wrapper(&block) end elsif call_is_writer_that_needs_handling? handle_writer(&block) else yield end end def call_is_writer_that_needs_handling? (expr? || recv?) && (meth.to_s =~ /^\w+=$/ || meth == :[]=) end # Handle safe-operator calls: foo&.bar / foo&.bar ||= baz / ... def handle_conditional_send # temporary variable that stores method receiver receiver_temp = scope.new_temp push "#{receiver_temp} = ", expr(receiver_sexp) # execute the sexp only if the receiver isn't nil push ", (#{receiver_temp} === nil || #{receiver_temp} == null) ? nil : " @conditional_recvr = receiver_temp yield wrap '(', ')' end def handle_writer with_temp do |temp| push "(#{temp} = " compile_arguments(true) push ", " @with_writer_temp = temp yield @with_writer_temp = false push ", " push "#{temp}[#{temp}.length - 1])" end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/logic.rb
lib/opal/nodes/logic.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes class NextNode < Base handle :next def compile thrower(:next, value) end def value case children.size when 0 s(:nil) when 1 children.first else s(:array, *children) end end end class BreakNode < Base handle :break children :value def compile thrower(:break, value) end end class RedoNode < Base handle :redo def compile if in_while? compile_while elsif scope.iter? compile_iter else push 'REDO()' end end def compile_while push "#{while_loop[:redo_var]} = true;" thrower(:redo) end def compile_iter helper :slice push "return #{scope.identity}.apply(null, $slice(arguments))" end end class SplatNode < Base handle :splat children :value def empty_splat? value == s(:array) end def compile if empty_splat? push '[]' else helper :to_a push '$to_a(', recv(value), ')' end end end class RetryNode < Base handle :retry def compile thrower(:retry) end end class ReturnNode < Base handle :return children :value def return_val if value.nil? s(:nil) elsif children.size > 1 s(:array, *children) else value end end def compile thrower(:return, return_val) end end class JSReturnNode < Base handle :js_return children :value def compile push 'return ' push expr(value) end end class JSTempNode < Base handle :js_tmp children :value def compile push value.to_s end end class BlockPassNode < Base handle :block_pass children :value def compile push expr(s(:send, value, :to_proc, s(:arglist))) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/lambda.rb
lib/opal/nodes/lambda.rb
# frozen_string_literal: true require 'opal/nodes/call' module Opal module Nodes class LambdaNode < Base handle :lambda children :iter def compile helper :lambda scope.defines_lambda do push '$lambda(', expr(iter), ')' end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/call/match3.rb
lib/opal/nodes/call/match3.rb
# frozen_string_literal: true require 'opal/nodes/base' require 'opal/nodes/call' module Opal module Nodes # Handles match_with_lvasgn nodes which represent matching a regular expression # with a right-hand side value and assigning the match result to a left-hand side variable. class Match3Node < Base handle :match_with_lvasgn children :lhs, :rhs def compile sexp = s(:send, lhs, :=~, rhs) # Handle named matches like: /(?<abc>b)/ =~ 'b' if lhs.type == :regexp && lhs.children.first.type == :str names = extract_names(lhs) unless names.empty? names_def = generate_names_definition names_assignments = generate_names_assignments(names) sexp = if stmt? handle_statement(sexp, names_def, names_assignments) else handle_non_statement(sexp, names_def, names_assignments) end end end push process(sexp, @level) end private def extract_names(regexp_node) re = regexp_node.children.first.children.first re.scan(/\(\?<([^>]*)>/).flatten.map(&:to_sym) end def generate_names_definition # Generate names definition: $m3names = $~ ? $~.named_captures : {} s(:lvasgn, :$m3names, s(:if, s(:gvar, :$~), s(:send, s(:gvar, :$~), :named_captures), s(:hash) ) ) end def generate_names_assignments(names) # Generate names assignments: abc = $m3names[:abc] names.map do |name| s(:lvasgn, name, s(:send, s(:lvar, :$m3names), :[], s(:sym, name) ) ) end end def handle_statement(sexp, names_def, names_assignments) # We don't care about a return value of this one, so we # ignore it and just assign the local variables. # # (/(?<abc>b)/ =~ 'f') # $m3names = $~ ? $~.named_captures : {} # abc = $m3names[:abc] s(:begin, sexp, names_def, *names_assignments) end def handle_non_statement(sexp, names_def, names_assignments) # We actually do care about a return value, so we must # keep it saved. # # $m3tmp = (/(?<abc>b)/ =~ 'f') # $m3names = $~ ? $~.named_captures : {} # abc = $m3names[:abc] # $m3tmp s(:begin, s(:lvasgn, :$m3tmp, sexp), names_def, *names_assignments, s(:lvar, :$m3tmp) ) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/call/dce.rb
lib/opal/nodes/call/dce.rb
# frozen_string_literal: true require 'opal/nodes/base' require 'opal/nodes/call' module Opal module Nodes class CallNode def dce_matcher(methods) case methods.length when 0 when 1 methods.first else methods end end def dce_symbol_arguments_matcher if arglist.children.all? { |c| c.type == :sym } methods = arglist.children.map { |c| c.children[0] } methods = yield(methods) if block_given? matcher = dce_matcher(methods) placeholder = methods.to_json unless stmt? end [matcher, placeholder] end # Add additional awareness for certain calls. add_special :attr_reader do |default| matcher, placeholder = dce_symbol_arguments_matcher push dce_def_begin(matcher, placeholder: placeholder) if matcher default.call push dce_def_end(matcher) if matcher end add_special :attr_writer do |default| matcher, placeholder = dce_symbol_arguments_matcher do |ary| ary.map { |i| :"#{i}=" } end push dce_def_begin(matcher, placeholder: placeholder) if matcher default.call push dce_def_end(matcher) if matcher end add_special :attr_accessor do |default| matcher, placeholder = dce_symbol_arguments_matcher do |ary| ary.map { |i| [i, :"#{i}="] }.flatten end push dce_def_begin(matcher, placeholder: placeholder) if matcher default.call push dce_def_end(matcher) if matcher end add_special :alias_method do |default| if arglist.children.all? { |c| c.type == :sym } && arglist.children.length == 2 new_func, old_func = arglist.children.map { |c| c.children[0] } placeholder = new_func.to_s.to_json unless stmt? push dce_def_begin(new_func, placeholder: placeholder) push dce_use(old_func) default.call push dce_def_end(new_func) else default.call end end def dce_make_constant_definition(default, const_node, const_type, const_child) if const_node&.type == const_type name = const_node.children[const_child] push dce_def_begin(name, placeholder: 'false', type: :const) default.call push dce_def_end(name, type: :const) else default.call end end # In const mode, calls like: `::Rational === string` can be # marked as definition. # This is to allow stripping of such calls if there's no # class to begin with. add_special :=== do |default| dce_make_constant_definition(default, recvr, :const, 1) end add_special :autoload do |default| dce_make_constant_definition(default, arglist.children.first, :sym, 0) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/call/reflection.rb
lib/opal/nodes/call/reflection.rb
# frozen_string_literal: true require 'opal/nodes/base' require 'opal/nodes/call' module Opal module Nodes class CallNode add_special :__callee__ do if scope.def? push fragment scope.mid.to_s.inspect else push fragment 'nil' end end add_special :__method__ do if scope.def? push fragment scope.mid.to_s.inspect else push fragment 'nil' end end add_special :__dir__ do push File.dirname(Opal::Compiler.module_name(compiler.file)).inspect end add_special :__OPAL_COMPILER_CONFIG__ do push fragment "(new Map([['arity_check', #{compiler.arity_check?}]]))" end add_special :nesting do |compile_default| push_nesting = push_nesting? push "(Opal.Module.$$nesting = #{scope.nesting}, " if push_nesting compile_default.call push ')' if push_nesting end add_special :constants do |compile_default| push_nesting = push_nesting? push "(Opal.Module.$$nesting = #{scope.nesting}, " if push_nesting compile_default.call push ')' if push_nesting end add_special :local_variables do |compile_default| next compile_default.call unless [s(:self), nil].include?(recvr) scope_variables = scope.scope_locals.map(&:to_s).inspect push scope_variables end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/call/require.rb
lib/opal/nodes/call/require.rb
# frozen_string_literal: true require 'opal/nodes/base' require 'opal/nodes/call' module Opal module Nodes class CallNode add_special :require do |compile_default| str = DependencyResolver.new(compiler, arglist.children[0]).resolve compiler.track_require str unless str.nil? compile_default.call end add_special :require_relative do arg = arglist.children[0] file = compiler.file if arg.type == :str dir = File.dirname(file) compiler.track_require Pathname(dir).join(arg.children[0]).cleanpath.to_s end push fragment("#{scope.self}.$require(#{file.inspect}+ '/../' + ") push process(arglist) push fragment(')') end add_special :autoload do |compile_default| args = arglist.children if args.length == 2 && args[0].type == :sym str = DependencyResolver.new(compiler, args[1], :ignore).resolve if str.nil? compiler.warning "File for autoload of constant '#{args[0].children[0]}' could not be bundled!" else compiler.track_require str compiler.autoloads << str end end compile_default.call end add_special :require_tree do |compile_default| first_arg, *rest = *arglist.children if first_arg.type == :str relative_path = first_arg.children[0] compiler.required_trees << relative_path dir = File.dirname(compiler.file) full_path = Pathname(dir).join(relative_path).cleanpath.to_s full_path.force_encoding(relative_path.encoding) first_arg = first_arg.updated(nil, [full_path]) end @arglist = arglist.updated(nil, [first_arg] + rest) compile_default.call end class DependencyResolver def initialize(compiler, sexp, missing_dynamic_require = nil) @compiler = compiler @sexp = sexp @missing_dynamic_require = missing_dynamic_require || @compiler.dynamic_require_severity end def resolve handle_part @sexp end def handle_part(sexp, missing_dynamic_require = @missing_dynamic_require) if sexp case sexp.type when :str return sexp.children[0] when :dstr return sexp.children.map { |i| handle_part i }.join when :begin return handle_part sexp.children[0] if sexp.children.length == 1 when :send recv, meth, *args = sexp.children parts = args.map { |s| handle_part(s, :ignore) } return nil if parts.include? nil if recv.is_a?(::Opal::AST::Node) && recv.type == :const && recv.children.last == :File case meth when :expand_path return expand_path(*parts) when :join return expand_path parts.join('/') when :dirname return expand_path parts[0].split('/')[0...-1].join('/') end elsif meth == :__dir__ return File.dirname(Opal::Compiler.module_name(@compiler.file)) end end end case missing_dynamic_require when :error @compiler.error 'Cannot handle dynamic require', @sexp.line when :warning @compiler.warning 'Cannot handle dynamic require', @sexp.line end end def expand_path(path, base = '') "#{base}/#{path}".split('/').each_with_object([]) do |part, p| if part == '' # we had '//', so ignore elsif part == '..' p.pop else p << part end end.join '/' end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/call/eval.rb
lib/opal/nodes/call/eval.rb
# frozen_string_literal: true require 'opal/nodes/base' require 'opal/nodes/call' module Opal module Nodes class CallNode # This can be refactored in terms of binding, but it would need 'corelib/binding' # to be required in existing code. add_special :eval do |compile_default| # Catch the return throw coming from eval thrower(:eval_return) next compile_default.call if arglist.children.length != 1 || ![s(:self), nil].include?(recvr) helper :compile scope.nesting temp = scope.new_temp scope_variables = scope.scope_locals.map(&:to_s).inspect push "(#{temp} = ", expr(arglist) push ", typeof Opal.compile === 'function' ? eval($compile(#{temp}" push ', {scope_variables: ', scope_variables push ", arity_check: #{compiler.arity_check?}, file: '(eval)', eval: true})) : " push "#{scope.self}.$eval(#{temp}))" end add_special :binding do |compile_default| next compile_default.call unless recvr.nil? scope.nesting push "Opal.Binding.$new(" push " function($code) {" push " return eval($code);" push " }," push " ", scope.scope_locals.map(&:to_s).inspect, "," push " ", scope.self, "," push " ", source_location push ")" end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/call/js_property.rb
lib/opal/nodes/call/js_property.rb
# frozen_string_literal: true require 'opal/nodes/base' require 'opal/nodes/call' module Opal module Nodes # recvr.JS[:prop] # => recvr.prop class JsAttrNode < Base handle :jsattr children :recvr, :property def compile push recv(recvr), '[', expr(property), ']' end end # recvr.JS[:prop] = value # => recvr.prop = value class JsAttrAsgnNode < Base handle :jsattrasgn children :recvr, :property, :value def compile push recv(recvr), '[', expr(property), '] = ', expr(value) end end class JsCallNode < CallNode handle :jscall def initialize(*) super # For .JS. call we pass a block # as a plain JS callback if @iter @iter.meta[:plain_js_function] = true @arglist <<= @iter end @iter = nil end def compile default_compile end def method_jsid ".#{meth}" end def compile_using_send push recv(receiver_sexp), method_jsid, '.apply(null' compile_arguments if iter push '.concat(', expr(iter), ')' end push ')' end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/node_with_args/shortcuts.rb
lib/opal/nodes/node_with_args/shortcuts.rb
# frozen_string_literal: true module Opal module Nodes class NodeWithArgs < ScopeNode # Shortcuts for the simplest kinds of methods Shortcut = Struct.new(:name, :for, :when, :transform) do def match?(node) node.instance_exec(&self.when) end def compile(node) node.helper name node.instance_exec(&transform) end end @shortcuts = [] @shortcuts_for = {} def self.define_shortcut(name, **kwargs, &block) kwargs[:for] ||= :def @shortcuts << Shortcut.new(name, kwargs[:for], kwargs[:when], block) end def self.shortcuts_for(node_type) @shortcuts_for[node_type] ||= @shortcuts.select do |shortcut| [node_type, :*].include? shortcut.for end end def compile_body_or_shortcut # The shortcuts don't check arity. If we want to check arity, # we can't use them. return compile_body if compiler.arity_check? node_type = is_a?(DefNode) ? :def : :iter NodeWithArgs.shortcuts_for(node_type).each do |shortcut| if shortcut.match?(self) if ENV['OPAL_DEBUG_SHORTCUTS'] node_desc = node_type == :def ? "def #{mid}" : "iter" warn "* shortcut #{shortcut.name} used for #{node_desc}" end return shortcut.compile(self) end end compile_body end # Shortcut definitions # -------------------- # def a; self; end define_shortcut :return_self, when: -> { stmts.type == :self } do push '$return_self' end def simple_value?(node = stmts) %i[true false nil int float str sym].include?(node.type) end # def a; 123; end define_shortcut :return_val, for: :*, when: -> { simple_value? } do push '$return_val(', expr(stmts), ')' end # def a; @x; end define_shortcut :return_ivar, when: -> { stmts.type == :ivar } do name = stmts.children.first.to_s[1..-1].to_sym push '$return_ivar(', expr(stmts.updated(:sym, [name])), ')' end # def a; @x = 5; end define_shortcut :assign_ivar, when: -> { stmts.type == :ivasgn && inline_args.children.length == 1 && inline_args.children.last.type == :arg && stmts.children.last.type == :lvar && stmts.children.last.children.last == inline_args.children.last.children.last } do name = stmts.children.first.to_s[1..-1].to_sym name = expr(stmts.updated(:sym, [name])) push '$assign_ivar(', name, ')' end # def a(x); @x = x; end define_shortcut :assign_ivar_val, when: -> { stmts.type == :ivasgn && simple_value?(stmts.children.last) } do name = stmts.children.first.to_s[1..-1].to_sym name = expr(stmts.updated(:sym, [name])) push '$assign_ivar_val(', name, ', ', expr(stmts.children.last), ')' end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/arg.rb
lib/opal/nodes/args/arg.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # Compiles a single inline required argument # def m(a); end # ^ class ArgNode < Base handle :arg children :name def compile scope.add_arg name push name.to_s end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/prepare_post_args.rb
lib/opal/nodes/args/prepare_post_args.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # A utility node responsible for preparing # post-argument for :extract_post_* nodes class PreparePostArgs < Base handle :prepare_post_args children :offset def compile add_temp '$post_args' helper :slice if offset == 0 push "$post_args = $slice(arguments)" else push "$post_args = $slice(arguments, #{offset})" end end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/extract_kwoptarg.rb
lib/opal/nodes/args/extract_kwoptarg.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # This node is responsible for extracting a single # optional keyword argument from $kwargs # # $kwargs always exist (as argument when inlining is possible # and as a local variable when it's not) # class ExtractKwoptarg < Base handle :extract_kwoptarg children :lvar_name, :default_value def compile helper :hash_get key_name = @sexp.meta[:arg_name] scope.used_kwargs << key_name add_temp lvar_name line "#{lvar_name} = $hash_get($kwargs, #{key_name.to_s.inspect});" return if default_value.children[1] == :undefined push "if (#{lvar_name} == null) #{lvar_name} = ", expr(default_value) end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/extract_kwrestarg.rb
lib/opal/nodes/args/extract_kwrestarg.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # This node is responsible for extracting a single # splat keyword argument from $kwargs # # $kwargs always exist (as argument when inlining is possible # and as a local variable when it's not) # class ExtractKwrestarg < Base handle :extract_kwrestarg children :name def compile # def m(**) # arguments are assigned to `$kw_rest_arg` for super call name = self.name || '$kw_rest_arg' add_temp name helper :kwrestargs push "#{name} = $kwrestargs($kwargs, #{used_kwargs})" end def used_kwargs args = scope.used_kwargs.map do |arg_name| "'#{arg_name}': true" end "{#{args.join ','}}" end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/extract_block_arg.rb
lib/opal/nodes/args/extract_block_arg.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # Compiles extraction of the block argument # def m(&block); end # ^^^^^^ # # This node doesn't exist in the original AST, # InlineArgs rewriter creates it to simplify compilation class ExtractBlockarg < Base handle :extract_blockarg children :name def compile scope.uses_block! scope.add_arg name scope.prepare_block(name) end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/arity_check.rb
lib/opal/nodes/args/arity_check.rb
# frozen_string_literal: true require 'opal/nodes/base' require 'opal/rewriters/arguments' module Opal module Nodes class ArityCheckNode < Base handle :arity_check children :args_node def initialize(*) super arguments = Rewriters::Arguments.new(args_node.children) @args = arguments.args @optargs = arguments.optargs @restarg = arguments.restarg @postargs = arguments.postargs @kwargs = arguments.kwargs @kwoptargs = arguments.kwoptargs @kwrestarg = arguments.kwrestarg @kwnilarg = arguments.kwnilarg end def compile return if compiler.runtime_mode? scope.arity = arity return unless compiler.arity_check? unless arity_checks.empty? helper :ac meth = scope.mid.to_s.inspect line 'var $arity = arguments.length;' push " if (#{arity_checks.join(' || ')}) { $ac($arity, #{arity}, this, #{meth}); }" end end def kwargs [*@kwargs, *@kwoptargs, @kwrestarg].compact end def all_args @all_args ||= [*@args, *@optargs, @restarg, *@postargs, *kwargs].compact end # Returns an array of JS conditions for raising and argument # error caused by arity check def arity_checks return @arity_checks if defined?(@arity_checks) arity = all_args.size arity -= @optargs.size arity -= 1 if @restarg arity -= kwargs.size arity = -arity - 1 if !@optargs.empty? || !kwargs.empty? || @restarg @arity_checks = [] if arity < 0 # splat or opt args min_arity = -(arity + 1) max_arity = all_args.size @arity_checks << "$arity < #{min_arity}" if min_arity > 0 @arity_checks << "$arity > #{max_arity}" unless @restarg else @arity_checks << "$arity !== #{arity}" end @arity_checks end def arity if @restarg || @optargs.any? || has_only_optional_kwargs? negative_arity else positive_arity end end def negative_arity required_plain_args = all_args.select do |arg| %i[arg mlhs].include?(arg.type) end result = required_plain_args.size if has_required_kwargs? result += 1 end result = -result - 1 result end def positive_arity result = all_args.size result -= kwargs.size result += 1 if kwargs.any? result end def has_only_optional_kwargs? kwargs.any? && kwargs.all? { |arg| %i[kwoptarg kwrestarg].include?(arg.type) } end def has_required_kwargs? kwargs.any? { |arg| arg.type == :kwarg } end end class IterArityCheckNode < ArityCheckNode handle :iter_arity_check def compile return if compiler.runtime_mode? scope.arity = arity return unless compiler.arity_check? unless arity_checks.empty? parent_scope = scope until parent_scope.def? || parent_scope.class_scope? || parent_scope.top? parent_scope = parent_scope.parent end context = if parent_scope.top? "'<main>'" elsif parent_scope.def? "'#{parent_scope.mid}'" elsif parent_scope.class? "'<class:#{parent_scope.name}>'" elsif parent_scope.module? "'<module:#{parent_scope.name}>'" end identity = scope.identity helper :block_ac line "if (#{identity}.$$is_lambda || #{identity}.$$define_meth) {" line ' var $arity = arguments.length;' line " if (#{arity_checks.join(' || ')}) { $block_ac($arity, #{arity}, #{context}); }" line '}' end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/extract_restarg.rb
lib/opal/nodes/args/extract_restarg.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # This node is responsible for extracting a splat argument from post-arguments # # args_to_keep is the number of required post-arguments # # def m(*a, b, c, d); end # becomes something like: # a = post_args[0..-3] # post_args = post_args[-3..-1] # class ExtractRestarg < Base handle :extract_restarg children :name, :args_to_keep def compile # def m(*) # arguments are assigned to `$rest_arg` for super call name = self.name || '$rest_arg' add_temp name if args_to_keep == 0 # no post-args, we are free to grab everything push "#{name} = $post_args" else push "#{name} = $post_args.splice(0, $post_args.length - #{args_to_keep})" end end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/initialize_iterarg.rb
lib/opal/nodes/args/initialize_iterarg.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # This node is responsible for initializing a single # required block arg # # proc { |a| } # # Procs don't have arity checking and code like # proc { |a| }.call # must return nil class InitializeIterarg < Base handle :initialize_iter_arg children :name def compile push "if (#{name} == null) #{name} = nil" end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/extract_post_optarg.rb
lib/opal/nodes/args/extract_post_optarg.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # This node is responsible for extracting a single # optional post-argument # # args_to_keep is the number of required post-arguments # # def m(a = 1, b, c, d); end # becomes something like: # if post_args.length > 3 # a = post_args[0] # post_args = post_args[1..-1] # end # class ExtractPostOptarg < Base handle :extract_post_optarg children :name, :default_value, :args_to_keep def compile add_temp name line "if ($post_args.length > #{args_to_keep}) #{name} = $post_args.shift();" return if default_value.children[1] == :undefined push "if (#{name} == null) #{name} = ", expr(default_value) end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/extract_kwarg.rb
lib/opal/nodes/args/extract_kwarg.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # This node is responsible for extracting a single # required keyword argument from $kwargs # # $kwargs always exist (as argument when inlining is possible # and as a local variable when it's not) # class ExtractKwarg < Base handle :extract_kwarg children :lvar_name def compile key_name = @sexp.meta[:arg_name] scope.used_kwargs << key_name add_temp lvar_name helper :get_kwarg push "#{lvar_name} = $get_kwarg($kwargs, #{key_name.to_s.inspect})" end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/initialize_shadowarg.rb
lib/opal/nodes/args/initialize_shadowarg.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # This node is responsible for initializing a shadow arg # # proc { |;a| } # class InitializeShadowarg < Base handle :initialize_shadowarg children :name def compile scope.locals << name scope.add_arg(name) push "#{name} = nil" end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/parameters.rb
lib/opal/nodes/args/parameters.rb
# frozen_string_literal: true module Opal module Nodes module Args class Parameters def initialize(args) @args = args.children end def to_code stringified_parameters = @args.map do |arg| public_send(:"on_#{arg.type}", arg) end "[#{stringified_parameters.compact.join(', ')}]" end def on_arg(arg) arg_name = arg.meta[:arg_name] %{['req', '#{arg_name}']} end def on_mlhs(_arg) %{['req']} end def on_optarg(arg) arg_name = arg.meta[:arg_name] %{['opt', '#{arg_name}']} end def on_restarg(arg) arg_name = arg.meta[:arg_name] if arg_name arg_name = :* if arg_name == :fwd_rest_arg %{['rest', '#{arg_name}']} else %{['rest']} end end def on_kwarg(arg) arg_name = arg.meta[:arg_name] %{['keyreq', '#{arg_name}']} end def on_kwoptarg(arg) arg_name = arg.meta[:arg_name] %{['key', '#{arg_name}']} end def on_kwrestarg(arg) arg_name = arg.meta[:arg_name] if arg_name %{['keyrest', '#{arg_name}']} else %{['keyrest']} end end def on_blockarg(arg) arg_name = arg.meta[:arg_name] arg_name = :& if arg_name == :fwd_block_arg %{['block', '#{arg_name}']} end def on_kwnilarg(_arg) %{['nokey']} end def on_shadowarg(_arg); end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/ensure_kwargs_are_kwargs.rb
lib/opal/nodes/args/ensure_kwargs_are_kwargs.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # A utility node responsible for compiling # a runtime validation for kwargs. # # This node is used for both inline and post-kwargs # class EnsureKwargsAreKwargs < Base handle :ensure_kwargs_are_kwargs def compile helper :ensure_kwargs push '$kwargs = $ensure_kwargs($kwargs)' end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/extract_post_arg.rb
lib/opal/nodes/args/extract_post_arg.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # This node is responsible for extracting a single # required post-argument from $post_args # class ExtractPostArg < Base handle :extract_post_arg children :name def compile add_temp name line "#{name} = $post_args.shift();" push "if (#{name} == null) #{name} = nil" end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/extract_kwargs.rb
lib/opal/nodes/args/extract_kwargs.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # A utility node responsible for extracting # post-kwargs from post-arguments. # # This node is used when kwargs cannot be inlined: # def m(a = 1, kw:); end # # This node is NOT used when kwargs can be inlined: # def m(a, kw:); end # class ExtractKwargs < Base handle :extract_kwargs def compile add_temp '$kwargs' helper :extract_kwargs push '$kwargs = $extract_kwargs($post_args)' end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/extract_optarg.rb
lib/opal/nodes/args/extract_optarg.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # Compiles extraction of a single inline optional argument # def m(a = 1); end # ^^^^^ # # This node doesn't exist in the original AST, # InlineArgs rewriter creates it to simplify compilation # # Sometimes the argument can't be inlined. # In such cases InlineArgs rewriter replaces # s(:optarg, :arg_name, ...default value...) # to: # s(:fakearg) + s(:extract_post_optarg, :arg_name, ...default value...) # class ExtractOptargNode < Base handle :extract_optarg children :name, :default_value def compile return if default_value.children[1] == :undefined push "if (#{name} == null) #{name} = ", expr(default_value) end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/nodes/args/fake_arg.rb
lib/opal/nodes/args/fake_arg.rb
# frozen_string_literal: true require 'opal/nodes/base' module Opal module Nodes module Args # Compiles a fake argument produced by the InlineArgs rewriter. # # This argument represents an argument from the # Ruby code that gets initialized later in the function body. # # def m(a = 1, b); end # ^ class FakeArgNode < Base handle :fake_arg def compile name = scope.next_temp scope.add_arg name push name end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/source_map/vlq.rb
lib/opal/source_map/vlq.rb
# Ported from http://github.com/maccman/sourcemap # # Adopted from ConradIrwin/ruby-source_map # https://github.com/ConradIrwin/ruby-source_map/blob/master/lib/source_map/vlq.rb # # Resources # # http://en.wikipedia.org/wiki/Variable-length_quantity # https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit # https://github.com/mozilla/source-map/blob/master/lib/source-map/base64-vlq.js # module Opal::SourceMap::VLQ VLQ_BASE_SHIFT = 5 VLQ_BASE = 1 << VLQ_BASE_SHIFT VLQ_BASE_MASK = VLQ_BASE - 1 VLQ_CONTINUATION_BIT = VLQ_BASE BASE64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('') BASE64_VALUES = (0...64).inject({}) { |h, i| h[BASE64_DIGITS[i]] = i; h } # Public: Encode a list of numbers into a compact VLQ string. # # ary - An Array of Integers # # Returns a VLQ String. def self.encode(ary) result = [] ary.each do |n| vlq = n < 0 ? ((-n) << 1) + 1 : n << 1 loop do digit = vlq & VLQ_BASE_MASK vlq >>= VLQ_BASE_SHIFT digit |= VLQ_CONTINUATION_BIT if vlq > 0 result << BASE64_DIGITS[digit] break unless vlq > 0 end end result.join end # Public: Decode a VLQ string. # # str - VLQ encoded String # # Returns an Array of Integers. def self.decode(str) result = [] chars = str.split('') while chars.any? vlq = 0 shift = 0 continuation = true while continuation char = chars.shift raise ArgumentError unless char digit = BASE64_VALUES[char] continuation = false if (digit & VLQ_CONTINUATION_BIT) == 0 digit &= VLQ_BASE_MASK vlq += digit << shift shift += VLQ_BASE_SHIFT end result << (vlq & 1 == 1 ? -(vlq >> 1) : vlq >> 1) end result end # Public: Encode a mapping array into a compact VLQ string. # # ary - Two dimensional Array of Integers. # # Returns a VLQ encoded String seperated by , and ;. def self.encode_mappings(ary) ary.map { |group| group.map { |segment| encode(segment) }.join(',') }.join(';') end # Public: Decode a VLQ string into mapping numbers. # # str - VLQ encoded String # # Returns an two dimensional Array of Integers. def self.decode_mappings(str) mappings = [] str.split(';').each_with_index do |group, index| mappings[index] = [] group.split(',').each do |segment| mappings[index] << decode(segment) end end mappings end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/source_map/index.rb
lib/opal/source_map/index.rb
# frozen_string_literal: true class Opal::SourceMap::Index include Opal::SourceMap::Map attr_reader :source_maps # @param source_maps [Opal::SourceMap::File] # @param join: the string used to join the sources, empty by default, Opal::Builder uses "\n" def initialize(source_maps, join: nil) @source_maps = source_maps @join = join end # To support concatenating generated code and other common post processing, an # alternate representation of a map is supported: # # 1: { # 2: version : 3, # 3: file: “app.js”, # 4: sections: [ # 5: { offset: {line:0, column:0}, url: “url_for_part1.map” } # 6: { offset: {line:100, column:10}, map: # 7: { # 8: version : 3, # 9: file: “section.js”, # 10: sources: ["foo.js", "bar.js"], # 11: names: ["src", "maps", "are", "fun"], # 12: mappings: "AAAA,E;;ABCDE;" # 13: } # 14: } # 15: ], # 16: } # # The index map follow the form of the standard map # # Line 1: The entire file is an JSON object. # Line 2: The version field. See the description of the standard map. # Line 3: The name field. See the description of the standard map. # Line 4: The sections field. # # The “sections” field is an array of JSON objects that itself has two fields # “offset” and a source map reference. “offset” is an object with two fields, # “line” and “column”, that represent the offset into generated code that the # referenced source map represents. # # The other field must be either “url” or “map”. A “url” entry must be a URL # where a source map can be found for this section and the url is resolved in the # same way as the “sources” fields in the standard map. A “map” entry must be an # embedded complete source map object. An embedded map does not inherit any # values from the containing index map. # # The sections must be sorted by starting position and the represented sections # may not overlap. # def map offset_line = 0 offset_column = 0 { version: 3, # file: "app.js", sections: @source_maps.map do |source_map| map = { offset: { line: offset_line, column: offset_column, }, map: source_map.to_h, } generated_code = source_map.generated_code generated_code += @join if @join new_lines_count = generated_code.count("\n") last_line = generated_code[generated_code.rindex("\n") + 1..-1] offset_line += new_lines_count offset_column += last_line.size map end } end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/source_map/file.rb
lib/opal/source_map/file.rb
# frozen_string_literal: true class Opal::SourceMap::File include Opal::SourceMap::Map attr_reader :fragments attr_reader :file attr_reader :source def initialize(fragments, file, source, generated_code = nil) @fragments = fragments @file = file @source = source @names_map = Hash.new { |hash, name| hash[name] = hash.size } @generated_code = generated_code @absolute_mappings = nil end def generated_code @generated_code ||= @fragments.map(&:code).join end # Proposed Format # 1: { # 2: "version" : 3, # 3: "file": "out.js", # 4: "sourceRoot": "", # 5: "sources": ["foo.js", "bar.js"], # 6: "sourcesContent": [null, null], # 7: "names": ["src", "maps", "are", "fun"], # 8: "mappings": "A,AAAB;;ABCDE;" # 9: } # # Line 1: The entire file is a single JSON object # Line 2: File version (always the first entry in the object) and must be a # positive integer. # Line 3: An optional name of the generated code that this source map is # associated with. # Line 4: An optional source root, useful for relocating source files on a server # or removing repeated values in the “sources” entry. This value is prepended to # the individual entries in the “source” field. # Line 5: A list of original sources used by the “mappings” entry. # Line 6: An optional list of source content, useful when the “source” can’t be # hosted. The contents are listed in the same order as the sources in line 5. # “null” may be used if some original sources should be retrieved by name. # Line 7: A list of symbol names used by the “mappings” entry. # Line 8: A string with the encoded mapping data. def map(source_root: '') { version: 3, # file: "out.js", # This is optional sourceRoot: source_root, sources: [file], sourcesContent: [source.encoding == Encoding::UTF_8 ? source : source.encode('UTF-8', undef: :replace)], names: names, mappings: Opal::SourceMap::VLQ.encode_mappings(relative_mappings), # x_com_opalrb_original_lines: source.count("\n"), # x_com_opalrb_generated_lines: generated_code.count("\n"), } end def names @names ||= begin absolute_mappings # let the processing happen @names_map.to_a.sort_by { |_, index| index }.map { |name, _| name } end end # The fields in each segment are: # # 1. The zero-based starting column of the line in the generated code that # the segment represents. If this is the first field of the first segment, or # the first segment following a new generated line (“;”), then this field # holds the whole base 64 VLQ. Otherwise, this field contains a base 64 VLQ # that is relative to the previous occurrence of this field. Note that this # is different than the fields below because the previous value is reset # after every generated line. # # 2. If present, an zero-based index into the “sources” list. This field is # a base 64 VLQ relative to the previous occurrence of this field, unless # this is the first occurrence of this field, in which case the whole value # is represented. # # 3. If present, the zero-based starting line in the original source # represented. This field is a base 64 VLQ relative to the previous # occurrence of this field, unless this is the first occurrence of this # field, in which case the whole value is represented. Always present if # there is a source field. # # 4. If present, the zero-based starting column of the line in the source # represented. This field is a base 64 VLQ relative to the previous # occurrence of this field, unless this is the first occurrence of this # field, in which case the whole value is represented. Always present if # there is a source field. # # 5. If present, the zero-based index into the “names” list associated with # this segment. This field is a base 64 VLQ relative to the previous # occurrence of this field, unless this is the first occurrence of this # field, in which case the whole value is represented. def segment_from_fragment(fragment, generated_column) source_index = 0 # always 0, we're dealing with a single file original_line = (fragment.line || 0) - 1 # fragments have 1-based lines original_line = 0 if original_line < 0 # line 0 (-1) for fragments in source maps will crash # browsers devtools and the webpack build process original_column = fragment.column || 0 # fragments have 0-based columns if fragment.source_map_name map_name_index = (@names_map[fragment.source_map_name.to_s] ||= @names_map.size) [ generated_column, source_index, original_line, original_column, map_name_index, ] else [ generated_column, source_index, original_line, original_column, ] end end def relative_mappings @relative_mappings ||= begin reference_segment = [0, 0, 0, 0, 0] reference_name_index = 0 absolute_mappings.map do |absolute_mapping| # [generated_column, source_index, original_line, original_column, map_name_index] reference_segment[0] = 0 # reset the generated_column at each new line absolute_mapping.map do |absolute_segment| segment = [] segment[0] = absolute_segment[0] - reference_segment[0] segment[1] = absolute_segment[1] - (reference_segment[1] || 0) segment[2] = absolute_segment[2] - (reference_segment[2] || 0) segment[3] = absolute_segment[3] - (reference_segment[3] || 0) # Since [4] can be nil we need to keep track of it in the reference_segment even if it's nil in absolute_segment if absolute_segment[4] segment[4] = absolute_segment[4].to_int - (reference_segment[4] || reference_name_index).to_int reference_name_index = absolute_segment[4] end reference_segment = absolute_segment segment end end end end # The “mappings” data is broken down as follows: # # each group representing a line in the generated file is separated by a ”;” # each segment is separated by a “,” # each segment is made up of 1,4 or 5 variable length fields. def absolute_mappings @absolute_mappings ||= begin mappings = [] fragments_by_line.each do |raw_segments| generated_column = 0 segments = [] raw_segments.each do |(generated_code, fragment)| unless fragment.is_a?(Opal::Fragment) && fragment.skip_source_map? segments << segment_from_fragment(fragment, generated_column) end generated_column += generated_code.size end mappings << segments end mappings end end private def fragments_by_line raw_mappings = [[]] fragments.flat_map do |fragment| fragment_code = fragment.code splitter = /\r/.match?(fragment_code) ? /\r?\n/ : "\n" fragment_lines = fragment_code.split(splitter, -1) # a negative limit won't suppress trailing null values fragment_lines.each.with_index do |fragment_line, index| raw_segment = [fragment_line, fragment] if index.zero? && !fragment_line.size.zero? raw_mappings.last << raw_segment elsif index.zero? && fragment_line.size.zero? # noop elsif fragment_line.size.zero? raw_mappings << [] else raw_mappings << [raw_segment] end end end raw_mappings end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/source_map/map.rb
lib/opal/source_map/map.rb
# frozen_string_literal: true require 'base64' require 'json' module Opal::SourceMap::Map def to_h @to_h || map end def to_json map = to_h map.to_json rescue Encoding::UndefinedConversionError map[:sections].each do |i| i.to_json rescue Encoding::UndefinedConversionError map[:sections].delete(i) end map.to_json end def as_json(*) to_h end def to_s to_h.to_s end def to_data_uri_comment "//# sourceMappingURL=data:application/json;base64,#{Base64.encode64(to_json).delete("\n")}" end # Marshaling for cache shortpath def cache @to_h ||= map self end def marshal_dump [to_h, generated_code] end def marshal_load(value) @to_h, @generated_code = value end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/ast/node.rb
lib/opal/ast/node.rb
# frozen_string_literal: true require 'ast' require 'parser/ast/node' module Opal module AST class Node < ::Parser::AST::Node attr_reader :meta def assign_properties(properties) if meta = properties[:meta] meta = meta.dup if meta.frozen? @meta.merge!(meta) else @meta ||= {} end super end def line loc.line if loc end def column loc.column if loc end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/ast/matcher.rb
lib/opal/ast/matcher.rb
# frozen_string_literal: true require 'ast' require 'parser/ast/node' module Opal module AST class Matcher def initialize(&block) @root = instance_exec(&block) end def s(type, *children) Node.new(type, children) end def cap(capture) Node.new(:capture, [capture]) end def match(ast) @captures = [] @root.match(ast, self) || (return false) @captures end def inspect "#<Opal::AST::Matcher: #{@root.inspect}>" end attr_accessor :captures Node = Struct.new(:type, :children) do def match(ast, matcher) return false if ast.nil? ast_parts = [ast.type] + ast.children self_parts = [type] + children return false if ast_parts.length != self_parts.length ast_parts.length.times.all? do |i| ast_elem = ast_parts[i] self_elem = self_parts[i] if self_elem.is_a?(Node) && self_elem.type == :capture capture = true self_elem = self_elem.children.first end res = case self_elem when Node self_elem.match(ast_elem, matcher) when Array self_elem.include?(ast_elem) when :* true else self_elem == ast_elem end matcher.captures << ast_elem if capture res end end def inspect if type == :capture "{#{children.first.inspect}}" else "s(#{type.inspect}, #{children.inspect[1..-2]})" end end end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/ast/builder.rb
lib/opal/ast/builder.rb
# frozen_string_literal: true require 'opal/ast/node' require 'parser/ruby32' module Opal module AST class Builder < ::Parser::Builders::Default self.emit_lambda = true def n(type, children, location) ::Opal::AST::Node.new(type, children, location: location) end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/parser/default_config.rb
lib/opal/parser/default_config.rb
# frozen_string_literal: true module Opal module Parser module DefaultConfig module ClassMethods attr_accessor :diagnostics_consumer def default_parser parser = super parser.diagnostics.all_errors_are_fatal = true parser.diagnostics.ignore_warnings = false parser.diagnostics.consumer = diagnostics_consumer parser end end def self.included(klass) klass.extend(ClassMethods) klass.diagnostics_consumer = ->(diagnostic) do if RUBY_ENGINE != 'opal' $stderr.puts(diagnostic.render) end end end def initialize(*) super(Opal::AST::Builder.new) end def parse(source_buffer) parsed = super || ::Opal::AST::Node.new(:nil) wrapped = ::Opal::AST::Node.new(:top, [parsed]) rewriten = rewrite(wrapped) rewriten end def rewrite(node) Opal::Rewriter.new(node).process end end class << self attr_accessor :default_parser_class def default_parser default_parser_class.default_parser end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/parser/patch.rb
lib/opal/parser/patch.rb
# backtick_javascript: true # frozen_string_literal: true if RUBY_ENGINE == 'opal' class Parser::Lexer def source_buffer=(source_buffer) @source_buffer = source_buffer if @source_buffer source = @source_buffer.source # Force UTF8 unpacking even if JS works with UTF-16/UCS-2 # See: https://mathiasbynens.be/notes/javascript-encoding @source_pts = source.unpack('U*') else @source_pts = nil end # Since parser v3.2.1 Parser::Lexer has @strings if @strings @strings.source_buffer = @source_buffer @strings.source_pts = @source_pts end end end class Parser::Lexer::Literal undef :extend_string def extend_string(string, ts, te) @buffer_s ||= ts @buffer_e = te # Patch for opal-parser, original: # @buffer << string @buffer += string end end class Parser::Source::Buffer def source_lines @lines ||= begin lines = @source.lines.to_a lines << '' if @source.end_with?("\n") lines.map { |line| line.chomp("\n") } end end end class Parser::Builders::Default def check_lvar_name(name, loc) # https://javascript.info/regexp-unicode if name =~ `new RegExp('^[\\p{Ll}|_][\\p{L}\\p{Nl}\\p{Nd}_]*$', 'u')` # OK else diagnostic :error, :lvar_name, { name: name }, loc end end # Taken From: # https://github.com/whitequark/parser/blob/a7c638b7b205db9213a56897b41a8e5620df766e/lib/parser/builders/default.rb#L388 def dedent_string(node, dedent_level) unless dedent_level.nil? dedenter = ::Parser::Lexer::Dedenter.new(dedent_level) case node.type when :str node = node.updated(nil, [dedenter.dedent(node.children.first)]) when :dstr, :xstr children = node.children.map do |str_node| if str_node.type == :str str_node = str_node.updated(nil, [dedenter.dedent(str_node.children.first)]) next nil if str_node.children.first.empty? else dedenter.interrupt end str_node end node = node.updated(nil, children.compact) end end node end end class Parser::Lexer::Dedenter # Taken From: # https://github.com/whitequark/parser/blob/b7a08031523d05b2f76b0bab22fac00b1d3fe653/lib/parser/lexer/dedenter.rb#L36 def dedent(string) original_encoding = string.encoding # Prevent the following error when processing binary encoded source. # "\xC0".split # => ArgumentError (invalid byte sequence in UTF-8) lines = string.force_encoding(Encoding::BINARY).split("\\\n") if lines.length == 1 # If the line continuation sequence was found but there is no second # line, it was not really a line continuation and must be ignored. lines = [string.force_encoding(original_encoding)] else lines.map! { |s| s.force_encoding(original_encoding) } end lines.each_with_index do |line, index| next if (index == 0) && !@at_line_begin left_to_remove = @dedent_level remove = 0 line.each_char do |char| break if left_to_remove <= 0 case char when "\s" remove += 1 left_to_remove -= 1 when "\t" break if TAB_WIDTH * (remove / TAB_WIDTH + 1) > @dedent_level remove += 1 left_to_remove -= TAB_WIDTH else # no more spaces or tabs break end end lines[index] = line[remove..-1] end string = lines.join @at_line_begin = string.end_with?("\n") string end end end module AST::Processor::Mixin undef process # This patch to #process removes a bit of dynamic abilities (removed # call to node.to_ast) and it tries to optimize away the string # operations and method existence check by caching them inside a # processor. # # This is the second most inefficient call in the compilation phase # so an optimization may be warranted. def process(node) return if node.nil? @_on_handler_cache ||= {} type = node.type on_handler = @_on_handler_cache[type] ||= begin handler = :"on_#{type}" handler = :handler_missing unless respond_to?(handler) handler end send(on_handler, node) || node end end class Parser::Builders::Default # string_value raises on invalid UTF-8 strings, like "\x80", # otherwise it's the same as value. undef string_value def string_value(token) value(token) end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/parser/with_ruby_lexer.rb
lib/opal/parser/with_ruby_lexer.rb
# frozen_string_literal: true class Opal::Parser::WithRubyLexer < Parser::Ruby32 include Opal::Parser::DefaultConfig Opal::Parser.default_parser_class = self end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/lib/opal/parser/source_buffer.rb
lib/opal/parser/source_buffer.rb
# frozen_string_literal: true module Opal module Parser class SourceBuffer < ::Parser::Source::Buffer def self.recognize_encoding(string) super || Encoding::UTF_8 end end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/quickjs.rb
stdlib/quickjs.rb
# backtick_javascript: true `/* global std, scriptArgs */` require 'quickjs/io' require 'quickjs/kernel'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/open-uri.rb
stdlib/open-uri.rb
# frozen_string_literal: true # backtick_javascript: true # Copied from https://raw.githubusercontent.com/ruby/ruby/373babeaac8c3e663e1ded74a9f06ac94a671ed9/lib/open-uri.rb require 'stringio' require 'corelib/array/pack' module Kernel private alias open_uri_original_open open # :nodoc: class << self alias open_uri_original_open open # :nodoc: end # Allows the opening of various resources including URIs. # # If the first argument responds to the 'open' method, 'open' is called on # it with the rest of the arguments. # # If the first argument is a string that begins with xxx://, it is parsed by # URI.parse. If the parsed object responds to the 'open' method, # 'open' is called on it with the rest of the arguments. # # Otherwise, the original Kernel#open is called. # # OpenURI::OpenRead#open provides URI::HTTP#open, URI::HTTPS#open and # URI::FTP#open, Kernel#open. # # We can accept URIs and strings that begin with http://, https:// and # ftp://. In these cases, the opened file object is extended by OpenURI::Meta. def open(name, *rest, &block) # :doc: if name.respond_to?(:to_str) && %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ name OpenURI.open_uri(name, *rest, &block) else open_uri_original_open(name, *rest, &block) end end module_function :open end # OpenURI is an easy-to-use wrapper for Net::HTTP, Net::HTTPS and Net::FTP. # # == Example # # It is possible to open an http, https or ftp URL as though it were a file: # # open("http://www.ruby-lang.org/") {|f| # f.each_line {|line| p line} # } # # The opened file has several getter methods for its meta-information, as # follows, since it is extended by OpenURI::Meta. # # open("http://www.ruby-lang.org/en") {|f| # f.each_line {|line| p line} # p f.base_uri # <URI::HTTP:0x40e6ef2 URL:http://www.ruby-lang.org/en/> # p f.content_type # "text/html" # p f.charset # "iso-8859-1" # p f.content_encoding # [] # p f.last_modified # Thu Dec 05 02:45:02 UTC 2002 # } # # Additional header fields can be specified by an optional hash argument. # # open("http://www.ruby-lang.org/en/", # "User-Agent" => "Ruby/#{RUBY_VERSION}", # "From" => "foo@bar.invalid", # "Referer" => "http://www.ruby-lang.org/") {|f| # # ... # } # # The environment variables such as http_proxy, https_proxy and ftp_proxy # are in effect by default. Here we disable proxy: # # open("http://www.ruby-lang.org/en/", :proxy => nil) {|f| # # ... # } # # See OpenURI::OpenRead.open and Kernel#open for more on available options. # # URI objects can be opened in a similar way. # # uri = URI.parse("http://www.ruby-lang.org/en/") # uri.open {|f| # # ... # } # # URI objects can be read directly. The returned string is also extended by # OpenURI::Meta. # # str = uri.read # p str.base_uri # # Author:: Tanaka Akira <akr@m17n.org> module OpenURI def self.open_uri(name, *rest) # :nodoc: io = open_loop(name, {}) io.rewind if block_given? begin yield io ensure close_io(io) end else io end end def self.close_io(io) if io.respond_to? :close! io.close! # Tempfile else io.close unless io.closed? end end def self.open_loop(uri, options) # :nodoc: req = request(uri) data = `req.responseText` status = `req.status` status_text = `req.statusText && req.statusText.errno ? req.statusText.errno : req.statusText` if status == 200 || (status == 0 && data) build_response(req, status, status_text) else raise OpenURI::HTTPError.new("#{status} #{status_text}", '') end end def self.build_response(req, status, status_text) buf = Buffer.new buf << data(req).pack('c*') io = buf.io #io.base_uri = uri # TODO: Generate a URI object from the uri String io.status = "#{status} #{status_text}" io.meta_add_field('content-type', `req.getResponseHeader("Content-Type") || ''`) last_modified = `req.getResponseHeader("Last-Modified")` io.meta_add_field('last-modified', last_modified) if last_modified io end def self.data(req) %x{ var binStr = req.responseText; var byteArray = []; for (var i = 0, len = binStr.length; i < len; ++i) { var c = binStr.charCodeAt(i); var byteCode = c & 0xff; // byte at offset i byteArray.push(byteCode); } return byteArray; } end def self.request(uri) %x{ try { var xhr = new XMLHttpRequest(); xhr.open('GET', uri, false); // We cannot use xhr.responseType = "arraybuffer" because XMLHttpRequest is used in synchronous mode. // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType#Synchronous_XHR_restrictions xhr.overrideMimeType('text/plain; charset=x-user-defined'); xhr.send(); return xhr; } catch (error) { #{raise OpenURI::HTTPError.new(`error.message`, '')} } } end class HTTPError < StandardError def initialize(message, io) super(message, io) @io = io end attr_reader :io end class Buffer # :nodoc: all def initialize @io = StringIO.new @size = 0 end attr_reader :size def <<(str) @io << str @size += str.length end def io Meta.init @io unless Meta === @io @io end end # Mixin for holding meta-information. module Meta def Meta.init(obj, src=nil) # :nodoc: obj.extend Meta obj.instance_eval { @base_uri = nil @meta = {} # name to string. legacy. @metas = {} # name to array of strings. } if src obj.status = src.status obj.base_uri = src.base_uri src.metas.each {|name, values| obj.meta_add_field2(name, values) } end end # returns an Array that consists of status code and message. attr_accessor :status # returns a URI that is the base of relative URIs in the data. # It may differ from the URI supplied by a user due to redirection. attr_accessor :base_uri # returns a Hash that represents header fields. # The Hash keys are downcased for canonicalization. # The Hash values are a field body. # If there are multiple field with same field name, # the field values are concatenated with a comma. attr_reader :meta # returns a Hash that represents header fields. # The Hash keys are downcased for canonicalization. # The Hash value are an array of field values. attr_reader :metas def meta_setup_encoding # :nodoc: charset = self.charset enc = find_encoding(charset) set_encoding(enc) end def set_encoding(enc) if self.respond_to? :force_encoding self.force_encoding(enc) elsif self.respond_to? :string self.string.force_encoding(enc) else # Tempfile self.set_encoding enc end end def find_encoding(charset) enc = nil if charset begin enc = Encoding.find(charset) rescue ArgumentError end end enc = Encoding::ASCII_8BIT unless enc enc end def meta_add_field2(name, values) # :nodoc: name = name.downcase @metas[name] = values @meta[name] = values.join(', ') meta_setup_encoding if name == 'content-type' end def meta_add_field(name, value) # :nodoc: meta_add_field2(name, [value]) end def last_modified if (vs = @metas['last-modified']) Time.at(`Date.parse(#{vs.join(', ')}) / 1000`).utc else nil end end def content_type_parse # :nodoc: content_type = @metas['content-type'] # FIXME Extract type, subtype and parameters content_type.join(', ') end # returns a charset parameter in Content-Type field. # It is downcased for canonicalization. # # If charset parameter is not given but a block is given, # the block is called and its result is returned. # It can be used to guess charset. # # If charset parameter and block is not given, # nil is returned except text type in HTTP. # In that case, "iso-8859-1" is returned as defined by RFC2616 3.7.1. def charset type = content_type_parse if type && %r{\Atext/} =~ type && @base_uri && /\Ahttp\z/i =~ @base_uri.scheme 'iso-8859-1' # RFC2616 3.7.1 else nil end end # returns "type/subtype" which is MIME Content-Type. # It is downcased for canonicalization. # Content-Type parameters are stripped. def content_type type = content_type_parse type || 'application/octet-stream' end end # Mixin for HTTP and FTP URIs. module OpenRead # OpenURI::OpenRead#open provides `open' for URI::HTTP and URI::FTP. # # OpenURI::OpenRead#open takes optional 3 arguments as: # # OpenURI::OpenRead#open([mode [, perm]] [, options]) [{|io| ... }] # # OpenURI::OpenRead#open returns an IO-like object if block is not given. # Otherwise it yields the IO object and return the value of the block. # The IO object is extended with OpenURI::Meta. # # +mode+ and +perm+ are the same as Kernel#open. # # However, +mode+ must be read mode because OpenURI::OpenRead#open doesn't # support write mode (yet). # Also +perm+ is ignored because it is meaningful only for file creation. # def open(*rest, &block) OpenURI.open_uri(self, *rest, &block) end # OpenURI::OpenRead#read([options]) reads a content referenced by self and # returns the content as string. # The string is extended with OpenURI::Meta. # The argument +options+ is same as OpenURI::OpenRead#open. def read(options={}) self.open(options) {|f| str = f.read Meta.init str, f str } end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/thread.rb
stdlib/thread.rb
# This shim implementation of Thread is meant to only appease code that tries # to be safe in the presence of threads, but does not actually utilize them, # e.g., uses thread- or fiber-local variables. class ThreadError < StandardError end class Thread def self.current unless @current @current = allocate @current.core_initialize! end @current end def self.list [current] end # Do not allow creation of new instances. def initialize(*args) raise NotImplementedError, 'Thread creation not available' end # fiber-local attribute access. def [](key) @fiber_locals[coerce_key_name(key)] end def []=(key, value) @fiber_locals[coerce_key_name(key)] = value end def key?(key) @fiber_locals.key?(coerce_key_name(key)) end def keys @fiber_locals.keys end # thread-local attribute access. def thread_variable_get(key) @thread_locals[coerce_key_name(key)] end def thread_variable_set(key, value) @thread_locals[coerce_key_name(key)] = value end def thread_variable?(key) @thread_locals.key?(coerce_key_name(key)) end def thread_variables @thread_locals.keys end private def core_initialize! @thread_locals = {} @fiber_locals = {} end def coerce_key_name(key) ::Opal.coerce_to!(key, String, :to_s) end class Queue def initialize clear end def clear @storage = [] end def empty? @storage.empty? end def size @storage.size end def pop(non_block = false) if empty? raise ThreadError, 'Queue empty' if non_block raise ThreadError, 'Deadlock' end @storage.shift end def push(value) @storage.push(value) end def each(&block) @storage.each(&block) end alias << push alias deq pop alias enq push alias length size alias shift pop end class Backtrace class Location def initialize(str) @str = str str =~ /^(.*?):(\d+):(\d+):in `(.*?)'$/ @path = Regexp.last_match(1) @label = Regexp.last_match(4) @lineno = Regexp.last_match(2).to_i @label =~ /(\w+)$/ @base_label = Regexp.last_match(1) || @label end def to_s @str end def inspect @str.inspect end attr_reader :base_label, :label, :lineno, :path # TODO: Make it somehow provide the absolute path. alias absolute_path path end end end Queue = Thread::Queue class Mutex def initialize # We still keep the @locked state so any logic based on try_lock while # held yields reasonable results. @locked = false end def lock raise ThreadError, 'Deadlock' if @locked @locked = true self end def locked? @locked end def owned? # Being the only "thread", we implicitly own any locked mutex. @locked end def try_lock if locked? false else lock true end end def unlock raise ThreadError, 'Mutex not locked' unless @locked @locked = false self end def synchronize lock begin yield ensure unlock end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/securerandom.rb
stdlib/securerandom.rb
# backtick_javascript: true require 'corelib/random/formatter' module SecureRandom extend Random::Formatter %x{ var gen_random_bytes; if ((Opal.global.crypto && Opal.global.crypto.getRandomValues) || (Opal.global.msCrypto && Opal.global.msCrypto.getRandomValues)) { // This method is available in all non-ancient web browsers. var crypto = Opal.global.crypto || Opal.global.msCrypto; gen_random_bytes = function(count) { var storage = new Uint8Array(count); crypto.getRandomValues(storage); return storage; }; } else if (Opal.global.crypto && Opal.global.crypto.randomBytes) { // This method is available in Node.js gen_random_bytes = function(count) { return Opal.global.crypto.randomBytes(count); }; } else { // Let's dangerously polyfill this interface with our MersenneTwister // xor native JS Math.random xor something about current time... // That's hardly secure, but the following warning should provide a person // deploying the code a good idea on what he should do to make his deployment // actually secure. // It's possible to interface other libraries by adding an else if above if // that's really desired. #{warn 'Can\'t get a Crypto.getRandomValues interface or Crypto.randomBytes.' \ 'The random values generated with SecureRandom won\'t be ' \ 'cryptographically secure'} gen_random_bytes = function(count) { var storage = new Uint8Array(count); for (var i = 0; i < count; i++) { storage[i] = #{rand(0xff)} ^ Math.floor(Math.random() * 256); storage[i] ^= +(new Date())>>#{rand(0xff)}&0xff; } return storage; } } } def self.bytes(bytes = nil) gen_random(bytes) end def self.gen_random(count = nil) count = Random._verify_count(count) out = '' %x{ var bytes = gen_random_bytes(#{count}); for (var i = 0; i < #{count}; i++) { out += String.fromCharCode(bytes[i]); } } out.encode('ASCII-8BIT') end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/js.rb
stdlib/js.rb
# backtick_javascript: true require 'opal/raw' warn '[Opal] JS module has been renamed to Opal::Raw and will change semantics in Opal 2.1. ' \ 'In addition, you will need to require "opal/raw" instead of "js". ' \ 'To ensure forward compatibility, please update your calls.' module JS extend Opal::Raw include Opal::Raw end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/optparse.rb
stdlib/optparse.rb
# frozen_string_literal: true # # optparse.rb - command-line option analysis with the OptionParser class. # # Author:: Nobu Nakada # Documentation:: Nobu Nakada and Gavin Sinclair. # # See OptionParser for documentation. # #-- # == Developer Documentation (not for RDoc output) # # === Class tree # # - OptionParser:: front end # - OptionParser::Switch:: each switches # - OptionParser::List:: options list # - OptionParser::ParseError:: errors on parsing # - OptionParser::AmbiguousOption # - OptionParser::NeedlessArgument # - OptionParser::MissingArgument # - OptionParser::InvalidOption # - OptionParser::InvalidArgument # - OptionParser::AmbiguousArgument # # === Object relationship diagram # # +--------------+ # | OptionParser |<>-----+ # +--------------+ | +--------+ # | ,-| Switch | # on_head -------->+---------------+ / +--------+ # accept/reject -->| List |<|>- # | |<|>- +----------+ # on ------------->+---------------+ `-| argument | # : : | class | # +---------------+ |==========| # on_tail -------->| | |pattern | # +---------------+ |----------| # OptionParser.accept ->| DefaultList | |converter | # reject |(shared between| +----------+ # | all instances)| # +---------------+ # #++ # # == OptionParser # # === New to \OptionParser? # # See the {Tutorial}[./doc/optparse/tutorial_rdoc.html]. # # === Introduction # # OptionParser is a class for command-line option analysis. It is much more # advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented # solution. # # === Features # # 1. The argument specification and the code to handle it are written in the # same place. # 2. It can output an option summary; you don't need to maintain this string # separately. # 3. Optional and mandatory arguments are specified very gracefully. # 4. Arguments can be automatically converted to a specified class. # 5. Arguments can be restricted to a certain set. # # All of these features are demonstrated in the examples below. See # #make_switch for full documentation. # # === Minimal example # # require 'optparse' # # options = {} # OptionParser.new do |parser| # parser.banner = "Usage: example.rb [options]" # # parser.on("-v", "--[no-]verbose", "Run verbosely") do |v| # options[:verbose] = v # end # end.parse! # # p options # p ARGV # # === Generating Help # # OptionParser can be used to automatically generate help for the commands you # write: # # require 'optparse' # # Options = Struct.new(:name) # # class Parser # def self.parse(options) # args = Options.new("world") # # opt_parser = OptionParser.new do |parser| # parser.banner = "Usage: example.rb [options]" # # parser.on("-nNAME", "--name=NAME", "Name to say hello to") do |n| # args.name = n # end # # parser.on("-h", "--help", "Prints this help") do # puts parser # exit # end # end # # opt_parser.parse!(options) # return args # end # end # options = Parser.parse %w[--help] # # #=> # # Usage: example.rb [options] # # -n, --name=NAME Name to say hello to # # -h, --help Prints this help # # === Required Arguments # # For options that require an argument, option specification strings may include an # option name in all caps. If an option is used without the required argument, # an exception will be raised. # # require 'optparse' # # options = {} # OptionParser.new do |parser| # parser.on("-r", "--require LIBRARY", # "Require the LIBRARY before executing your script") do |lib| # puts "You required #{lib}!" # end # end.parse! # # Used: # # $ ruby optparse-test.rb -r # optparse-test.rb:9:in `<main>': missing argument: -r (OptionParser::MissingArgument) # $ ruby optparse-test.rb -r my-library # You required my-library! # # === Type Coercion # # OptionParser supports the ability to coerce command line arguments # into objects for us. # # OptionParser comes with a few ready-to-use kinds of type # coercion. They are: # # - Date -- Anything accepted by +Date.parse+ # - DateTime -- Anything accepted by +DateTime.parse+ # - Time -- Anything accepted by +Time.httpdate+ or +Time.parse+ # - URI -- Anything accepted by +URI.parse+ # - Shellwords -- Anything accepted by +Shellwords.shellwords+ # - String -- Any non-empty string # - Integer -- Any integer. Will convert octal. (e.g. 124, -3, 040) # - Float -- Any float. (e.g. 10, 3.14, -100E+13) # - Numeric -- Any integer, float, or rational (1, 3.4, 1/3) # - DecimalInteger -- Like +Integer+, but no octal format. # - OctalInteger -- Like +Integer+, but no decimal format. # - DecimalNumeric -- Decimal integer or float. # - TrueClass -- Accepts '+, yes, true, -, no, false' and # defaults as +true+ # - FalseClass -- Same as +TrueClass+, but defaults to +false+ # - Array -- Strings separated by ',' (e.g. 1,2,3) # - Regexp -- Regular expressions. Also includes options. # # We can also add our own coercions, which we will cover below. # # ==== Using Built-in Conversions # # As an example, the built-in +Time+ conversion is used. The other built-in # conversions behave in the same way. # OptionParser will attempt to parse the argument # as a +Time+. If it succeeds, that time will be passed to the # handler block. Otherwise, an exception will be raised. # # require 'optparse' # require 'optparse/time' # OptionParser.new do |parser| # parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time| # p time # end # end.parse! # # Used: # # $ ruby optparse-test.rb -t nonsense # ... invalid argument: -t nonsense (OptionParser::InvalidArgument) # $ ruby optparse-test.rb -t 10-11-12 # 2010-11-12 00:00:00 -0500 # $ ruby optparse-test.rb -t 9:30 # 2014-08-13 09:30:00 -0400 # # ==== Creating Custom Conversions # # The +accept+ method on OptionParser may be used to create converters. # It specifies which conversion block to call whenever a class is specified. # The example below uses it to fetch a +User+ object before the +on+ handler receives it. # # require 'optparse' # # User = Struct.new(:id, :name) # # def find_user id # not_found = ->{ raise "No User Found for id #{id}" } # [ User.new(1, "Sam"), # User.new(2, "Gandalf") ].find(not_found) do |u| # u.id == id # end # end # # op = OptionParser.new # op.accept(User) do |user_id| # find_user user_id.to_i # end # # op.on("--user ID", User) do |user| # puts user # end # # op.parse! # # Used: # # $ ruby optparse-test.rb --user 1 # #<struct User id=1, name="Sam"> # $ ruby optparse-test.rb --user 2 # #<struct User id=2, name="Gandalf"> # $ ruby optparse-test.rb --user 3 # optparse-test.rb:15:in `block in find_user': No User Found for id 3 (RuntimeError) # # === Store options to a Hash # # The +into+ option of +order+, +parse+ and so on methods stores command line options into a Hash. # # require 'optparse' # # options = {} # OptionParser.new do |parser| # parser.on('-a') # parser.on('-b NUM', Integer) # parser.on('-v', '--verbose') # end.parse!(into: options) # # p options # # Used: # # $ ruby optparse-test.rb -a # {:a=>true} # $ ruby optparse-test.rb -a -v # {:a=>true, :verbose=>true} # $ ruby optparse-test.rb -a -b 100 # {:a=>true, :b=>100} # # === Complete example # # The following example is a complete Ruby program. You can run it and see the # effect of specifying various options. This is probably the best way to learn # the features of +optparse+. # # require 'optparse' # require 'optparse/time' # require 'ostruct' # require 'pp' # # class OptparseExample # Version = '1.0.0' # # CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary] # CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" } # # class ScriptOptions # attr_accessor :library, :inplace, :encoding, :transfer_type, # :verbose, :extension, :delay, :time, :record_separator, # :list # # def initialize # self.library = [] # self.inplace = false # self.encoding = "utf8" # self.transfer_type = :auto # self.verbose = false # end # # def define_options(parser) # parser.banner = "Usage: example.rb [options]" # parser.separator "" # parser.separator "Specific options:" # # # add additional options # perform_inplace_option(parser) # delay_execution_option(parser) # execute_at_time_option(parser) # specify_record_separator_option(parser) # list_example_option(parser) # specify_encoding_option(parser) # optional_option_argument_with_keyword_completion_option(parser) # boolean_verbose_option(parser) # # parser.separator "" # parser.separator "Common options:" # # No argument, shows at tail. This will print an options summary. # # Try it and see! # parser.on_tail("-h", "--help", "Show this message") do # puts parser # exit # end # # Another typical switch to print the version. # parser.on_tail("--version", "Show version") do # puts Version # exit # end # end # # def perform_inplace_option(parser) # # Specifies an optional option argument # parser.on("-i", "--inplace [EXTENSION]", # "Edit ARGV files in place", # "(make backup if EXTENSION supplied)") do |ext| # self.inplace = true # self.extension = ext || '' # self.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot. # end # end # # def delay_execution_option(parser) # # Cast 'delay' argument to a Float. # parser.on("--delay N", Float, "Delay N seconds before executing") do |n| # self.delay = n # end # end # # def execute_at_time_option(parser) # # Cast 'time' argument to a Time object. # parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time| # self.time = time # end # end # # def specify_record_separator_option(parser) # # Cast to octal integer. # parser.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger, # "Specify record separator (default \\0)") do |rs| # self.record_separator = rs # end # end # # def list_example_option(parser) # # List of arguments. # parser.on("--list x,y,z", Array, "Example 'list' of arguments") do |list| # self.list = list # end # end # # def specify_encoding_option(parser) # # Keyword completion. We are specifying a specific set of arguments (CODES # # and CODE_ALIASES - notice the latter is a Hash), and the user may provide # # the shortest unambiguous text. # code_list = (CODE_ALIASES.keys + CODES).join(', ') # parser.on("--code CODE", CODES, CODE_ALIASES, "Select encoding", # "(#{code_list})") do |encoding| # self.encoding = encoding # end # end # # def optional_option_argument_with_keyword_completion_option(parser) # # Optional '--type' option argument with keyword completion. # parser.on("--type [TYPE]", [:text, :binary, :auto], # "Select transfer type (text, binary, auto)") do |t| # self.transfer_type = t # end # end # # def boolean_verbose_option(parser) # # Boolean switch. # parser.on("-v", "--[no-]verbose", "Run verbosely") do |v| # self.verbose = v # end # end # end # # # # # Return a structure describing the options. # # # def parse(args) # # The options specified on the command line will be collected in # # *options*. # # @options = ScriptOptions.new # @args = OptionParser.new do |parser| # @options.define_options(parser) # parser.parse!(args) # end # @options # end # # attr_reader :parser, :options # end # class OptparseExample # # example = OptparseExample.new # options = example.parse(ARGV) # pp options # example.options # pp ARGV # # === Shell Completion # # For modern shells (e.g. bash, zsh, etc.), you can use shell # completion for command line options. # # === Further documentation # # The above examples, along with the accompanying # {Tutorial}[./doc/optparse/tutorial_rdoc.html], # should be enough to learn how to use this class. # If you have any questions, file a ticket at http://bugs.ruby-lang.org. # class OptionParser OptionParser::Version = '0.1.1' # :stopdoc: NoArgument = [NO_ARGUMENT = :NONE, nil].freeze RequiredArgument = [REQUIRED_ARGUMENT = :REQUIRED, true].freeze OptionalArgument = [OPTIONAL_ARGUMENT = :OPTIONAL, false].freeze # :startdoc: # # Keyword completion module. This allows partial arguments to be specified # and resolved against a list of acceptable values. # module Completion def self.regexp(key, icase) Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'), icase) end def self.candidate(key, icase = false, pat = nil, &block) pat ||= Completion.regexp(key, icase) candidates = [] block.call do |k, *v| (if Regexp === k kn = '' k === key else kn = defined?(k.id2name) ? k.id2name : k pat === kn end) || next v << k if v.empty? candidates << [k, v, kn] end candidates end def candidate(key, icase = false, pat = nil) Completion.candidate(key, icase, pat, &method(:each)) end public def complete(key, icase = false, pat = nil) candidates = candidate(key, icase, pat, &method(:each)).sort_by { |k, v, kn| kn.size } if candidates.size == 1 canon, sw, * = candidates[0] elsif candidates.size > 1 canon, sw, cn = candidates.shift candidates.each do |k, v, kn| next if sw == v if (String === cn) && (String === kn) if cn.rindex(kn, 0) canon, sw, cn = k, v, kn next elsif kn.rindex(cn, 0) next end end throw :ambiguous, key end end if canon block_given? || (return key, *sw) yield(key, *sw) end end def convert(opt = nil, val = nil, *) val end end # # Map from option/keyword string to object with completion. # class OptionMap < Hash include Completion end # # Individual switch class. Not important to the user. # # Defined within Switch are several Switch-derived classes: NoArgument, # RequiredArgument, etc. # class Switch attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block # # Guesses argument style from +arg+. Returns corresponding # OptionParser::Switch class (OptionalArgument, etc.). # def self.guess(arg) case arg when '' t = self when /\A=?\[/ t = Switch::OptionalArgument when /\A\s+\[/ t = Switch::PlacedArgument else t = Switch::RequiredArgument end (self >= t) || incompatible_argument_styles(arg, t) t end def self.incompatible_argument_styles(arg, t) raise(ArgumentError, "#{arg}: incompatible argument styles\n #{self}, #{t}", ParseError.filter_backtrace(caller(2)) ) end def self.pattern NilClass end def initialize(pattern = nil, conv = nil, short = nil, long = nil, arg = nil, desc = ([] if short || long), block = nil, &_block) raise if Array === pattern block ||= _block @pattern, @conv, @short, @long, @arg, @desc, @block = pattern, conv, short, long, arg, desc, block end # # Parses +arg+ and returns rest of +arg+ and matched portion to the # argument pattern. Yields when the pattern doesn't match substring. # def parse_arg(arg) # :nodoc: pattern || (return nil, [arg]) unless m = pattern.match(arg) yield(InvalidArgument, arg) return arg, [] end if String === m m = [s = m] else m = m.to_a s = m[0] return nil, m unless String === s end raise InvalidArgument, arg unless arg.rindex(s, 0) return nil, m if s.length == arg.length yield(InvalidArgument, arg) # didn't match whole arg [arg[s.length..-1], m] end private :parse_arg # # Parses argument, converts and returns +arg+, +block+ and result of # conversion. Yields at semi-error condition instead of raising an # exception. # def conv_arg(arg, val = []) # :nodoc: if conv val = conv.call(*val) else val = proc { |v| v }.call(*val) end [arg, block, val] end private :conv_arg # # Produces the summary text. Each line of the summary is yielded to the # block (without newline). # # +sdone+:: Already summarized short style options keyed hash. # +ldone+:: Already summarized long style options keyed hash. # +width+:: Width of left side (option part). In other words, the right # side (description part) starts after +width+ columns. # +max+:: Maximum width of left side -> the options are filled within # +max+ columns. # +indent+:: Prefix string indents all summarized lines. # def summarize(sdone = {}, ldone = {}, width = 1, max = width - 1, indent = '') sopts, lopts = [], [], nil @short.each { |s| sdone.fetch(s) { sopts << s }; sdone[s] = true } if @short @long.each { |s| ldone.fetch(s) { lopts << s }; ldone[s] = true } if @long return if sopts.empty? && lopts.empty? # completely hidden left = [sopts.join(', ')] right = desc.dup while s = lopts.shift l = left[-1].length + s.length l += arg.length if left.size == 1 && arg (l < max) || sopts.empty? || left << +'' left[-1] += (left[-1].empty? ? ' ' * 4 : ', ') + s end if arg left[0] += (left[1] ? arg.sub(/\A(\[?)=/, '\1') + ',' : arg) end mlen = left.collect(&:length).max.to_i while (mlen > width) && (l = left.shift) mlen = left.collect(&:length).max.to_i if l.length == mlen if (l.length < width) && (r = right[0]) && !r.empty? l = l.to_s.ljust(width) + ' ' + r right.shift end yield(indent + l) end while begin l = left.shift; r = right.shift; l || r end l = l.to_s.ljust(width) + ' ' + r if r && !r.empty? yield(indent + l) end self end def add_banner(to) # :nodoc: unless @short || @long s = desc.join to << ' [' + s + ']...' unless s.empty? end to end def match_nonswitch?(str) # :nodoc: @pattern =~ str unless @short || @long end # # Main name of the switch. # def switch_name (long.first || short.first).sub(/\A-+(?:\[no-\])?/, '') end def compsys(sdone, ldone) # :nodoc: sopts, lopts = [], [] @short.each { |s| sdone.fetch(s) { sopts << s }; sdone[s] = true } if @short @long.each { |s| ldone.fetch(s) { lopts << s }; ldone[s] = true } if @long return if sopts.empty? && lopts.empty? # completely hidden (sopts + lopts).each do |opt| # "(-x -c -r)-l[left justify]" if /^--\[no-\](.+)$/ =~ opt o = Regexp.last_match(1) yield("--#{o}", desc.join('')) yield("--no-#{o}", desc.join('')) else yield(opt.to_s, desc.join('')) end end end # # Switch that takes no arguments. # class NoArgument < self # # Raises an exception if any arguments given. # def parse(arg, argv) yield(NeedlessArgument, arg) if arg conv_arg(arg) end def self.incompatible_argument_styles(*) end def self.pattern Object end end # # Switch that takes an argument. # class RequiredArgument < self # # Raises an exception if argument is not present. # def parse(arg, argv) unless arg raise MissingArgument if argv.empty? arg = argv.shift end conv_arg(*parse_arg(arg, &method(:raise))) end end # # Switch that can omit argument. # class OptionalArgument < self # # Parses argument if given, or uses default value. # def parse(arg, argv, &error) if arg conv_arg(*parse_arg(arg, &error)) else conv_arg(arg) end end end # # Switch that takes an argument, which does not begin with '-'. # class PlacedArgument < self # # Returns nil if argument is not present or begins with '-'. # def parse(arg, argv, &error) if !(val = arg) && (argv.empty? || /\A-/ =~ (val = argv[0])) return nil, block, nil end opt = (val = parse_arg(val, &error))[1] val = conv_arg(*val) if opt && !arg argv.shift else val[0] = nil end val end end end # # Simple option list providing mapping from short and/or long option # string to OptionParser::Switch and mapping from acceptable argument to # matching pattern and converter pair. Also provides summary feature. # class List # Map from acceptable argument types to pattern and converter pairs. attr_reader :atype # Map from short style option switches to actual switch objects. attr_reader :short # Map from long style option switches to actual switch objects. attr_reader :long # List of all switches and summary string. attr_reader :list # # Just initializes all instance variables. # def initialize @atype = {} @short = OptionMap.new @long = OptionMap.new @list = [] end # # See OptionParser.accept. # def accept(t, pat = /.*/m, &block) if pat pat.respond_to?(:match) || raise(TypeError, "has no `match'", ParseError.filter_backtrace(caller(2))) else pat = t if t.respond_to?(:match) end unless block block = pat.method(:convert).to_proc if pat.respond_to?(:convert) end @atype[t] = [pat, block] end # # See OptionParser.reject. # def reject(t) @atype.delete(t) end # # Adds +sw+ according to +sopts+, +lopts+ and +nlopts+. # # +sw+:: OptionParser::Switch instance to be added. # +sopts+:: Short style option list. # +lopts+:: Long style option list. # +nlopts+:: Negated long style options list. # def update(sw, sopts, lopts, nsw = nil, nlopts = nil) # :nodoc: sopts.each { |o| @short[o] = sw } if sopts lopts.each { |o| @long[o] = sw } if lopts nlopts.each { |o| @long[o] = nsw } if nsw && nlopts used = @short.invert.update(@long.invert) @list.delete_if { |o| (Switch === o) && !used[o] } end private :update # # Inserts +switch+ at the head of the list, and associates short, long # and negated long options. Arguments are: # # +switch+:: OptionParser::Switch instance to be inserted. # +short_opts+:: List of short style options. # +long_opts+:: List of long style options. # +nolong_opts+:: List of long style options with "no-" prefix. # # prepend(switch, short_opts, long_opts, nolong_opts) # def prepend(*args) update(*args) @list.unshift(args[0]) end # # Appends +switch+ at the tail of the list, and associates short, long # and negated long options. Arguments are: # # +switch+:: OptionParser::Switch instance to be inserted. # +short_opts+:: List of short style options. # +long_opts+:: List of long style options. # +nolong_opts+:: List of long style options with "no-" prefix. # # append(switch, short_opts, long_opts, nolong_opts) # def append(*args) update(*args) @list.push(args[0]) end # # Searches +key+ in +id+ list. The result is returned or yielded if a # block is given. If it isn't found, nil is returned. # def search(id, key) if list = __send__(id) val = list.fetch(key) { return nil } block_given? ? yield(val) : val end end # # Searches list +id+ for +opt+ and the optional patterns for completion # +pat+. If +icase+ is true, the search is case insensitive. The result # is returned or yielded if a block is given. If it isn't found, nil is # returned. # def complete(id, opt, icase = false, *pat, &block) __send__(id).complete(opt, icase, *pat, &block) end def get_candidates(id) yield __send__(id).keys end # # Iterates over each option, passing the option to the +block+. # def each_option(&block) list.each(&block) end # # Creates the summary table, passing each line to the +block+ (without # newline). The arguments +args+ are passed along to the summarize # method which is called on every option. # def summarize(*args, &block) sum = [] list.reverse_each do |opt| if opt.respond_to?(:summarize) # perhaps OptionParser::Switch s = [] opt.summarize(*args) { |l| s << l } sum.concat(s.reverse) elsif !opt || opt.empty? sum << '' elsif opt.respond_to?(:each_line) sum.concat([*opt.each_line].reverse) else sum.concat([*opt.each].reverse) end end sum.reverse_each(&block) end def add_banner(to) # :nodoc: list.each do |opt| if opt.respond_to?(:add_banner) opt.add_banner(to) end end to end def compsys(*args, &block) # :nodoc: list.each do |opt| if opt.respond_to?(:compsys) opt.compsys(*args, &block) end end end end # # Hash with completion search feature. See OptionParser::Completion. # class CompletingHash < Hash include Completion # # Completion for hash key. # def match(key) *values = fetch(key) do raise AmbiguousArgument, catch(:ambiguous) { return complete(key) } end [key, *values] end end # :stopdoc: # # Enumeration of acceptable argument styles. Possible values are: # # NO_ARGUMENT:: The switch takes no arguments. (:NONE) # REQUIRED_ARGUMENT:: The switch requires an argument. (:REQUIRED) # OPTIONAL_ARGUMENT:: The switch requires an optional argument. (:OPTIONAL) # # Use like --switch=argument (long style) or -Xargument (short style). For # short style, only portion matched to argument pattern is treated as # argument. # ArgumentStyle = {} NoArgument.each { |el| ArgumentStyle[el] = Switch::NoArgument } RequiredArgument.each { |el| ArgumentStyle[el] = Switch::RequiredArgument } OptionalArgument.each { |el| ArgumentStyle[el] = Switch::OptionalArgument } ArgumentStyle.freeze # # Switches common used such as '--', and also provides default # argument classes # DefaultList = List.new DefaultList.short['-'] = Switch::NoArgument.new {} DefaultList.long[''] = Switch::NoArgument.new { throw :terminate } COMPSYS_HEADER = <<'XXX' # :nodoc: typeset -A opt_args local context state line _arguments -s -S \ XXX def compsys(to, name = File.basename($0)) # :nodoc: to << "#compdef #{name}\n" to << COMPSYS_HEADER visit(:compsys, {}, {}) do |o, d| to << %[ "#{o}[#{d.gsub(/[\"\[\]]/, '\\\\\&')}]" \\\n] end to << " '*:file:_files' && return 0\n" end # # Default options for ARGV, which never appear in option summary. # Officious = {} # # --help # Shows option summary. # Officious['help'] = proc do |parser| Switch::NoArgument.new do |arg| puts parser.help exit end end # # --*-completion-bash=WORD # Shows candidates for command line completion. # Officious['*-completion-bash'] = proc do |parser| Switch::RequiredArgument.new do |arg| puts parser.candidate(arg) exit end end # # --*-completion-zsh[=NAME:FILE] # Creates zsh completion file. # Officious['*-completion-zsh'] = proc do |parser| Switch::OptionalArgument.new do |arg| parser.compsys(STDOUT, arg) exit end end # # --version # Shows version string if Version is defined. # Officious['version'] = proc do |parser| Switch::OptionalArgument.new do |pkg| if pkg begin require 'optparse/version' rescue LoadError else show_version(*pkg.split(/,/)) || abort("#{parser.program_name}: no version found in package #{pkg}") exit end end (v = parser.ver) || abort("#{parser.program_name}: version unknown") puts v exit end end # :startdoc: # # Class methods # # # Initializes a new instance and evaluates the optional block in context # of the instance. Arguments +args+ are passed to #new, see there for # description of parameters. # # This method is *deprecated*, its behavior corresponds to the older #new # method. # def self.with(*args, &block) opts = new(*args) opts.instance_eval(&block) opts end # # Returns an incremented value of +default+ according to +arg+. # def self.inc(arg, default = nil) case arg when Integer arg.nonzero? when nil default.to_i + 1 end end def inc(*args) self.class.inc(*args) end # # Initializes the instance and yields itself if called with a block. # # +banner+:: Banner message. # +width+:: Summary width. # +indent+:: Summary indent. # def initialize(banner = nil, width = 32, indent = ' ' * 4) @stack = [DefaultList, List.new, List.new] @program_name = nil @banner = banner @summary_width = width @summary_indent = indent @default_argv = ARGV @require_exact = false add_officious yield self if block_given? end def add_officious # :nodoc: list = base Officious.each do |opt, block| list.long[opt] ||= block.call(self) end end # # Terminates option parsing. Optional parameter +arg+ is a string pushed # back to be the first non-option argument. # def terminate(arg = nil) self.class.terminate(arg) end def self.terminate(arg = nil) throw :terminate, arg end @stack = [DefaultList] def self.top DefaultList end # # Directs to accept specified class +t+. The argument string is passed to # the block in which it should be converted to the desired class. # # +t+:: Argument class specifier, any object including Class. # +pat+:: Pattern for argument, defaults to +t+ if it responds to match. # # accept(t, pat, &block) # def accept(*args, &blk) top.accept(*args, &blk) end # # See #accept. # def self.accept(*args, &blk) top.accept(*args, &blk) end # # Directs to reject specified class argument. # # +t+:: Argument class specifier, any object including Class. # # reject(t) # def reject(*args, &blk) top.reject(*args, &blk) end # # See #reject. # def self.reject(*args, &blk) top.reject(*args, &blk) end # # Instance methods # # Heading banner preceding summary. attr_writer :banner # Program name to be emitted in error message and default banner, # defaults to $0. attr_writer :program_name # Width for option list portion of summary. Must be Numeric. attr_accessor :summary_width # Indentation for summary. Must be String (or have + String method). attr_accessor :summary_indent # Strings to be parsed in default. attr_accessor :default_argv # Whether to require that options match exactly (disallows providing
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
true
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/stringio.rb
stdlib/stringio.rb
class StringIO < IO VERSION = "0" def self.open(string = "", mode = nil, &block) io = new(string, mode) res = block.call(io) io.close res end attr_accessor :string def initialize(string = "", mode = 'rw') @string = string @position = 0 super(nil, mode) end def eof? check_readable @position == @string.length end def seek(pos, whence = IO::SEEK_SET) # Let's reset the read buffer, because it will be most likely wrong @read_buffer = '' case whence when IO::SEEK_SET raise Errno::EINVAL unless pos >= 0 @position = pos when IO::SEEK_CUR if @position + pos > @string.length @position = @string.length else @position += pos end when IO::SEEK_END if pos > @string.length @position = 0 else @position -= pos end end 0 end def tell @position end def rewind seek 0 end def write(string) check_writable # Let's reset the read buffer, because it will be most likely wrong @read_buffer = '' string = String(string) if @string.length == @position @string += string @position += string.length else before = @string[0 .. @position - 1] after = @string[@position + string.length .. -1] @string = before + string + after @position += string.length end end def read(length = nil, outbuf = nil) check_readable return if eof? string = if length str = @string[@position, length] @position += length @position = @string.length if @position > @string.length str else str = @string[@position .. -1] @position = @string.length str end if outbuf outbuf.write(string) else string end end def sysread(length) check_readable read(length) end alias eof eof? alias pos tell alias pos= seek alias readpartial read end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/logger.rb
stdlib/logger.rb
# backtick_javascript: true class Logger module Severity DEBUG = 0 INFO = 1 WARN = 2 ERROR = 3 FATAL = 4 UNKNOWN = 5 end include Severity SEVERITY_LABELS = Severity.constants.map { |s| [(Severity.const_get s), s.to_s] }.to_h class Formatter MESSAGE_FORMAT = "%s, [%s] %5s -- %s: %s\n" DATE_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%6N' def call(severity, time, progname, msg) format(MESSAGE_FORMAT, severity.chr, time.strftime(DATE_TIME_FORMAT), severity, progname, message_as_string(msg)) end def message_as_string(msg) case msg when ::String msg when ::Exception msg.full_message else msg.inspect end end end attr_reader :level attr_accessor :progname attr_accessor :formatter def initialize(pipe, level: DEBUG, progname: nil, formatter: nil) @pipe = pipe @level = level @formatter = formatter || Formatter.new @progname = progname end def level=(severity) if ::Integer === severity @level = severity elsif (level = SEVERITY_LABELS.key(severity.to_s.upcase)) @level = level else raise ArgumentError, "invalid log level: #{severity}" end end def info(progname = nil, &block) add INFO, nil, progname, &block end def debug(progname = nil, &block) add DEBUG, nil, progname, &block end def warn(progname = nil, &block) add WARN, nil, progname, &block end def error(progname = nil, &block) add ERROR, nil, progname, &block end def fatal(progname = nil, &block) add FATAL, nil, progname, &block end def unknown(progname = nil, &block) add UNKNOWN, nil, progname, &block end def info? @level <= INFO end def debug? @level <= DEBUG end def warn? @level <= WARN end def error? @level <= ERROR end def fatal? @level <= FATAL end def add(severity, message = nil, progname = nil, &block) return true if (severity ||= UNKNOWN) < @level progname ||= @progname unless message if block_given? message = yield else message = progname progname = @progname end end @pipe.write(@formatter.call(SEVERITY_LABELS[severity] || 'ANY', ::Time.now, progname, message)) true end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/ruby2_keywords.rb
stdlib/ruby2_keywords.rb
# This file ended up in Opal as a port of: # https://github.com/ruby/ruby2_keywords/blob/master/lib/ruby2_keywords.rb class Module unless private_method_defined?(:ruby2_keywords) private # call-seq: # ruby2_keywords(method_name, ...) # # Does nothing. def ruby2_keywords(name, *) # nil end end end main = TOPLEVEL_BINDING.eval('self') unless main.respond_to?(:ruby2_keywords, true) # call-seq: # ruby2_keywords(method_name, ...) # # Does nothing. def main.ruby2_keywords(name, *) # nil end end class Proc unless method_defined?(:ruby2_keywords) # call-seq: # proc.ruby2_keywords -> proc # # Does nothing and just returns the receiver. def ruby2_keywords self end end end class << Hash unless method_defined?(:ruby2_keywords_hash?) # call-seq: # Hash.ruby2_keywords_hash?(hash) -> false # # Returns false. def ruby2_keywords_hash?(hash) false end end unless method_defined?(:ruby2_keywords_hash) # call-seq: # Hash.ruby2_keywords_hash(hash) -> new_hash # # Duplicates a given hash and returns the new hash. def ruby2_keywords_hash(hash) hash.dup end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/opal-source-maps.rb
stdlib/opal-source-maps.rb
require 'opal/source_map'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/ostruct.rb
stdlib/ostruct.rb
# backtick_javascript: true class OpenStruct def initialize(hash = nil) @table = {} if hash hash.each_pair do |key, value| @table[new_ostruct_member(key)] = value end end end def [](name) @table[name.to_sym] end def []=(name, value) @table[new_ostruct_member(name)] = value end def method_missing(name, *args) if args.length > 2 raise NoMethodError.new("undefined method `#{name}' for #<OpenStruct>", name) end if name.end_with? '=' if args.length != 1 raise ArgumentError, 'wrong number of arguments (0 for 1)' end @table[new_ostruct_member(name[0..-2])] = args[0] else @table[name.to_sym] end end def respond_to_missing?(mid, include_private = false) # :nodoc: mname = mid.to_s.chomp('=').to_sym @table&.key?(mname) || super end def each_pair return enum_for :each_pair unless block_given? @table.each_pair do |pair| yield pair end end def ==(other) return false unless other.is_a?(OpenStruct) @table == other.instance_variable_get(:@table) end def ===(other) return false unless other.is_a?(OpenStruct) @table === other.instance_variable_get(:@table) end def eql?(other) return false unless other.is_a?(OpenStruct) @table.eql? other.instance_variable_get(:@table) end def to_h(&block) block_given? ? @table.to_h(&block) : @table.dup end def to_n @table.to_n end def hash @table.hash end attr_reader :table def delete_field(name) sym = name.to_sym begin singleton_class.__send__(:remove_method, sym, "#{sym}=") rescue NameError end @table.delete sym end def new_ostruct_member(name) name = name.to_sym unless respond_to?(name) define_singleton_method(name) { @table[name] } define_singleton_method("#{name}=") { |x| @table[name] = x } end name end def freeze @table.freeze super end def initialize_dup(copy) @table = @table.dup if @table.frozen? end `var ostruct_ids;` def inspect %x{ var top = (ostruct_ids === undefined), ostruct_id = #{__id__}; } begin result = "#<#{self.class}" %x{ if (top) { ostruct_ids = {}; } if (ostruct_ids.hasOwnProperty(ostruct_id)) { return result + ' ...>'; } ostruct_ids[ostruct_id] = true; } result += ' ' if @table.any? result += each_pair.map do |name, value| "#{name}=#{value.inspect}" end.join ', ' result += '>' result ensure %x{ if (top) { ostruct_ids = undefined; } } end end alias to_s inspect end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/benchmark.rb
stdlib/benchmark.rb
#-- # benchmark.rb - a performance benchmarking library # # $Id$ # # Created by Gotoken (gotoken@notwork.org). # # Documentation by Gotoken (original RD), Lyle Johnson (RDoc conversion), and # Gavin Sinclair (editing). #++ # # == Overview # # The Benchmark module provides methods for benchmarking Ruby code, giving # detailed reports on the time taken for each task. # # The Benchmark module provides methods to measure and report the time # used to execute Ruby code. # # * Measure the time to construct the string given by the expression # <code>"a"*1_000_000_000</code>: # # require 'benchmark' # # puts Benchmark.measure { "a"*1_000_000_000 } # # On my machine (OSX 10.8.3 on i5 1.7 Ghz) this generates: # # 0.350000 0.400000 0.750000 ( 0.835234) # # This report shows the user CPU time, system CPU time, the sum of # the user and system CPU times, and the elapsed real time. The unit # of time is seconds. # # * Do some experiments sequentially using the #bm method: # # require 'benchmark' # # n = 5000000 # Benchmark.bm do |x| # x.report { for i in 1..n; a = "1"; end } # x.report { n.times do ; a = "1"; end } # x.report { 1.upto(n) do ; a = "1"; end } # end # # The result: # # user system total real # 1.010000 0.000000 1.010000 ( 1.014479) # 1.000000 0.000000 1.000000 ( 0.998261) # 0.980000 0.000000 0.980000 ( 0.981335) # # * Continuing the previous example, put a label in each report: # # require 'benchmark' # # n = 5000000 # Benchmark.bm(7) do |x| # x.report("for:") { for i in 1..n; a = "1"; end } # x.report("times:") { n.times do ; a = "1"; end } # x.report("upto:") { 1.upto(n) do ; a = "1"; end } # end # # The result: # # user system total real # for: 1.010000 0.000000 1.010000 ( 1.015688) # times: 1.000000 0.000000 1.000000 ( 1.003611) # upto: 1.030000 0.000000 1.030000 ( 1.028098) # # * The times for some benchmarks depend on the order in which items # are run. These differences are due to the cost of memory # allocation and garbage collection. To avoid these discrepancies, # the #bmbm method is provided. For example, to compare ways to # sort an array of floats: # # require 'benchmark' # # array = (1..1000000).map { rand } # # Benchmark.bmbm do |x| # x.report("sort!") { array.dup.sort! } # x.report("sort") { array.dup.sort } # end # # The result: # # Rehearsal ----------------------------------------- # sort! 1.490000 0.010000 1.500000 ( 1.490520) # sort 1.460000 0.000000 1.460000 ( 1.463025) # -------------------------------- total: 2.960000sec # # user system total real # sort! 1.460000 0.000000 1.460000 ( 1.460465) # sort 1.450000 0.010000 1.460000 ( 1.448327) # # * Report statistics of sequential experiments with unique labels, # using the #benchmark method: # # require 'benchmark' # include Benchmark # we need the CAPTION and FORMAT constants # # n = 5000000 # Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x| # tf = x.report("for:") { for i in 1..n; a = "1"; end } # tt = x.report("times:") { n.times do ; a = "1"; end } # tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end } # [tf+tt+tu, (tf+tt+tu)/3] # end # # The result: # # user system total real # for: 0.950000 0.000000 0.950000 ( 0.952039) # times: 0.980000 0.000000 0.980000 ( 0.984938) # upto: 0.950000 0.000000 0.950000 ( 0.946787) # >total: 2.880000 0.000000 2.880000 ( 2.883764) # >avg: 0.960000 0.000000 0.960000 ( 0.961255) module Benchmark BENCHMARK_VERSION = "2002-04-25" # :nodoc: # Invokes the block with a Benchmark::Report object, which # may be used to collect and report on the results of individual # benchmark tests. Reserves +label_width+ leading spaces for # labels on each line. Prints +caption+ at the top of the # report, and uses +format+ to format each line. # Returns an array of Benchmark::Tms objects. # # If the block returns an array of # Benchmark::Tms objects, these will be used to format # additional lines of output. If +label+ parameters are # given, these are used to label these extra lines. # # _Note_: Other methods provide a simpler interface to this one, and are # suitable for nearly all benchmarking requirements. See the examples in # Benchmark, and the #bm and #bmbm methods. # # Example: # # require 'benchmark' # include Benchmark # we need the CAPTION and FORMAT constants # # n = 5000000 # Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x| # tf = x.report("for:") { for i in 1..n; a = "1"; end } # tt = x.report("times:") { n.times do ; a = "1"; end } # tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end } # [tf+tt+tu, (tf+tt+tu)/3] # end # # Generates: # # user system total real # for: 0.970000 0.000000 0.970000 ( 0.970493) # times: 0.990000 0.000000 0.990000 ( 0.989542) # upto: 0.970000 0.000000 0.970000 ( 0.972854) # >total: 2.930000 0.000000 2.930000 ( 2.932889) # >avg: 0.976667 0.000000 0.976667 ( 0.977630) # def benchmark(caption = "", label_width = nil, format = nil, *labels) # :yield: report sync = STDOUT.sync STDOUT.sync = true label_width ||= 0 label_width += 1 format ||= FORMAT print ' '*label_width + caption unless caption.empty? report = Report.new(label_width, format) results = yield(report) Array === results and results.grep(Tms).each {|t| print((labels.shift || t.label || "").ljust(label_width), t.format(format)) } report.list ensure STDOUT.sync = sync unless sync.nil? end # A simple interface to the #benchmark method, #bm generates sequential # reports with labels. The parameters have the same meaning as for # #benchmark. # # require 'benchmark' # # n = 5000000 # Benchmark.bm(7) do |x| # x.report("for:") { for i in 1..n; a = "1"; end } # x.report("times:") { n.times do ; a = "1"; end } # x.report("upto:") { 1.upto(n) do ; a = "1"; end } # end # # Generates: # # user system total real # for: 0.960000 0.000000 0.960000 ( 0.957966) # times: 0.960000 0.000000 0.960000 ( 0.960423) # upto: 0.950000 0.000000 0.950000 ( 0.954864) # def bm(label_width = 0, *labels, &blk) # :yield: report benchmark(CAPTION, label_width, FORMAT, *labels, &blk) end # Sometimes benchmark results are skewed because code executed # earlier encounters different garbage collection overheads than # that run later. #bmbm attempts to minimize this effect by running # the tests twice, the first time as a rehearsal in order to get the # runtime environment stable, the second time for # real. GC.start is executed before the start of each of # the real timings; the cost of this is not included in the # timings. In reality, though, there's only so much that #bmbm can # do, and the results are not guaranteed to be isolated from garbage # collection and other effects. # # Because #bmbm takes two passes through the tests, it can # calculate the required label width. # # require 'benchmark' # # array = (1..1000000).map { rand } # # Benchmark.bmbm do |x| # x.report("sort!") { array.dup.sort! } # x.report("sort") { array.dup.sort } # end # # Generates: # # Rehearsal ----------------------------------------- # sort! 1.440000 0.010000 1.450000 ( 1.446833) # sort 1.440000 0.000000 1.440000 ( 1.448257) # -------------------------------- total: 2.890000sec # # user system total real # sort! 1.460000 0.000000 1.460000 ( 1.458065) # sort 1.450000 0.000000 1.450000 ( 1.455963) # # #bmbm yields a Benchmark::Job object and returns an array of # Benchmark::Tms objects. # def bmbm(width = 0) # :yield: job job = Job.new(width) yield(job) width = job.width + 1 sync = STDOUT.sync STDOUT.sync = true # rehearsal puts 'Rehearsal '.ljust(width+CAPTION.length,'-') ets = job.list.inject(Tms.new) { |sum,(label,item)| print label.ljust(width) res = Benchmark.measure(&item) print res.format sum + res }.format("total: %tsec") print " #{ets}\n\n".rjust(width+CAPTION.length+2,'-') # take print ' '*width + CAPTION job.list.map { |label,item| GC.start print label.ljust(width) Benchmark.measure(label, &item).tap { |res| print res } } ensure STDOUT.sync = sync unless sync.nil? end # :stopdoc: case when defined?(Process::CLOCK_MONOTONIC) BENCHMARK_CLOCK = Process::CLOCK_MONOTONIC else BENCHMARK_CLOCK = Process::CLOCK_REALTIME end # :startdoc: # # Returns the time used to execute the given block as a # Benchmark::Tms object. # def measure(label = "") # :yield: t0, r0 = Process.times, Process.clock_gettime(BENCHMARK_CLOCK) yield t1, r1 = Process.times, Process.clock_gettime(BENCHMARK_CLOCK) Benchmark::Tms.new(t1.utime - t0.utime, t1.stime - t0.stime, t1.cutime - t0.cutime, t1.cstime - t0.cstime, r1 - r0, label) end # # Returns the elapsed real time used to execute the given block. # def realtime # :yield: r0 = Process.clock_gettime(BENCHMARK_CLOCK) yield Process.clock_gettime(BENCHMARK_CLOCK) - r0 end module_function :benchmark, :measure, :realtime, :bm, :bmbm # # A Job is a sequence of labelled blocks to be processed by the # Benchmark.bmbm method. It is of little direct interest to the user. # class Job # :nodoc: # # Returns an initialized Job instance. # Usually, one doesn't call this method directly, as new # Job objects are created by the #bmbm method. # +width+ is a initial value for the label offset used in formatting; # the #bmbm method passes its +width+ argument to this constructor. # def initialize(width) @width = width @list = [] end # # Registers the given label and block pair in the job list. # def item(label = "", &blk) # :yield: raise ArgumentError, "no block" unless block_given? label = label.to_s w = label.length @width = w if @width < w @list << [label, blk] self end alias report item # An array of 2-element arrays, consisting of label and block pairs. attr_reader :list # Length of the widest label in the #list. attr_reader :width end # # This class is used by the Benchmark.benchmark and Benchmark.bm methods. # It is of little direct interest to the user. # class Report # :nodoc: # # Returns an initialized Report instance. # Usually, one doesn't call this method directly, as new # Report objects are created by the #benchmark and #bm methods. # +width+ and +format+ are the label offset and # format string used by Tms#format. # def initialize(width = 0, format = nil) @width, @format, @list = width, format, [] end # # Prints the +label+ and measured time for the block, # formatted by +format+. See Tms#format for the # formatting rules. # def item(label = "", *format, &blk) # :yield: print label.to_s.ljust(@width) @list << res = Benchmark.measure(label, &blk) print res.format(@format, *format) res end alias report item # An array of Benchmark::Tms objects representing each item. attr_reader :list end # # A data object, representing the times associated with a benchmark # measurement. # class Tms # Default caption, see also Benchmark::CAPTION CAPTION = " user system total real\n" # Default format string, see also Benchmark::FORMAT FORMAT = "%10.6u %10.6y %10.6t %10.6r\n" # User CPU time attr_reader :utime # System CPU time attr_reader :stime # User CPU time of children attr_reader :cutime # System CPU time of children attr_reader :cstime # Elapsed real time attr_reader :real # Total time, that is +utime+ + +stime+ + +cutime+ + +cstime+ attr_reader :total # Label attr_reader :label # # Returns an initialized Tms object which has # +utime+ as the user CPU time, +stime+ as the system CPU time, # +cutime+ as the children's user CPU time, +cstime+ as the children's # system CPU time, +real+ as the elapsed real time and +label+ as the label. # def initialize(utime = 0.0, stime = 0.0, cutime = 0.0, cstime = 0.0, real = 0.0, label = nil) @utime, @stime, @cutime, @cstime, @real, @label = utime, stime, cutime, cstime, real, label.to_s @total = @utime + @stime + @cutime + @cstime end # # Returns a new Tms object whose times are the sum of the times for this # Tms object, plus the time required to execute the code block (+blk+). # def add(&blk) # :yield: self + Benchmark.measure(&blk) end # # An in-place version of #add. # def add!(&blk) t = Benchmark.measure(&blk) @utime = utime + t.utime @stime = stime + t.stime @cutime = cutime + t.cutime @cstime = cstime + t.cstime @real = real + t.real self end # # Returns a new Tms object obtained by memberwise summation # of the individual times for this Tms object with those of the other # Tms object. # This method and #/() are useful for taking statistics. # def +(other); memberwise(:+, other) end # # Returns a new Tms object obtained by memberwise subtraction # of the individual times for the other Tms object from those of this # Tms object. # def -(other); memberwise(:-, other) end # # Returns a new Tms object obtained by memberwise multiplication # of the individual times for this Tms object by _x_. # def *(x); memberwise(:*, x) end # # Returns a new Tms object obtained by memberwise division # of the individual times for this Tms object by _x_. # This method and #+() are useful for taking statistics. # def /(x); memberwise(:/, x) end # # Returns the contents of this Tms object as # a formatted string, according to a format string # like that passed to Kernel.format. In addition, #format # accepts the following extensions: # # <tt>%u</tt>:: Replaced by the user CPU time, as reported by Tms#utime. # <tt>%y</tt>:: Replaced by the system CPU time, as reported by #stime (Mnemonic: y of "s*y*stem") # <tt>%U</tt>:: Replaced by the children's user CPU time, as reported by Tms#cutime # <tt>%Y</tt>:: Replaced by the children's system CPU time, as reported by Tms#cstime # <tt>%t</tt>:: Replaced by the total CPU time, as reported by Tms#total # <tt>%r</tt>:: Replaced by the elapsed real time, as reported by Tms#real # <tt>%n</tt>:: Replaced by the label string, as reported by Tms#label (Mnemonic: n of "*n*ame") # # If _format_ is not given, FORMAT is used as default value, detailing the # user, system and real elapsed time. # def format(format = nil, *args) str = (format || FORMAT).dup .gsub(/(%[-+.\d]*)n/) { "#{$1}s" % label } .gsub(/(%[-+.\d]*)u/) { "#{$1}f" % utime } .gsub(/(%[-+.\d]*)y/) { "#{$1}f" % stime } .gsub(/(%[-+.\d]*)U/) { "#{$1}f" % cutime } .gsub(/(%[-+.\d]*)Y/) { "#{$1}f" % cstime } .gsub(/(%[-+.\d]*)t/) { "#{$1}f" % total } .gsub(/(%[-+.\d]*)r/) { "(#{$1}f)" % real } format ? str % args : str end # # Same as #format. # def to_s format end # # Returns a new 6-element array, consisting of the # label, user CPU time, system CPU time, children's # user CPU time, children's system CPU time and elapsed # real time. # def to_a [@label, @utime, @stime, @cutime, @cstime, @real] end # # Returns a hash containing the same data as `to_a`. # def to_h { label: @label, utime: @utime, stime: @stime, cutime: @cutime, cstime: @cstime, real: @real } end protected # # Returns a new Tms object obtained by memberwise operation +op+ # of the individual times for this Tms object with those of the other # Tms object. # # +op+ can be a mathematical operation such as <tt>+</tt>, <tt>-</tt>, # <tt>*</tt>, <tt>/</tt> # def memberwise(op, x) case x when Benchmark::Tms Benchmark::Tms.new(utime.__send__(op, x.utime), stime.__send__(op, x.stime), cutime.__send__(op, x.cutime), cstime.__send__(op, x.cstime), real.__send__(op, x.real) ) else Benchmark::Tms.new(utime.__send__(op, x), stime.__send__(op, x), cutime.__send__(op, x), cstime.__send__(op, x), real.__send__(op, x) ) end end end # The default caption string (heading above the output times). CAPTION = Benchmark::Tms::CAPTION # The default format string used to display times. See also Benchmark::Tms#format. FORMAT = Benchmark::Tms::FORMAT end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/math.rb
stdlib/math.rb
warn 'DEPRECATION: math is now part of the core library, requiring it is deprecated'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/set.rb
stdlib/set.rb
# Set has been moved to corelib
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/time.rb
stdlib/time.rb
# backtick_javascript: true class Time def self.parse(str) %x{ var d = Date.parse(str); if (d !== d) { // parsing failed, d is a NaN // probably str is not in ISO 8601 format, which is the only format, required to be supported by Javascript // try to make the format more like ISO or more like Chrome and parse again str = str.replace(/^(\d+)([\./])(\d+)([\./])?(\d+)?/, function(matched_sub, c1, c2, c3, c4, c5, offset, orig_string) { if ((c2 === c4) && c5) { // 2007.10.1 or 2007/10/1 are ok, but 2007/10.1 is not, convert to 2007-10-1 return c1 + '-' + c3 + '-' + c5; } else if (c3 && !c4) { // 2007.10 or 2007/10 // Chrome and Ruby can parse "2007/10", assuming its "2007-10-01", do the same return c1 + '-' + c3 + '-01'; }; return matched_sub; }); d = Date.parse(str); } return new Date(d); } end def self.def_formatter(name, format, on_utc: false, utc_tz: nil, tz_format: nil, fractions: false, on: self) on.define_method name do |fdigits = 0| case self when defined?(::DateTime) && ::DateTime date = on_utc ? new_offset(0) : self when defined?(::Date) && ::Date date = ::Time.utc(year, month, day) when ::Time date = on_utc ? getutc : self end str = date.strftime(format) str += date.strftime(".%#{fdigits}N") if fractions && fdigits > 0 if utc_tz str += utc ? utc_tz : date.strftime(tz_format) elsif tz_format str += date.strftime(tz_format) end str end end def_formatter :rfc2822, '%a, %d %b %Y %T ', utc_tz: '-00:00', tz_format: '%z' alias rfc822 rfc2822 def_formatter :httpdate, '%a, %d %b %Y %T GMT', on_utc: true def_formatter :xmlschema, '%FT%T', utc_tz: 'Z', tz_format: '%:z', fractions: true alias iso8601 xmlschema def to_date Date.wrap(self) end def to_datetime DateTime.wrap(self) end def to_time self end end require 'date'
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/file.rb
stdlib/file.rb
warn "File is already part of corelib now, you don't need to require it anymore."
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/fileutils.rb
stdlib/fileutils.rb
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/observer.rb
stdlib/observer.rb
# # Implementation of the _Observer_ object-oriented design pattern. The # following documentation is copied, with modifications, from "Programming # Ruby", by Hunt and Thomas; http://www.ruby-doc.org/docs/ProgrammingRuby/html/lib_patterns.html. # # See Observable for more info. # The Observer pattern (also known as publish/subscribe) provides a simple # mechanism for one object to inform a set of interested third-party objects # when its state changes. # # == Mechanism # # The notifying class mixes in the +Observable+ # module, which provides the methods for managing the associated observer # objects. # # The observers must implement a method called +update+ to receive # notifications. # # The observable object must: # * assert that it has +#changed+ # * call +#notify_observers+ # # === Example # # The following example demonstrates this nicely. A +Ticker+, when run, # continually receives the stock +Price+ for its <tt>@symbol</tt>. A +Warner+ # is a general observer of the price, and two warners are demonstrated, a # +WarnLow+ and a +WarnHigh+, which print a warning if the price is below or # above their set limits, respectively. # # The +update+ callback allows the warners to run without being explicitly # called. The system is set up with the +Ticker+ and several observers, and the # observers do their duty without the top-level code having to interfere. # # Note that the contract between publisher and subscriber (observable and # observer) is not declared or enforced. The +Ticker+ publishes a time and a # price, and the warners receive that. But if you don't ensure that your # contracts are correct, nothing else can warn you. # # require "observer" # # class Ticker ### Periodically fetch a stock price. # include Observable # # def initialize(symbol) # @symbol = symbol # end # # def run # lastPrice = nil # loop do # price = Price.fetch(@symbol) # print "Current price: #{price}\n" # if price != lastPrice # changed # notify observers # lastPrice = price # notify_observers(Time.now, price) # end # sleep 1 # end # end # end # # class Price ### A mock class to fetch a stock price (60 - 140). # def Price.fetch(symbol) # 60 + rand(80) # end # end # # class Warner ### An abstract observer of Ticker objects. # def initialize(ticker, limit) # @limit = limit # ticker.add_observer(self) # end # end # # class WarnLow < Warner # def update(time, price) # callback for observer # if price < @limit # print "--- #{time.to_s}: Price below #@limit: #{price}\n" # end # end # end # # class WarnHigh < Warner # def update(time, price) # callback for observer # if price > @limit # print "+++ #{time.to_s}: Price above #@limit: #{price}\n" # end # end # end # # ticker = Ticker.new("MSFT") # WarnLow.new(ticker, 80) # WarnHigh.new(ticker, 120) # ticker.run # # Produces: # # Current price: 83 # Current price: 75 # --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 75 # Current price: 90 # Current price: 134 # +++ Sun Jun 09 00:10:25 CDT 2002: Price above 120: 134 # Current price: 134 # Current price: 112 # Current price: 79 # --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 79 module Observable # # Add +observer+ as an observer on this object. so that it will receive # notifications. # # +observer+:: the object that will be notified of changes. # +func+:: Symbol naming the method that will be called when this Observable # has changes. # # This method must return true for +observer.respond_to?+ and will # receive <tt>*arg</tt> when #notify_observers is called, where # <tt>*arg</tt> is the value passed to #notify_observers by this # Observable def add_observer(observer, func=:update) @observer_peers = {} unless defined? @observer_peers unless observer.respond_to? func raise NoMethodError.new("observer does not respond to `#{func.to_s}'", func.to_s) end @observer_peers[observer] = func end # # Remove +observer+ as an observer on this object so that it will no longer # receive notifications. # # +observer+:: An observer of this Observable def delete_observer(observer) @observer_peers.delete observer if defined? @observer_peers end # # Remove all observers associated with this object. # def delete_observers @observer_peers.clear if defined? @observer_peers end # # Return the number of observers associated with this object. # def count_observers if defined? @observer_peers @observer_peers.size else 0 end end # # Set the changed state of this object. Notifications will be sent only if # the changed +state+ is +true+. # # +state+:: Boolean indicating the changed state of this Observable. # def changed(state=true) @observer_state = state end # # Returns true if this object's state has been changed since the last # #notify_observers call. # def changed? if defined? @observer_state and @observer_state true else false end end # # Notify observers of a change in state *if* this object's changed state is # +true+. # # This will invoke the method named in #add_observer, passing <tt>*arg</tt>. # The changed state is then set to +false+. # # <tt>*arg</tt>:: Any arguments to pass to the observers. def notify_observers(*arg) if defined? @observer_state and @observer_state if defined? @observer_peers @observer_peers.each do |k, v| k.send v, *arg end end @observer_state = false end end end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/yaml.rb
stdlib/yaml.rb
warn "REMOVED: use `require 'nodejs/yaml'` instead"
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/console.rb
stdlib/console.rb
# backtick_javascript: true require 'native' # Manipulate the browser console. # # @see https://developer.mozilla.org/en-US/docs/Web/API/console class Console include Native::Wrapper # Clear the console. def clear `#{@native}.clear()` end # Print a stacktrace from the call site. def trace `#{@native}.trace()` end # Log the passed objects based on an optional initial format. def log(*args) `#{@native}.log.apply(#{@native}, args)` end # Log the passed objects based on an optional initial format as informational # log. def info(*args) `#{@native}.info.apply(#{@native}, args)` end # Log the passed objects based on an optional initial format as warning. def warn(*args) `#{@native}.warn.apply(#{@native}, args)` end # Log the passed objects based on an optional initial format as error. def error(*args) `#{@native}.error.apply(#{@native}, args)` end # Time the given block with the given label. def time(label, &block) raise ArgumentError, 'no block given' unless block `#{@native}.time(label)` begin if block.arity == 0 instance_exec(&block) else yield(self) end ensure `#{@native}.timeEnd()` end end # Group the given block. def group(*args, &block) raise ArgumentError, 'no block given' unless block `#{@native}.group.apply(#{@native}, args)` begin if block.arity == 0 instance_exec(&block) else yield(self) end ensure `#{@native}.groupEnd()` end end # Group the given block but collapse it. def group!(*args, &block) return unless block_given? `#{@native}.groupCollapsed.apply(#{@native}, args)` begin if block.arity == 0 instance_exec(&block) else yield(self) end ensure `#{@native}.groupEnd()` end end end if defined?(`Opal.global.console`) $console = Console.new(`Opal.global.console`) end
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false
opal/opal
https://github.com/opal/opal/blob/b4e228990534515b83cd509a9297beca59bf8733/stdlib/iconv.rb
stdlib/iconv.rb
ruby
MIT
b4e228990534515b83cd509a9297beca59bf8733
2026-01-04T15:44:44.154940Z
false